cc: Added inline to Tile::IsReadyToDraw
[chromium-blink-merge.git] / third_party / sqlite / amalgamation / sqlite3.c
blobebae3286cbb2c4f0dd0998afa9432aed347d2daf
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
6954 /* Begin recover.patch for Chromium */
6956 ** Call to initialize the recover virtual-table modules (see recover.c).
6958 ** This could be loaded by default in main.c, but that would make the
6959 ** virtual table available to Web SQL. Breaking it out allows only
6960 ** selected users to enable it (currently sql/recovery.cc).
6962 int recoverVtableInit(sqlite3 *db);
6963 /* End recover.patch for Chromium */
6966 ** Undo the hack that converts floating point types to integer for
6967 ** builds on processors without floating point support.
6969 #ifdef SQLITE_OMIT_FLOATING_POINT
6970 # undef double
6971 #endif
6973 #if 0
6974 } /* End of the 'extern "C"' block */
6975 #endif
6976 #endif
6979 ** 2010 August 30
6981 ** The author disclaims copyright to this source code. In place of
6982 ** a legal notice, here is a blessing:
6984 ** May you do good and not evil.
6985 ** May you find forgiveness for yourself and forgive others.
6986 ** May you share freely, never taking more than you give.
6988 *************************************************************************
6991 #ifndef _SQLITE3RTREE_H_
6992 #define _SQLITE3RTREE_H_
6995 #if 0
6996 extern "C" {
6997 #endif
6999 typedef struct sqlite3_rtree_geometry sqlite3_rtree_geometry;
7002 ** Register a geometry callback named zGeom that can be used as part of an
7003 ** R-Tree geometry query as follows:
7005 ** SELECT ... FROM <rtree> WHERE <rtree col> MATCH $zGeom(... params ...)
7007 SQLITE_API int sqlite3_rtree_geometry_callback(
7008 sqlite3 *db,
7009 const char *zGeom,
7010 int (*xGeom)(sqlite3_rtree_geometry *, int nCoord, double *aCoord, int *pRes),
7011 void *pContext
7016 ** A pointer to a structure of the following type is passed as the first
7017 ** argument to callbacks registered using rtree_geometry_callback().
7019 struct sqlite3_rtree_geometry {
7020 void *pContext; /* Copy of pContext passed to s_r_g_c() */
7021 int nParam; /* Size of array aParam[] */
7022 double *aParam; /* Parameters passed to SQL geom function */
7023 void *pUser; /* Callback implementation user data */
7024 void (*xDelUser)(void *); /* Called by SQLite to clean up pUser */
7028 #if 0
7029 } /* end of the 'extern "C"' block */
7030 #endif
7032 #endif /* ifndef _SQLITE3RTREE_H_ */
7035 /************** End of sqlite3.h *********************************************/
7036 /************** Continuing where we left off in sqliteInt.h ******************/
7037 /************** Include hash.h in the middle of sqliteInt.h ******************/
7038 /************** Begin file hash.h ********************************************/
7040 ** 2001 September 22
7042 ** The author disclaims copyright to this source code. In place of
7043 ** a legal notice, here is a blessing:
7045 ** May you do good and not evil.
7046 ** May you find forgiveness for yourself and forgive others.
7047 ** May you share freely, never taking more than you give.
7049 *************************************************************************
7050 ** This is the header file for the generic hash-table implemenation
7051 ** used in SQLite.
7053 #ifndef _SQLITE_HASH_H_
7054 #define _SQLITE_HASH_H_
7056 /* Forward declarations of structures. */
7057 typedef struct Hash Hash;
7058 typedef struct HashElem HashElem;
7060 /* A complete hash table is an instance of the following structure.
7061 ** The internals of this structure are intended to be opaque -- client
7062 ** code should not attempt to access or modify the fields of this structure
7063 ** directly. Change this structure only by using the routines below.
7064 ** However, some of the "procedures" and "functions" for modifying and
7065 ** accessing this structure are really macros, so we can't really make
7066 ** this structure opaque.
7068 ** All elements of the hash table are on a single doubly-linked list.
7069 ** Hash.first points to the head of this list.
7071 ** There are Hash.htsize buckets. Each bucket points to a spot in
7072 ** the global doubly-linked list. The contents of the bucket are the
7073 ** element pointed to plus the next _ht.count-1 elements in the list.
7075 ** Hash.htsize and Hash.ht may be zero. In that case lookup is done
7076 ** by a linear search of the global list. For small tables, the
7077 ** Hash.ht table is never allocated because if there are few elements
7078 ** in the table, it is faster to do a linear search than to manage
7079 ** the hash table.
7081 struct Hash {
7082 unsigned int htsize; /* Number of buckets in the hash table */
7083 unsigned int count; /* Number of entries in this table */
7084 HashElem *first; /* The first element of the array */
7085 struct _ht { /* the hash table */
7086 int count; /* Number of entries with this hash */
7087 HashElem *chain; /* Pointer to first entry with this hash */
7088 } *ht;
7091 /* Each element in the hash table is an instance of the following
7092 ** structure. All elements are stored on a single doubly-linked list.
7094 ** Again, this structure is intended to be opaque, but it can't really
7095 ** be opaque because it is used by macros.
7097 struct HashElem {
7098 HashElem *next, *prev; /* Next and previous elements in the table */
7099 void *data; /* Data associated with this element */
7100 const char *pKey; int nKey; /* Key associated with this element */
7104 ** Access routines. To delete, insert a NULL pointer.
7106 SQLITE_PRIVATE void sqlite3HashInit(Hash*);
7107 SQLITE_PRIVATE void *sqlite3HashInsert(Hash*, const char *pKey, int nKey, void *pData);
7108 SQLITE_PRIVATE void *sqlite3HashFind(const Hash*, const char *pKey, int nKey);
7109 SQLITE_PRIVATE void sqlite3HashClear(Hash*);
7112 ** Macros for looping over all elements of a hash table. The idiom is
7113 ** like this:
7115 ** Hash h;
7116 ** HashElem *p;
7117 ** ...
7118 ** for(p=sqliteHashFirst(&h); p; p=sqliteHashNext(p)){
7119 ** SomeStructure *pData = sqliteHashData(p);
7120 ** // do something with pData
7121 ** }
7123 #define sqliteHashFirst(H) ((H)->first)
7124 #define sqliteHashNext(E) ((E)->next)
7125 #define sqliteHashData(E) ((E)->data)
7126 /* #define sqliteHashKey(E) ((E)->pKey) // NOT USED */
7127 /* #define sqliteHashKeysize(E) ((E)->nKey) // NOT USED */
7130 ** Number of entries in a hash table
7132 /* #define sqliteHashCount(H) ((H)->count) // NOT USED */
7134 #endif /* _SQLITE_HASH_H_ */
7136 /************** End of hash.h ************************************************/
7137 /************** Continuing where we left off in sqliteInt.h ******************/
7138 /************** Include parse.h in the middle of sqliteInt.h *****************/
7139 /************** Begin file parse.h *******************************************/
7140 #define TK_SEMI 1
7141 #define TK_EXPLAIN 2
7142 #define TK_QUERY 3
7143 #define TK_PLAN 4
7144 #define TK_BEGIN 5
7145 #define TK_TRANSACTION 6
7146 #define TK_DEFERRED 7
7147 #define TK_IMMEDIATE 8
7148 #define TK_EXCLUSIVE 9
7149 #define TK_COMMIT 10
7150 #define TK_END 11
7151 #define TK_ROLLBACK 12
7152 #define TK_SAVEPOINT 13
7153 #define TK_RELEASE 14
7154 #define TK_TO 15
7155 #define TK_TABLE 16
7156 #define TK_CREATE 17
7157 #define TK_IF 18
7158 #define TK_NOT 19
7159 #define TK_EXISTS 20
7160 #define TK_TEMP 21
7161 #define TK_LP 22
7162 #define TK_RP 23
7163 #define TK_AS 24
7164 #define TK_COMMA 25
7165 #define TK_ID 26
7166 #define TK_INDEXED 27
7167 #define TK_ABORT 28
7168 #define TK_ACTION 29
7169 #define TK_AFTER 30
7170 #define TK_ANALYZE 31
7171 #define TK_ASC 32
7172 #define TK_ATTACH 33
7173 #define TK_BEFORE 34
7174 #define TK_BY 35
7175 #define TK_CASCADE 36
7176 #define TK_CAST 37
7177 #define TK_COLUMNKW 38
7178 #define TK_CONFLICT 39
7179 #define TK_DATABASE 40
7180 #define TK_DESC 41
7181 #define TK_DETACH 42
7182 #define TK_EACH 43
7183 #define TK_FAIL 44
7184 #define TK_FOR 45
7185 #define TK_IGNORE 46
7186 #define TK_INITIALLY 47
7187 #define TK_INSTEAD 48
7188 #define TK_LIKE_KW 49
7189 #define TK_MATCH 50
7190 #define TK_NO 51
7191 #define TK_KEY 52
7192 #define TK_OF 53
7193 #define TK_OFFSET 54
7194 #define TK_PRAGMA 55
7195 #define TK_RAISE 56
7196 #define TK_REPLACE 57
7197 #define TK_RESTRICT 58
7198 #define TK_ROW 59
7199 #define TK_TRIGGER 60
7200 #define TK_VACUUM 61
7201 #define TK_VIEW 62
7202 #define TK_VIRTUAL 63
7203 #define TK_REINDEX 64
7204 #define TK_RENAME 65
7205 #define TK_CTIME_KW 66
7206 #define TK_ANY 67
7207 #define TK_OR 68
7208 #define TK_AND 69
7209 #define TK_IS 70
7210 #define TK_BETWEEN 71
7211 #define TK_IN 72
7212 #define TK_ISNULL 73
7213 #define TK_NOTNULL 74
7214 #define TK_NE 75
7215 #define TK_EQ 76
7216 #define TK_GT 77
7217 #define TK_LE 78
7218 #define TK_LT 79
7219 #define TK_GE 80
7220 #define TK_ESCAPE 81
7221 #define TK_BITAND 82
7222 #define TK_BITOR 83
7223 #define TK_LSHIFT 84
7224 #define TK_RSHIFT 85
7225 #define TK_PLUS 86
7226 #define TK_MINUS 87
7227 #define TK_STAR 88
7228 #define TK_SLASH 89
7229 #define TK_REM 90
7230 #define TK_CONCAT 91
7231 #define TK_COLLATE 92
7232 #define TK_BITNOT 93
7233 #define TK_STRING 94
7234 #define TK_JOIN_KW 95
7235 #define TK_CONSTRAINT 96
7236 #define TK_DEFAULT 97
7237 #define TK_NULL 98
7238 #define TK_PRIMARY 99
7239 #define TK_UNIQUE 100
7240 #define TK_CHECK 101
7241 #define TK_REFERENCES 102
7242 #define TK_AUTOINCR 103
7243 #define TK_ON 104
7244 #define TK_INSERT 105
7245 #define TK_DELETE 106
7246 #define TK_UPDATE 107
7247 #define TK_SET 108
7248 #define TK_DEFERRABLE 109
7249 #define TK_FOREIGN 110
7250 #define TK_DROP 111
7251 #define TK_UNION 112
7252 #define TK_ALL 113
7253 #define TK_EXCEPT 114
7254 #define TK_INTERSECT 115
7255 #define TK_SELECT 116
7256 #define TK_DISTINCT 117
7257 #define TK_DOT 118
7258 #define TK_FROM 119
7259 #define TK_JOIN 120
7260 #define TK_USING 121
7261 #define TK_ORDER 122
7262 #define TK_GROUP 123
7263 #define TK_HAVING 124
7264 #define TK_LIMIT 125
7265 #define TK_WHERE 126
7266 #define TK_INTO 127
7267 #define TK_VALUES 128
7268 #define TK_INTEGER 129
7269 #define TK_FLOAT 130
7270 #define TK_BLOB 131
7271 #define TK_REGISTER 132
7272 #define TK_VARIABLE 133
7273 #define TK_CASE 134
7274 #define TK_WHEN 135
7275 #define TK_THEN 136
7276 #define TK_ELSE 137
7277 #define TK_INDEX 138
7278 #define TK_ALTER 139
7279 #define TK_ADD 140
7280 #define TK_TO_TEXT 141
7281 #define TK_TO_BLOB 142
7282 #define TK_TO_NUMERIC 143
7283 #define TK_TO_INT 144
7284 #define TK_TO_REAL 145
7285 #define TK_ISNOT 146
7286 #define TK_END_OF_FILE 147
7287 #define TK_ILLEGAL 148
7288 #define TK_SPACE 149
7289 #define TK_UNCLOSED_STRING 150
7290 #define TK_FUNCTION 151
7291 #define TK_COLUMN 152
7292 #define TK_AGG_FUNCTION 153
7293 #define TK_AGG_COLUMN 154
7294 #define TK_CONST_FUNC 155
7295 #define TK_UMINUS 156
7296 #define TK_UPLUS 157
7298 /************** End of parse.h ***********************************************/
7299 /************** Continuing where we left off in sqliteInt.h ******************/
7300 #include <stdio.h>
7301 #include <stdlib.h>
7302 #include <string.h>
7303 #include <assert.h>
7304 #include <stddef.h>
7307 ** If compiling for a processor that lacks floating point support,
7308 ** substitute integer for floating-point
7310 #ifdef SQLITE_OMIT_FLOATING_POINT
7311 # define double sqlite_int64
7312 # define float sqlite_int64
7313 # define LONGDOUBLE_TYPE sqlite_int64
7314 # ifndef SQLITE_BIG_DBL
7315 # define SQLITE_BIG_DBL (((sqlite3_int64)1)<<50)
7316 # endif
7317 # define SQLITE_OMIT_DATETIME_FUNCS 1
7318 # define SQLITE_OMIT_TRACE 1
7319 # undef SQLITE_MIXED_ENDIAN_64BIT_FLOAT
7320 # undef SQLITE_HAVE_ISNAN
7321 #endif
7322 #ifndef SQLITE_BIG_DBL
7323 # define SQLITE_BIG_DBL (1e99)
7324 #endif
7327 ** OMIT_TEMPDB is set to 1 if SQLITE_OMIT_TEMPDB is defined, or 0
7328 ** afterward. Having this macro allows us to cause the C compiler
7329 ** to omit code used by TEMP tables without messy #ifndef statements.
7331 #ifdef SQLITE_OMIT_TEMPDB
7332 #define OMIT_TEMPDB 1
7333 #else
7334 #define OMIT_TEMPDB 0
7335 #endif
7338 ** The "file format" number is an integer that is incremented whenever
7339 ** the VDBE-level file format changes. The following macros define the
7340 ** the default file format for new databases and the maximum file format
7341 ** that the library can read.
7343 #define SQLITE_MAX_FILE_FORMAT 4
7344 #ifndef SQLITE_DEFAULT_FILE_FORMAT
7345 # define SQLITE_DEFAULT_FILE_FORMAT 1
7346 #endif
7349 ** Determine whether triggers are recursive by default. This can be
7350 ** changed at run-time using a pragma.
7352 #ifndef SQLITE_DEFAULT_RECURSIVE_TRIGGERS
7353 # define SQLITE_DEFAULT_RECURSIVE_TRIGGERS 0
7354 #endif
7357 ** Provide a default value for SQLITE_TEMP_STORE in case it is not specified
7358 ** on the command-line
7360 #ifndef SQLITE_TEMP_STORE
7361 # define SQLITE_TEMP_STORE 1
7362 #endif
7365 ** GCC does not define the offsetof() macro so we'll have to do it
7366 ** ourselves.
7368 #ifndef offsetof
7369 #define offsetof(STRUCTURE,FIELD) ((int)((char*)&((STRUCTURE*)0)->FIELD))
7370 #endif
7373 ** Check to see if this machine uses EBCDIC. (Yes, believe it or
7374 ** not, there are still machines out there that use EBCDIC.)
7376 #if 'A' == '\301'
7377 # define SQLITE_EBCDIC 1
7378 #else
7379 # define SQLITE_ASCII 1
7380 #endif
7383 ** Integers of known sizes. These typedefs might change for architectures
7384 ** where the sizes very. Preprocessor macros are available so that the
7385 ** types can be conveniently redefined at compile-type. Like this:
7387 ** cc '-DUINTPTR_TYPE=long long int' ...
7389 #ifndef UINT32_TYPE
7390 # ifdef HAVE_UINT32_T
7391 # define UINT32_TYPE uint32_t
7392 # else
7393 # define UINT32_TYPE unsigned int
7394 # endif
7395 #endif
7396 #ifndef UINT16_TYPE
7397 # ifdef HAVE_UINT16_T
7398 # define UINT16_TYPE uint16_t
7399 # else
7400 # define UINT16_TYPE unsigned short int
7401 # endif
7402 #endif
7403 #ifndef INT16_TYPE
7404 # ifdef HAVE_INT16_T
7405 # define INT16_TYPE int16_t
7406 # else
7407 # define INT16_TYPE short int
7408 # endif
7409 #endif
7410 #ifndef UINT8_TYPE
7411 # ifdef HAVE_UINT8_T
7412 # define UINT8_TYPE uint8_t
7413 # else
7414 # define UINT8_TYPE unsigned char
7415 # endif
7416 #endif
7417 #ifndef INT8_TYPE
7418 # ifdef HAVE_INT8_T
7419 # define INT8_TYPE int8_t
7420 # else
7421 # define INT8_TYPE signed char
7422 # endif
7423 #endif
7424 #ifndef LONGDOUBLE_TYPE
7425 # define LONGDOUBLE_TYPE long double
7426 #endif
7427 typedef sqlite_int64 i64; /* 8-byte signed integer */
7428 typedef sqlite_uint64 u64; /* 8-byte unsigned integer */
7429 typedef UINT32_TYPE u32; /* 4-byte unsigned integer */
7430 typedef UINT16_TYPE u16; /* 2-byte unsigned integer */
7431 typedef INT16_TYPE i16; /* 2-byte signed integer */
7432 typedef UINT8_TYPE u8; /* 1-byte unsigned integer */
7433 typedef INT8_TYPE i8; /* 1-byte signed integer */
7436 ** SQLITE_MAX_U32 is a u64 constant that is the maximum u64 value
7437 ** that can be stored in a u32 without loss of data. The value
7438 ** is 0x00000000ffffffff. But because of quirks of some compilers, we
7439 ** have to specify the value in the less intuitive manner shown:
7441 #define SQLITE_MAX_U32 ((((u64)1)<<32)-1)
7444 ** Macros to determine whether the machine is big or little endian,
7445 ** evaluated at runtime.
7447 #ifdef SQLITE_AMALGAMATION
7448 SQLITE_PRIVATE const int sqlite3one = 1;
7449 #else
7450 SQLITE_PRIVATE const int sqlite3one;
7451 #endif
7452 #if defined(i386) || defined(__i386__) || defined(_M_IX86)\
7453 || defined(__x86_64) || defined(__x86_64__)
7454 # define SQLITE_BIGENDIAN 0
7455 # define SQLITE_LITTLEENDIAN 1
7456 # define SQLITE_UTF16NATIVE SQLITE_UTF16LE
7457 #else
7458 # define SQLITE_BIGENDIAN (*(char *)(&sqlite3one)==0)
7459 # define SQLITE_LITTLEENDIAN (*(char *)(&sqlite3one)==1)
7460 # define SQLITE_UTF16NATIVE (SQLITE_BIGENDIAN?SQLITE_UTF16BE:SQLITE_UTF16LE)
7461 #endif
7464 ** Constants for the largest and smallest possible 64-bit signed integers.
7465 ** These macros are designed to work correctly on both 32-bit and 64-bit
7466 ** compilers.
7468 #define LARGEST_INT64 (0xffffffff|(((i64)0x7fffffff)<<32))
7469 #define SMALLEST_INT64 (((i64)-1) - LARGEST_INT64)
7472 ** Round up a number to the next larger multiple of 8. This is used
7473 ** to force 8-byte alignment on 64-bit architectures.
7475 #define ROUND8(x) (((x)+7)&~7)
7478 ** Round down to the nearest multiple of 8
7480 #define ROUNDDOWN8(x) ((x)&~7)
7483 ** Assert that the pointer X is aligned to an 8-byte boundary. This
7484 ** macro is used only within assert() to verify that the code gets
7485 ** all alignment restrictions correct.
7487 ** Except, if SQLITE_4_BYTE_ALIGNED_MALLOC is defined, then the
7488 ** underlying malloc() implemention might return us 4-byte aligned
7489 ** pointers. In that case, only verify 4-byte alignment.
7491 #ifdef SQLITE_4_BYTE_ALIGNED_MALLOC
7492 # define EIGHT_BYTE_ALIGNMENT(X) ((((char*)(X) - (char*)0)&3)==0)
7493 #else
7494 # define EIGHT_BYTE_ALIGNMENT(X) ((((char*)(X) - (char*)0)&7)==0)
7495 #endif
7499 ** An instance of the following structure is used to store the busy-handler
7500 ** callback for a given sqlite handle.
7502 ** The sqlite.busyHandler member of the sqlite struct contains the busy
7503 ** callback for the database handle. Each pager opened via the sqlite
7504 ** handle is passed a pointer to sqlite.busyHandler. The busy-handler
7505 ** callback is currently invoked only from within pager.c.
7507 typedef struct BusyHandler BusyHandler;
7508 struct BusyHandler {
7509 int (*xFunc)(void *,int); /* The busy callback */
7510 void *pArg; /* First arg to busy callback */
7511 int nBusy; /* Incremented with each busy call */
7515 ** Name of the master database table. The master database table
7516 ** is a special table that holds the names and attributes of all
7517 ** user tables and indices.
7519 #define MASTER_NAME "sqlite_master"
7520 #define TEMP_MASTER_NAME "sqlite_temp_master"
7523 ** The root-page of the master database table.
7525 #define MASTER_ROOT 1
7528 ** The name of the schema table.
7530 #define SCHEMA_TABLE(x) ((!OMIT_TEMPDB)&&(x==1)?TEMP_MASTER_NAME:MASTER_NAME)
7533 ** A convenience macro that returns the number of elements in
7534 ** an array.
7536 #define ArraySize(X) ((int)(sizeof(X)/sizeof(X[0])))
7539 ** The following value as a destructor means to use sqlite3DbFree().
7540 ** This is an internal extension to SQLITE_STATIC and SQLITE_TRANSIENT.
7542 #define SQLITE_DYNAMIC ((sqlite3_destructor_type)sqlite3DbFree)
7545 ** When SQLITE_OMIT_WSD is defined, it means that the target platform does
7546 ** not support Writable Static Data (WSD) such as global and static variables.
7547 ** All variables must either be on the stack or dynamically allocated from
7548 ** the heap. When WSD is unsupported, the variable declarations scattered
7549 ** throughout the SQLite code must become constants instead. The SQLITE_WSD
7550 ** macro is used for this purpose. And instead of referencing the variable
7551 ** directly, we use its constant as a key to lookup the run-time allocated
7552 ** buffer that holds real variable. The constant is also the initializer
7553 ** for the run-time allocated buffer.
7555 ** In the usual case where WSD is supported, the SQLITE_WSD and GLOBAL
7556 ** macros become no-ops and have zero performance impact.
7558 #ifdef SQLITE_OMIT_WSD
7559 #define SQLITE_WSD const
7560 #define GLOBAL(t,v) (*(t*)sqlite3_wsd_find((void*)&(v), sizeof(v)))
7561 #define sqlite3GlobalConfig GLOBAL(struct Sqlite3Config, sqlite3Config)
7562 SQLITE_API int sqlite3_wsd_init(int N, int J);
7563 SQLITE_API void *sqlite3_wsd_find(void *K, int L);
7564 #else
7565 #define SQLITE_WSD
7566 #define GLOBAL(t,v) v
7567 #define sqlite3GlobalConfig sqlite3Config
7568 #endif
7571 ** The following macros are used to suppress compiler warnings and to
7572 ** make it clear to human readers when a function parameter is deliberately
7573 ** left unused within the body of a function. This usually happens when
7574 ** a function is called via a function pointer. For example the
7575 ** implementation of an SQL aggregate step callback may not use the
7576 ** parameter indicating the number of arguments passed to the aggregate,
7577 ** if it knows that this is enforced elsewhere.
7579 ** When a function parameter is not used at all within the body of a function,
7580 ** it is generally named "NotUsed" or "NotUsed2" to make things even clearer.
7581 ** However, these macros may also be used to suppress warnings related to
7582 ** parameters that may or may not be used depending on compilation options.
7583 ** For example those parameters only used in assert() statements. In these
7584 ** cases the parameters are named as per the usual conventions.
7586 #define UNUSED_PARAMETER(x) (void)(x)
7587 #define UNUSED_PARAMETER2(x,y) UNUSED_PARAMETER(x),UNUSED_PARAMETER(y)
7590 ** Forward references to structures
7592 typedef struct AggInfo AggInfo;
7593 typedef struct AuthContext AuthContext;
7594 typedef struct AutoincInfo AutoincInfo;
7595 typedef struct Bitvec Bitvec;
7596 typedef struct CollSeq CollSeq;
7597 typedef struct Column Column;
7598 typedef struct Db Db;
7599 typedef struct Schema Schema;
7600 typedef struct Expr Expr;
7601 typedef struct ExprList ExprList;
7602 typedef struct ExprSpan ExprSpan;
7603 typedef struct FKey FKey;
7604 typedef struct FuncDestructor FuncDestructor;
7605 typedef struct FuncDef FuncDef;
7606 typedef struct FuncDefHash FuncDefHash;
7607 typedef struct IdList IdList;
7608 typedef struct Index Index;
7609 typedef struct IndexSample IndexSample;
7610 typedef struct KeyClass KeyClass;
7611 typedef struct KeyInfo KeyInfo;
7612 typedef struct Lookaside Lookaside;
7613 typedef struct LookasideSlot LookasideSlot;
7614 typedef struct Module Module;
7615 typedef struct NameContext NameContext;
7616 typedef struct Parse Parse;
7617 typedef struct RowSet RowSet;
7618 typedef struct Savepoint Savepoint;
7619 typedef struct Select Select;
7620 typedef struct SrcList SrcList;
7621 typedef struct StrAccum StrAccum;
7622 typedef struct Table Table;
7623 typedef struct TableLock TableLock;
7624 typedef struct Token Token;
7625 typedef struct Trigger Trigger;
7626 typedef struct TriggerPrg TriggerPrg;
7627 typedef struct TriggerStep TriggerStep;
7628 typedef struct UnpackedRecord UnpackedRecord;
7629 typedef struct VTable VTable;
7630 typedef struct Walker Walker;
7631 typedef struct WherePlan WherePlan;
7632 typedef struct WhereInfo WhereInfo;
7633 typedef struct WhereLevel WhereLevel;
7636 ** Defer sourcing vdbe.h and btree.h until after the "u8" and
7637 ** "BusyHandler" typedefs. vdbe.h also requires a few of the opaque
7638 ** pointer types (i.e. FuncDef) defined above.
7640 /************** Include btree.h in the middle of sqliteInt.h *****************/
7641 /************** Begin file btree.h *******************************************/
7643 ** 2001 September 15
7645 ** The author disclaims copyright to this source code. In place of
7646 ** a legal notice, here is a blessing:
7648 ** May you do good and not evil.
7649 ** May you find forgiveness for yourself and forgive others.
7650 ** May you share freely, never taking more than you give.
7652 *************************************************************************
7653 ** This header file defines the interface that the sqlite B-Tree file
7654 ** subsystem. See comments in the source code for a detailed description
7655 ** of what each interface routine does.
7657 #ifndef _BTREE_H_
7658 #define _BTREE_H_
7660 /* TODO: This definition is just included so other modules compile. It
7661 ** needs to be revisited.
7663 #define SQLITE_N_BTREE_META 10
7666 ** If defined as non-zero, auto-vacuum is enabled by default. Otherwise
7667 ** it must be turned on for each database using "PRAGMA auto_vacuum = 1".
7669 #ifndef SQLITE_DEFAULT_AUTOVACUUM
7670 #define SQLITE_DEFAULT_AUTOVACUUM 0
7671 #endif
7673 #define BTREE_AUTOVACUUM_NONE 0 /* Do not do auto-vacuum */
7674 #define BTREE_AUTOVACUUM_FULL 1 /* Do full auto-vacuum */
7675 #define BTREE_AUTOVACUUM_INCR 2 /* Incremental vacuum */
7678 ** Forward declarations of structure
7680 typedef struct Btree Btree;
7681 typedef struct BtCursor BtCursor;
7682 typedef struct BtShared BtShared;
7685 SQLITE_PRIVATE int sqlite3BtreeOpen(
7686 const char *zFilename, /* Name of database file to open */
7687 sqlite3 *db, /* Associated database connection */
7688 Btree **ppBtree, /* Return open Btree* here */
7689 int flags, /* Flags */
7690 int vfsFlags /* Flags passed through to VFS open */
7693 /* The flags parameter to sqlite3BtreeOpen can be the bitwise or of the
7694 ** following values.
7696 ** NOTE: These values must match the corresponding PAGER_ values in
7697 ** pager.h.
7699 #define BTREE_OMIT_JOURNAL 1 /* Do not create or use a rollback journal */
7700 #define BTREE_NO_READLOCK 2 /* Omit readlocks on readonly files */
7701 #define BTREE_MEMORY 4 /* This is an in-memory DB */
7702 #define BTREE_SINGLE 8 /* The file contains at most 1 b-tree */
7703 #define BTREE_UNORDERED 16 /* Use of a hash implementation is OK */
7705 SQLITE_PRIVATE int sqlite3BtreeClose(Btree*);
7706 SQLITE_PRIVATE int sqlite3BtreeSetCacheSize(Btree*,int);
7707 SQLITE_PRIVATE int sqlite3BtreeSetSafetyLevel(Btree*,int,int,int);
7708 SQLITE_PRIVATE int sqlite3BtreeSyncDisabled(Btree*);
7709 SQLITE_PRIVATE int sqlite3BtreeSetPageSize(Btree *p, int nPagesize, int nReserve, int eFix);
7710 SQLITE_PRIVATE int sqlite3BtreeGetPageSize(Btree*);
7711 SQLITE_PRIVATE int sqlite3BtreeMaxPageCount(Btree*,int);
7712 SQLITE_PRIVATE u32 sqlite3BtreeLastPage(Btree*);
7713 SQLITE_PRIVATE int sqlite3BtreeSecureDelete(Btree*,int);
7714 SQLITE_PRIVATE int sqlite3BtreeGetReserve(Btree*);
7715 SQLITE_PRIVATE int sqlite3BtreeSetAutoVacuum(Btree *, int);
7716 SQLITE_PRIVATE int sqlite3BtreeGetAutoVacuum(Btree *);
7717 SQLITE_PRIVATE int sqlite3BtreeBeginTrans(Btree*,int);
7718 SQLITE_PRIVATE int sqlite3BtreeCommitPhaseOne(Btree*, const char *zMaster);
7719 SQLITE_PRIVATE int sqlite3BtreeCommitPhaseTwo(Btree*, int);
7720 SQLITE_PRIVATE int sqlite3BtreeCommit(Btree*);
7721 SQLITE_PRIVATE int sqlite3BtreeRollback(Btree*);
7722 SQLITE_PRIVATE int sqlite3BtreeBeginStmt(Btree*,int);
7723 SQLITE_PRIVATE int sqlite3BtreeCreateTable(Btree*, int*, int flags);
7724 SQLITE_PRIVATE int sqlite3BtreeIsInTrans(Btree*);
7725 SQLITE_PRIVATE int sqlite3BtreeIsInReadTrans(Btree*);
7726 SQLITE_PRIVATE int sqlite3BtreeIsInBackup(Btree*);
7727 SQLITE_PRIVATE void *sqlite3BtreeSchema(Btree *, int, void(*)(void *));
7728 SQLITE_PRIVATE int sqlite3BtreeSchemaLocked(Btree *pBtree);
7729 SQLITE_PRIVATE int sqlite3BtreeLockTable(Btree *pBtree, int iTab, u8 isWriteLock);
7730 SQLITE_PRIVATE int sqlite3BtreeSavepoint(Btree *, int, int);
7732 SQLITE_PRIVATE const char *sqlite3BtreeGetFilename(Btree *);
7733 SQLITE_PRIVATE const char *sqlite3BtreeGetJournalname(Btree *);
7734 SQLITE_PRIVATE int sqlite3BtreeCopyFile(Btree *, Btree *);
7736 SQLITE_PRIVATE int sqlite3BtreeIncrVacuum(Btree *);
7738 /* The flags parameter to sqlite3BtreeCreateTable can be the bitwise OR
7739 ** of the flags shown below.
7741 ** Every SQLite table must have either BTREE_INTKEY or BTREE_BLOBKEY set.
7742 ** With BTREE_INTKEY, the table key is a 64-bit integer and arbitrary data
7743 ** is stored in the leaves. (BTREE_INTKEY is used for SQL tables.) With
7744 ** BTREE_BLOBKEY, the key is an arbitrary BLOB and no content is stored
7745 ** anywhere - the key is the content. (BTREE_BLOBKEY is used for SQL
7746 ** indices.)
7748 #define BTREE_INTKEY 1 /* Table has only 64-bit signed integer keys */
7749 #define BTREE_BLOBKEY 2 /* Table has keys only - no data */
7751 SQLITE_PRIVATE int sqlite3BtreeDropTable(Btree*, int, int*);
7752 SQLITE_PRIVATE int sqlite3BtreeClearTable(Btree*, int, int*);
7753 SQLITE_PRIVATE void sqlite3BtreeTripAllCursors(Btree*, int);
7755 SQLITE_PRIVATE void sqlite3BtreeGetMeta(Btree *pBtree, int idx, u32 *pValue);
7756 SQLITE_PRIVATE int sqlite3BtreeUpdateMeta(Btree*, int idx, u32 value);
7759 ** The second parameter to sqlite3BtreeGetMeta or sqlite3BtreeUpdateMeta
7760 ** should be one of the following values. The integer values are assigned
7761 ** to constants so that the offset of the corresponding field in an
7762 ** SQLite database header may be found using the following formula:
7764 ** offset = 36 + (idx * 4)
7766 ** For example, the free-page-count field is located at byte offset 36 of
7767 ** the database file header. The incr-vacuum-flag field is located at
7768 ** byte offset 64 (== 36+4*7).
7770 #define BTREE_FREE_PAGE_COUNT 0
7771 #define BTREE_SCHEMA_VERSION 1
7772 #define BTREE_FILE_FORMAT 2
7773 #define BTREE_DEFAULT_CACHE_SIZE 3
7774 #define BTREE_LARGEST_ROOT_PAGE 4
7775 #define BTREE_TEXT_ENCODING 5
7776 #define BTREE_USER_VERSION 6
7777 #define BTREE_INCR_VACUUM 7
7779 SQLITE_PRIVATE int sqlite3BtreeCursor(
7780 Btree*, /* BTree containing table to open */
7781 int iTable, /* Index of root page */
7782 int wrFlag, /* 1 for writing. 0 for read-only */
7783 struct KeyInfo*, /* First argument to compare function */
7784 BtCursor *pCursor /* Space to write cursor structure */
7786 SQLITE_PRIVATE int sqlite3BtreeCursorSize(void);
7787 SQLITE_PRIVATE void sqlite3BtreeCursorZero(BtCursor*);
7789 SQLITE_PRIVATE int sqlite3BtreeCloseCursor(BtCursor*);
7790 SQLITE_PRIVATE int sqlite3BtreeMovetoUnpacked(
7791 BtCursor*,
7792 UnpackedRecord *pUnKey,
7793 i64 intKey,
7794 int bias,
7795 int *pRes
7797 SQLITE_PRIVATE int sqlite3BtreeCursorHasMoved(BtCursor*, int*);
7798 SQLITE_PRIVATE int sqlite3BtreeDelete(BtCursor*);
7799 SQLITE_PRIVATE int sqlite3BtreeInsert(BtCursor*, const void *pKey, i64 nKey,
7800 const void *pData, int nData,
7801 int nZero, int bias, int seekResult);
7802 SQLITE_PRIVATE int sqlite3BtreeFirst(BtCursor*, int *pRes);
7803 SQLITE_PRIVATE int sqlite3BtreeLast(BtCursor*, int *pRes);
7804 SQLITE_PRIVATE int sqlite3BtreeNext(BtCursor*, int *pRes);
7805 SQLITE_PRIVATE int sqlite3BtreeEof(BtCursor*);
7806 SQLITE_PRIVATE int sqlite3BtreePrevious(BtCursor*, int *pRes);
7807 SQLITE_PRIVATE int sqlite3BtreeKeySize(BtCursor*, i64 *pSize);
7808 SQLITE_PRIVATE int sqlite3BtreeKey(BtCursor*, u32 offset, u32 amt, void*);
7809 SQLITE_PRIVATE const void *sqlite3BtreeKeyFetch(BtCursor*, int *pAmt);
7810 SQLITE_PRIVATE const void *sqlite3BtreeDataFetch(BtCursor*, int *pAmt);
7811 SQLITE_PRIVATE int sqlite3BtreeDataSize(BtCursor*, u32 *pSize);
7812 SQLITE_PRIVATE int sqlite3BtreeData(BtCursor*, u32 offset, u32 amt, void*);
7813 SQLITE_PRIVATE void sqlite3BtreeSetCachedRowid(BtCursor*, sqlite3_int64);
7814 SQLITE_PRIVATE sqlite3_int64 sqlite3BtreeGetCachedRowid(BtCursor*);
7816 SQLITE_PRIVATE char *sqlite3BtreeIntegrityCheck(Btree*, int *aRoot, int nRoot, int, int*);
7817 SQLITE_PRIVATE struct Pager *sqlite3BtreePager(Btree*);
7819 SQLITE_PRIVATE int sqlite3BtreePutData(BtCursor*, u32 offset, u32 amt, void*);
7820 SQLITE_PRIVATE void sqlite3BtreeCacheOverflow(BtCursor *);
7821 SQLITE_PRIVATE void sqlite3BtreeClearCursor(BtCursor *);
7823 SQLITE_PRIVATE int sqlite3BtreeSetVersion(Btree *pBt, int iVersion);
7825 #ifndef NDEBUG
7826 SQLITE_PRIVATE int sqlite3BtreeCursorIsValid(BtCursor*);
7827 #endif
7829 #ifndef SQLITE_OMIT_BTREECOUNT
7830 SQLITE_PRIVATE int sqlite3BtreeCount(BtCursor *, i64 *);
7831 #endif
7833 #ifdef SQLITE_TEST
7834 SQLITE_PRIVATE int sqlite3BtreeCursorInfo(BtCursor*, int*, int);
7835 SQLITE_PRIVATE void sqlite3BtreeCursorList(Btree*);
7836 #endif
7838 #ifndef SQLITE_OMIT_WAL
7839 SQLITE_PRIVATE int sqlite3BtreeCheckpoint(Btree*, int, int *, int *);
7840 #endif
7843 ** If we are not using shared cache, then there is no need to
7844 ** use mutexes to access the BtShared structures. So make the
7845 ** Enter and Leave procedures no-ops.
7847 #ifndef SQLITE_OMIT_SHARED_CACHE
7848 SQLITE_PRIVATE void sqlite3BtreeEnter(Btree*);
7849 SQLITE_PRIVATE void sqlite3BtreeEnterAll(sqlite3*);
7850 #else
7851 # define sqlite3BtreeEnter(X)
7852 # define sqlite3BtreeEnterAll(X)
7853 #endif
7855 #if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE
7856 SQLITE_PRIVATE int sqlite3BtreeSharable(Btree*);
7857 SQLITE_PRIVATE void sqlite3BtreeLeave(Btree*);
7858 SQLITE_PRIVATE void sqlite3BtreeEnterCursor(BtCursor*);
7859 SQLITE_PRIVATE void sqlite3BtreeLeaveCursor(BtCursor*);
7860 SQLITE_PRIVATE void sqlite3BtreeLeaveAll(sqlite3*);
7861 #ifndef NDEBUG
7862 /* These routines are used inside assert() statements only. */
7863 SQLITE_PRIVATE int sqlite3BtreeHoldsMutex(Btree*);
7864 SQLITE_PRIVATE int sqlite3BtreeHoldsAllMutexes(sqlite3*);
7865 SQLITE_PRIVATE int sqlite3SchemaMutexHeld(sqlite3*,int,Schema*);
7866 #endif
7867 #else
7869 # define sqlite3BtreeSharable(X) 0
7870 # define sqlite3BtreeLeave(X)
7871 # define sqlite3BtreeEnterCursor(X)
7872 # define sqlite3BtreeLeaveCursor(X)
7873 # define sqlite3BtreeLeaveAll(X)
7875 # define sqlite3BtreeHoldsMutex(X) 1
7876 # define sqlite3BtreeHoldsAllMutexes(X) 1
7877 # define sqlite3SchemaMutexHeld(X,Y,Z) 1
7878 #endif
7881 #endif /* _BTREE_H_ */
7883 /************** End of btree.h ***********************************************/
7884 /************** Continuing where we left off in sqliteInt.h ******************/
7885 /************** Include vdbe.h in the middle of sqliteInt.h ******************/
7886 /************** Begin file vdbe.h ********************************************/
7888 ** 2001 September 15
7890 ** The author disclaims copyright to this source code. In place of
7891 ** a legal notice, here is a blessing:
7893 ** May you do good and not evil.
7894 ** May you find forgiveness for yourself and forgive others.
7895 ** May you share freely, never taking more than you give.
7897 *************************************************************************
7898 ** Header file for the Virtual DataBase Engine (VDBE)
7900 ** This header defines the interface to the virtual database engine
7901 ** or VDBE. The VDBE implements an abstract machine that runs a
7902 ** simple program to access and modify the underlying database.
7904 #ifndef _SQLITE_VDBE_H_
7905 #define _SQLITE_VDBE_H_
7908 ** A single VDBE is an opaque structure named "Vdbe". Only routines
7909 ** in the source file sqliteVdbe.c are allowed to see the insides
7910 ** of this structure.
7912 typedef struct Vdbe Vdbe;
7915 ** The names of the following types declared in vdbeInt.h are required
7916 ** for the VdbeOp definition.
7918 typedef struct VdbeFunc VdbeFunc;
7919 typedef struct Mem Mem;
7920 typedef struct SubProgram SubProgram;
7923 ** A single instruction of the virtual machine has an opcode
7924 ** and as many as three operands. The instruction is recorded
7925 ** as an instance of the following structure:
7927 struct VdbeOp {
7928 u8 opcode; /* What operation to perform */
7929 signed char p4type; /* One of the P4_xxx constants for p4 */
7930 u8 opflags; /* Mask of the OPFLG_* flags in opcodes.h */
7931 u8 p5; /* Fifth parameter is an unsigned character */
7932 int p1; /* First operand */
7933 int p2; /* Second parameter (often the jump destination) */
7934 int p3; /* The third parameter */
7935 union { /* fourth parameter */
7936 int i; /* Integer value if p4type==P4_INT32 */
7937 void *p; /* Generic pointer */
7938 char *z; /* Pointer to data for string (char array) types */
7939 i64 *pI64; /* Used when p4type is P4_INT64 */
7940 double *pReal; /* Used when p4type is P4_REAL */
7941 FuncDef *pFunc; /* Used when p4type is P4_FUNCDEF */
7942 VdbeFunc *pVdbeFunc; /* Used when p4type is P4_VDBEFUNC */
7943 CollSeq *pColl; /* Used when p4type is P4_COLLSEQ */
7944 Mem *pMem; /* Used when p4type is P4_MEM */
7945 VTable *pVtab; /* Used when p4type is P4_VTAB */
7946 KeyInfo *pKeyInfo; /* Used when p4type is P4_KEYINFO */
7947 int *ai; /* Used when p4type is P4_INTARRAY */
7948 SubProgram *pProgram; /* Used when p4type is P4_SUBPROGRAM */
7949 } p4;
7950 #ifdef SQLITE_DEBUG
7951 char *zComment; /* Comment to improve readability */
7952 #endif
7953 #ifdef VDBE_PROFILE
7954 int cnt; /* Number of times this instruction was executed */
7955 u64 cycles; /* Total time spent executing this instruction */
7956 #endif
7958 typedef struct VdbeOp VdbeOp;
7962 ** A sub-routine used to implement a trigger program.
7964 struct SubProgram {
7965 VdbeOp *aOp; /* Array of opcodes for sub-program */
7966 int nOp; /* Elements in aOp[] */
7967 int nMem; /* Number of memory cells required */
7968 int nCsr; /* Number of cursors required */
7969 void *token; /* id that may be used to recursive triggers */
7970 SubProgram *pNext; /* Next sub-program already visited */
7974 ** A smaller version of VdbeOp used for the VdbeAddOpList() function because
7975 ** it takes up less space.
7977 struct VdbeOpList {
7978 u8 opcode; /* What operation to perform */
7979 signed char p1; /* First operand */
7980 signed char p2; /* Second parameter (often the jump destination) */
7981 signed char p3; /* Third parameter */
7983 typedef struct VdbeOpList VdbeOpList;
7986 ** Allowed values of VdbeOp.p4type
7988 #define P4_NOTUSED 0 /* The P4 parameter is not used */
7989 #define P4_DYNAMIC (-1) /* Pointer to a string obtained from sqliteMalloc() */
7990 #define P4_STATIC (-2) /* Pointer to a static string */
7991 #define P4_COLLSEQ (-4) /* P4 is a pointer to a CollSeq structure */
7992 #define P4_FUNCDEF (-5) /* P4 is a pointer to a FuncDef structure */
7993 #define P4_KEYINFO (-6) /* P4 is a pointer to a KeyInfo structure */
7994 #define P4_VDBEFUNC (-7) /* P4 is a pointer to a VdbeFunc structure */
7995 #define P4_MEM (-8) /* P4 is a pointer to a Mem* structure */
7996 #define P4_TRANSIENT 0 /* P4 is a pointer to a transient string */
7997 #define P4_VTAB (-10) /* P4 is a pointer to an sqlite3_vtab structure */
7998 #define P4_MPRINTF (-11) /* P4 is a string obtained from sqlite3_mprintf() */
7999 #define P4_REAL (-12) /* P4 is a 64-bit floating point value */
8000 #define P4_INT64 (-13) /* P4 is a 64-bit signed integer */
8001 #define P4_INT32 (-14) /* P4 is a 32-bit signed integer */
8002 #define P4_INTARRAY (-15) /* P4 is a vector of 32-bit integers */
8003 #define P4_SUBPROGRAM (-18) /* P4 is a pointer to a SubProgram structure */
8005 /* When adding a P4 argument using P4_KEYINFO, a copy of the KeyInfo structure
8006 ** is made. That copy is freed when the Vdbe is finalized. But if the
8007 ** argument is P4_KEYINFO_HANDOFF, the passed in pointer is used. It still
8008 ** gets freed when the Vdbe is finalized so it still should be obtained
8009 ** from a single sqliteMalloc(). But no copy is made and the calling
8010 ** function should *not* try to free the KeyInfo.
8012 #define P4_KEYINFO_HANDOFF (-16)
8013 #define P4_KEYINFO_STATIC (-17)
8016 ** The Vdbe.aColName array contains 5n Mem structures, where n is the
8017 ** number of columns of data returned by the statement.
8019 #define COLNAME_NAME 0
8020 #define COLNAME_DECLTYPE 1
8021 #define COLNAME_DATABASE 2
8022 #define COLNAME_TABLE 3
8023 #define COLNAME_COLUMN 4
8024 #ifdef SQLITE_ENABLE_COLUMN_METADATA
8025 # define COLNAME_N 5 /* Number of COLNAME_xxx symbols */
8026 #else
8027 # ifdef SQLITE_OMIT_DECLTYPE
8028 # define COLNAME_N 1 /* Store only the name */
8029 # else
8030 # define COLNAME_N 2 /* Store the name and decltype */
8031 # endif
8032 #endif
8035 ** The following macro converts a relative address in the p2 field
8036 ** of a VdbeOp structure into a negative number so that
8037 ** sqlite3VdbeAddOpList() knows that the address is relative. Calling
8038 ** the macro again restores the address.
8040 #define ADDR(X) (-1-(X))
8043 ** The makefile scans the vdbe.c source file and creates the "opcodes.h"
8044 ** header file that defines a number for each opcode used by the VDBE.
8046 /************** Include opcodes.h in the middle of vdbe.h ********************/
8047 /************** Begin file opcodes.h *****************************************/
8048 /* Automatically generated. Do not edit */
8049 /* See the mkopcodeh.awk script for details */
8050 #define OP_Goto 1
8051 #define OP_Gosub 2
8052 #define OP_Return 3
8053 #define OP_Yield 4
8054 #define OP_HaltIfNull 5
8055 #define OP_Halt 6
8056 #define OP_Integer 7
8057 #define OP_Int64 8
8058 #define OP_Real 130 /* same as TK_FLOAT */
8059 #define OP_String8 94 /* same as TK_STRING */
8060 #define OP_String 9
8061 #define OP_Null 10
8062 #define OP_Blob 11
8063 #define OP_Variable 12
8064 #define OP_Move 13
8065 #define OP_Copy 14
8066 #define OP_SCopy 15
8067 #define OP_ResultRow 16
8068 #define OP_Concat 91 /* same as TK_CONCAT */
8069 #define OP_Add 86 /* same as TK_PLUS */
8070 #define OP_Subtract 87 /* same as TK_MINUS */
8071 #define OP_Multiply 88 /* same as TK_STAR */
8072 #define OP_Divide 89 /* same as TK_SLASH */
8073 #define OP_Remainder 90 /* same as TK_REM */
8074 #define OP_CollSeq 17
8075 #define OP_Function 18
8076 #define OP_BitAnd 82 /* same as TK_BITAND */
8077 #define OP_BitOr 83 /* same as TK_BITOR */
8078 #define OP_ShiftLeft 84 /* same as TK_LSHIFT */
8079 #define OP_ShiftRight 85 /* same as TK_RSHIFT */
8080 #define OP_AddImm 20
8081 #define OP_MustBeInt 21
8082 #define OP_RealAffinity 22
8083 #define OP_ToText 141 /* same as TK_TO_TEXT */
8084 #define OP_ToBlob 142 /* same as TK_TO_BLOB */
8085 #define OP_ToNumeric 143 /* same as TK_TO_NUMERIC*/
8086 #define OP_ToInt 144 /* same as TK_TO_INT */
8087 #define OP_ToReal 145 /* same as TK_TO_REAL */
8088 #define OP_Eq 76 /* same as TK_EQ */
8089 #define OP_Ne 75 /* same as TK_NE */
8090 #define OP_Lt 79 /* same as TK_LT */
8091 #define OP_Le 78 /* same as TK_LE */
8092 #define OP_Gt 77 /* same as TK_GT */
8093 #define OP_Ge 80 /* same as TK_GE */
8094 #define OP_Permutation 23
8095 #define OP_Compare 24
8096 #define OP_Jump 25
8097 #define OP_And 69 /* same as TK_AND */
8098 #define OP_Or 68 /* same as TK_OR */
8099 #define OP_Not 19 /* same as TK_NOT */
8100 #define OP_BitNot 93 /* same as TK_BITNOT */
8101 #define OP_If 26
8102 #define OP_IfNot 27
8103 #define OP_IsNull 73 /* same as TK_ISNULL */
8104 #define OP_NotNull 74 /* same as TK_NOTNULL */
8105 #define OP_Column 28
8106 #define OP_Affinity 29
8107 #define OP_MakeRecord 30
8108 #define OP_Count 31
8109 #define OP_Savepoint 32
8110 #define OP_AutoCommit 33
8111 #define OP_Transaction 34
8112 #define OP_ReadCookie 35
8113 #define OP_SetCookie 36
8114 #define OP_VerifyCookie 37
8115 #define OP_OpenRead 38
8116 #define OP_OpenWrite 39
8117 #define OP_OpenAutoindex 40
8118 #define OP_OpenEphemeral 41
8119 #define OP_OpenPseudo 42
8120 #define OP_Close 43
8121 #define OP_SeekLt 44
8122 #define OP_SeekLe 45
8123 #define OP_SeekGe 46
8124 #define OP_SeekGt 47
8125 #define OP_Seek 48
8126 #define OP_NotFound 49
8127 #define OP_Found 50
8128 #define OP_IsUnique 51
8129 #define OP_NotExists 52
8130 #define OP_Sequence 53
8131 #define OP_NewRowid 54
8132 #define OP_Insert 55
8133 #define OP_InsertInt 56
8134 #define OP_Delete 57
8135 #define OP_ResetCount 58
8136 #define OP_RowKey 59
8137 #define OP_RowData 60
8138 #define OP_Rowid 61
8139 #define OP_NullRow 62
8140 #define OP_Last 63
8141 #define OP_Sort 64
8142 #define OP_Rewind 65
8143 #define OP_Prev 66
8144 #define OP_Next 67
8145 #define OP_IdxInsert 70
8146 #define OP_IdxDelete 71
8147 #define OP_IdxRowid 72
8148 #define OP_IdxLT 81
8149 #define OP_IdxGE 92
8150 #define OP_Destroy 95
8151 #define OP_Clear 96
8152 #define OP_CreateIndex 97
8153 #define OP_CreateTable 98
8154 #define OP_ParseSchema 99
8155 #define OP_LoadAnalysis 100
8156 #define OP_DropTable 101
8157 #define OP_DropIndex 102
8158 #define OP_DropTrigger 103
8159 #define OP_IntegrityCk 104
8160 #define OP_RowSetAdd 105
8161 #define OP_RowSetRead 106
8162 #define OP_RowSetTest 107
8163 #define OP_Program 108
8164 #define OP_Param 109
8165 #define OP_FkCounter 110
8166 #define OP_FkIfZero 111
8167 #define OP_MemMax 112
8168 #define OP_IfPos 113
8169 #define OP_IfNeg 114
8170 #define OP_IfZero 115
8171 #define OP_AggStep 116
8172 #define OP_AggFinal 117
8173 #define OP_Checkpoint 118
8174 #define OP_JournalMode 119
8175 #define OP_Vacuum 120
8176 #define OP_IncrVacuum 121
8177 #define OP_Expire 122
8178 #define OP_TableLock 123
8179 #define OP_VBegin 124
8180 #define OP_VCreate 125
8181 #define OP_VDestroy 126
8182 #define OP_VOpen 127
8183 #define OP_VFilter 128
8184 #define OP_VColumn 129
8185 #define OP_VNext 131
8186 #define OP_VRename 132
8187 #define OP_VUpdate 133
8188 #define OP_Pagecount 134
8189 #define OP_MaxPgcnt 135
8190 #define OP_Trace 136
8191 #define OP_Noop 137
8192 #define OP_Explain 138
8194 /* The following opcode values are never used */
8195 #define OP_NotUsed_139 139
8196 #define OP_NotUsed_140 140
8199 /* Properties such as "out2" or "jump" that are specified in
8200 ** comments following the "case" for each opcode in the vdbe.c
8201 ** are encoded into bitvectors as follows:
8203 #define OPFLG_JUMP 0x0001 /* jump: P2 holds jmp target */
8204 #define OPFLG_OUT2_PRERELEASE 0x0002 /* out2-prerelease: */
8205 #define OPFLG_IN1 0x0004 /* in1: P1 is an input */
8206 #define OPFLG_IN2 0x0008 /* in2: P2 is an input */
8207 #define OPFLG_IN3 0x0010 /* in3: P3 is an input */
8208 #define OPFLG_OUT2 0x0020 /* out2: P2 is an output */
8209 #define OPFLG_OUT3 0x0040 /* out3: P3 is an output */
8210 #define OPFLG_INITIALIZER {\
8211 /* 0 */ 0x00, 0x01, 0x05, 0x04, 0x04, 0x10, 0x00, 0x02,\
8212 /* 8 */ 0x02, 0x02, 0x02, 0x02, 0x02, 0x00, 0x24, 0x24,\
8213 /* 16 */ 0x00, 0x00, 0x00, 0x24, 0x04, 0x05, 0x04, 0x00,\
8214 /* 24 */ 0x00, 0x01, 0x05, 0x05, 0x00, 0x00, 0x00, 0x02,\
8215 /* 32 */ 0x00, 0x00, 0x00, 0x02, 0x10, 0x00, 0x00, 0x00,\
8216 /* 40 */ 0x00, 0x00, 0x00, 0x00, 0x11, 0x11, 0x11, 0x11,\
8217 /* 48 */ 0x08, 0x11, 0x11, 0x11, 0x11, 0x02, 0x02, 0x00,\
8218 /* 56 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x00, 0x01,\
8219 /* 64 */ 0x01, 0x01, 0x01, 0x01, 0x4c, 0x4c, 0x08, 0x00,\
8220 /* 72 */ 0x02, 0x05, 0x05, 0x15, 0x15, 0x15, 0x15, 0x15,\
8221 /* 80 */ 0x15, 0x01, 0x4c, 0x4c, 0x4c, 0x4c, 0x4c, 0x4c,\
8222 /* 88 */ 0x4c, 0x4c, 0x4c, 0x4c, 0x01, 0x24, 0x02, 0x02,\
8223 /* 96 */ 0x00, 0x02, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00,\
8224 /* 104 */ 0x00, 0x0c, 0x45, 0x15, 0x01, 0x02, 0x00, 0x01,\
8225 /* 112 */ 0x08, 0x05, 0x05, 0x05, 0x00, 0x00, 0x00, 0x02,\
8226 /* 120 */ 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\
8227 /* 128 */ 0x01, 0x00, 0x02, 0x01, 0x00, 0x00, 0x02, 0x02,\
8228 /* 136 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x04, 0x04, 0x04,\
8229 /* 144 */ 0x04, 0x04,}
8231 /************** End of opcodes.h *********************************************/
8232 /************** Continuing where we left off in vdbe.h ***********************/
8235 ** Prototypes for the VDBE interface. See comments on the implementation
8236 ** for a description of what each of these routines does.
8238 SQLITE_PRIVATE Vdbe *sqlite3VdbeCreate(sqlite3*);
8239 SQLITE_PRIVATE int sqlite3VdbeAddOp0(Vdbe*,int);
8240 SQLITE_PRIVATE int sqlite3VdbeAddOp1(Vdbe*,int,int);
8241 SQLITE_PRIVATE int sqlite3VdbeAddOp2(Vdbe*,int,int,int);
8242 SQLITE_PRIVATE int sqlite3VdbeAddOp3(Vdbe*,int,int,int,int);
8243 SQLITE_PRIVATE int sqlite3VdbeAddOp4(Vdbe*,int,int,int,int,const char *zP4,int);
8244 SQLITE_PRIVATE int sqlite3VdbeAddOp4Int(Vdbe*,int,int,int,int,int);
8245 SQLITE_PRIVATE int sqlite3VdbeAddOpList(Vdbe*, int nOp, VdbeOpList const *aOp);
8246 SQLITE_PRIVATE void sqlite3VdbeChangeP1(Vdbe*, int addr, int P1);
8247 SQLITE_PRIVATE void sqlite3VdbeChangeP2(Vdbe*, int addr, int P2);
8248 SQLITE_PRIVATE void sqlite3VdbeChangeP3(Vdbe*, int addr, int P3);
8249 SQLITE_PRIVATE void sqlite3VdbeChangeP5(Vdbe*, u8 P5);
8250 SQLITE_PRIVATE void sqlite3VdbeJumpHere(Vdbe*, int addr);
8251 SQLITE_PRIVATE void sqlite3VdbeChangeToNoop(Vdbe*, int addr, int N);
8252 SQLITE_PRIVATE void sqlite3VdbeChangeP4(Vdbe*, int addr, const char *zP4, int N);
8253 SQLITE_PRIVATE void sqlite3VdbeUsesBtree(Vdbe*, int);
8254 SQLITE_PRIVATE VdbeOp *sqlite3VdbeGetOp(Vdbe*, int);
8255 SQLITE_PRIVATE int sqlite3VdbeMakeLabel(Vdbe*);
8256 SQLITE_PRIVATE void sqlite3VdbeRunOnlyOnce(Vdbe*);
8257 SQLITE_PRIVATE void sqlite3VdbeDelete(Vdbe*);
8258 SQLITE_PRIVATE void sqlite3VdbeDeleteObject(sqlite3*,Vdbe*);
8259 SQLITE_PRIVATE void sqlite3VdbeMakeReady(Vdbe*,int,int,int,int,int,int);
8260 SQLITE_PRIVATE int sqlite3VdbeFinalize(Vdbe*);
8261 SQLITE_PRIVATE void sqlite3VdbeResolveLabel(Vdbe*, int);
8262 SQLITE_PRIVATE int sqlite3VdbeCurrentAddr(Vdbe*);
8263 #ifdef SQLITE_DEBUG
8264 SQLITE_PRIVATE int sqlite3VdbeAssertMayAbort(Vdbe *, int);
8265 SQLITE_PRIVATE void sqlite3VdbeTrace(Vdbe*,FILE*);
8266 #endif
8267 SQLITE_PRIVATE void sqlite3VdbeResetStepResult(Vdbe*);
8268 SQLITE_PRIVATE int sqlite3VdbeReset(Vdbe*);
8269 SQLITE_PRIVATE void sqlite3VdbeSetNumCols(Vdbe*,int);
8270 SQLITE_PRIVATE int sqlite3VdbeSetColName(Vdbe*, int, int, const char *, void(*)(void*));
8271 SQLITE_PRIVATE void sqlite3VdbeCountChanges(Vdbe*);
8272 SQLITE_PRIVATE sqlite3 *sqlite3VdbeDb(Vdbe*);
8273 SQLITE_PRIVATE void sqlite3VdbeSetSql(Vdbe*, const char *z, int n, int);
8274 SQLITE_PRIVATE void sqlite3VdbeSwap(Vdbe*,Vdbe*);
8275 SQLITE_PRIVATE VdbeOp *sqlite3VdbeTakeOpArray(Vdbe*, int*, int*);
8276 SQLITE_PRIVATE sqlite3_value *sqlite3VdbeGetValue(Vdbe*, int, u8);
8277 SQLITE_PRIVATE void sqlite3VdbeSetVarmask(Vdbe*, int);
8278 #ifndef SQLITE_OMIT_TRACE
8279 SQLITE_PRIVATE char *sqlite3VdbeExpandSql(Vdbe*, const char*);
8280 #endif
8282 SQLITE_PRIVATE UnpackedRecord *sqlite3VdbeRecordUnpack(KeyInfo*,int,const void*,char*,int);
8283 SQLITE_PRIVATE void sqlite3VdbeDeleteUnpackedRecord(UnpackedRecord*);
8284 SQLITE_PRIVATE int sqlite3VdbeRecordCompare(int,const void*,UnpackedRecord*);
8286 #ifndef SQLITE_OMIT_TRIGGER
8287 SQLITE_PRIVATE void sqlite3VdbeLinkSubProgram(Vdbe *, SubProgram *);
8288 #endif
8291 #ifndef NDEBUG
8292 SQLITE_PRIVATE void sqlite3VdbeComment(Vdbe*, const char*, ...);
8293 # define VdbeComment(X) sqlite3VdbeComment X
8294 SQLITE_PRIVATE void sqlite3VdbeNoopComment(Vdbe*, const char*, ...);
8295 # define VdbeNoopComment(X) sqlite3VdbeNoopComment X
8296 #else
8297 # define VdbeComment(X)
8298 # define VdbeNoopComment(X)
8299 #endif
8301 #endif
8303 /************** End of vdbe.h ************************************************/
8304 /************** Continuing where we left off in sqliteInt.h ******************/
8305 /************** Include pager.h in the middle of sqliteInt.h *****************/
8306 /************** Begin file pager.h *******************************************/
8308 ** 2001 September 15
8310 ** The author disclaims copyright to this source code. In place of
8311 ** a legal notice, here is a blessing:
8313 ** May you do good and not evil.
8314 ** May you find forgiveness for yourself and forgive others.
8315 ** May you share freely, never taking more than you give.
8317 *************************************************************************
8318 ** This header file defines the interface that the sqlite page cache
8319 ** subsystem. The page cache subsystem reads and writes a file a page
8320 ** at a time and provides a journal for rollback.
8323 #ifndef _PAGER_H_
8324 #define _PAGER_H_
8327 ** Default maximum size for persistent journal files. A negative
8328 ** value means no limit. This value may be overridden using the
8329 ** sqlite3PagerJournalSizeLimit() API. See also "PRAGMA journal_size_limit".
8331 #ifndef SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT
8332 #define SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT -1
8333 #endif
8336 ** The type used to represent a page number. The first page in a file
8337 ** is called page 1. 0 is used to represent "not a page".
8339 typedef u32 Pgno;
8342 ** Each open file is managed by a separate instance of the "Pager" structure.
8344 typedef struct Pager Pager;
8347 ** Handle type for pages.
8349 typedef struct PgHdr DbPage;
8352 ** Page number PAGER_MJ_PGNO is never used in an SQLite database (it is
8353 ** reserved for working around a windows/posix incompatibility). It is
8354 ** used in the journal to signify that the remainder of the journal file
8355 ** is devoted to storing a master journal name - there are no more pages to
8356 ** roll back. See comments for function writeMasterJournal() in pager.c
8357 ** for details.
8359 #define PAGER_MJ_PGNO(x) ((Pgno)((PENDING_BYTE/((x)->pageSize))+1))
8362 ** Allowed values for the flags parameter to sqlite3PagerOpen().
8364 ** NOTE: These values must match the corresponding BTREE_ values in btree.h.
8366 #define PAGER_OMIT_JOURNAL 0x0001 /* Do not use a rollback journal */
8367 #define PAGER_NO_READLOCK 0x0002 /* Omit readlocks on readonly files */
8368 #define PAGER_MEMORY 0x0004 /* In-memory database */
8371 ** Valid values for the second argument to sqlite3PagerLockingMode().
8373 #define PAGER_LOCKINGMODE_QUERY -1
8374 #define PAGER_LOCKINGMODE_NORMAL 0
8375 #define PAGER_LOCKINGMODE_EXCLUSIVE 1
8378 ** Numeric constants that encode the journalmode.
8380 #define PAGER_JOURNALMODE_QUERY (-1) /* Query the value of journalmode */
8381 #define PAGER_JOURNALMODE_DELETE 0 /* Commit by deleting journal file */
8382 #define PAGER_JOURNALMODE_PERSIST 1 /* Commit by zeroing journal header */
8383 #define PAGER_JOURNALMODE_OFF 2 /* Journal omitted. */
8384 #define PAGER_JOURNALMODE_TRUNCATE 3 /* Commit by truncating journal */
8385 #define PAGER_JOURNALMODE_MEMORY 4 /* In-memory journal file */
8386 #define PAGER_JOURNALMODE_WAL 5 /* Use write-ahead logging */
8389 ** The remainder of this file contains the declarations of the functions
8390 ** that make up the Pager sub-system API. See source code comments for
8391 ** a detailed description of each routine.
8394 /* Open and close a Pager connection. */
8395 SQLITE_PRIVATE int sqlite3PagerOpen(
8396 sqlite3_vfs*,
8397 Pager **ppPager,
8398 const char*,
8399 int,
8400 int,
8401 int,
8402 void(*)(DbPage*)
8404 SQLITE_PRIVATE int sqlite3PagerClose(Pager *pPager);
8405 SQLITE_PRIVATE int sqlite3PagerReadFileheader(Pager*, int, unsigned char*);
8407 /* Functions used to configure a Pager object. */
8408 SQLITE_PRIVATE void sqlite3PagerSetBusyhandler(Pager*, int(*)(void *), void *);
8409 SQLITE_PRIVATE int sqlite3PagerSetPagesize(Pager*, u32*, int);
8410 SQLITE_PRIVATE int sqlite3PagerMaxPageCount(Pager*, int);
8411 SQLITE_PRIVATE void sqlite3PagerSetCachesize(Pager*, int);
8412 SQLITE_PRIVATE void sqlite3PagerSetSafetyLevel(Pager*,int,int,int);
8413 SQLITE_PRIVATE int sqlite3PagerLockingMode(Pager *, int);
8414 SQLITE_PRIVATE int sqlite3PagerSetJournalMode(Pager *, int);
8415 SQLITE_PRIVATE int sqlite3PagerGetJournalMode(Pager*);
8416 SQLITE_PRIVATE int sqlite3PagerOkToChangeJournalMode(Pager*);
8417 SQLITE_PRIVATE i64 sqlite3PagerJournalSizeLimit(Pager *, i64);
8418 SQLITE_PRIVATE sqlite3_backup **sqlite3PagerBackupPtr(Pager*);
8420 /* Functions used to obtain and release page references. */
8421 SQLITE_PRIVATE int sqlite3PagerAcquire(Pager *pPager, Pgno pgno, DbPage **ppPage, int clrFlag);
8422 #define sqlite3PagerGet(A,B,C) sqlite3PagerAcquire(A,B,C,0)
8423 SQLITE_PRIVATE DbPage *sqlite3PagerLookup(Pager *pPager, Pgno pgno);
8424 SQLITE_PRIVATE void sqlite3PagerRef(DbPage*);
8425 SQLITE_PRIVATE void sqlite3PagerUnref(DbPage*);
8427 /* Operations on page references. */
8428 SQLITE_PRIVATE int sqlite3PagerWrite(DbPage*);
8429 SQLITE_PRIVATE void sqlite3PagerDontWrite(DbPage*);
8430 SQLITE_PRIVATE int sqlite3PagerMovepage(Pager*,DbPage*,Pgno,int);
8431 SQLITE_PRIVATE int sqlite3PagerPageRefcount(DbPage*);
8432 SQLITE_PRIVATE void *sqlite3PagerGetData(DbPage *);
8433 SQLITE_PRIVATE void *sqlite3PagerGetExtra(DbPage *);
8435 /* Functions used to manage pager transactions and savepoints. */
8436 SQLITE_PRIVATE void sqlite3PagerPagecount(Pager*, int*);
8437 SQLITE_PRIVATE int sqlite3PagerBegin(Pager*, int exFlag, int);
8438 SQLITE_PRIVATE int sqlite3PagerCommitPhaseOne(Pager*,const char *zMaster, int);
8439 SQLITE_PRIVATE int sqlite3PagerExclusiveLock(Pager*);
8440 SQLITE_PRIVATE int sqlite3PagerSync(Pager *pPager);
8441 SQLITE_PRIVATE int sqlite3PagerCommitPhaseTwo(Pager*);
8442 SQLITE_PRIVATE int sqlite3PagerRollback(Pager*);
8443 SQLITE_PRIVATE int sqlite3PagerOpenSavepoint(Pager *pPager, int n);
8444 SQLITE_PRIVATE int sqlite3PagerSavepoint(Pager *pPager, int op, int iSavepoint);
8445 SQLITE_PRIVATE int sqlite3PagerSharedLock(Pager *pPager);
8447 SQLITE_PRIVATE int sqlite3PagerCheckpoint(Pager *pPager, int, int*, int*);
8448 SQLITE_PRIVATE int sqlite3PagerWalSupported(Pager *pPager);
8449 SQLITE_PRIVATE int sqlite3PagerWalCallback(Pager *pPager);
8450 SQLITE_PRIVATE int sqlite3PagerOpenWal(Pager *pPager, int *pisOpen);
8451 SQLITE_PRIVATE int sqlite3PagerCloseWal(Pager *pPager);
8453 /* Functions used to query pager state and configuration. */
8454 SQLITE_PRIVATE u8 sqlite3PagerIsreadonly(Pager*);
8455 SQLITE_PRIVATE int sqlite3PagerRefcount(Pager*);
8456 SQLITE_PRIVATE int sqlite3PagerMemUsed(Pager*);
8457 SQLITE_PRIVATE const char *sqlite3PagerFilename(Pager*);
8458 SQLITE_PRIVATE const sqlite3_vfs *sqlite3PagerVfs(Pager*);
8459 SQLITE_PRIVATE sqlite3_file *sqlite3PagerFile(Pager*);
8460 SQLITE_PRIVATE const char *sqlite3PagerJournalname(Pager*);
8461 SQLITE_PRIVATE int sqlite3PagerNosync(Pager*);
8462 /* This function is for preload-cache.patch for Chromium: */
8463 SQLITE_PRIVATE int sqlite3PagerLoadall(Pager*);
8464 SQLITE_PRIVATE void *sqlite3PagerTempSpace(Pager*);
8465 SQLITE_PRIVATE int sqlite3PagerIsMemdb(Pager*);
8467 /* Functions used to truncate the database file. */
8468 SQLITE_PRIVATE void sqlite3PagerTruncateImage(Pager*,Pgno);
8470 #if defined(SQLITE_HAS_CODEC) && !defined(SQLITE_OMIT_WAL)
8471 SQLITE_PRIVATE void *sqlite3PagerCodec(DbPage *);
8472 #endif
8474 /* Functions to support testing and debugging. */
8475 #if !defined(NDEBUG) || defined(SQLITE_TEST)
8476 SQLITE_PRIVATE Pgno sqlite3PagerPagenumber(DbPage*);
8477 SQLITE_PRIVATE int sqlite3PagerIswriteable(DbPage*);
8478 #endif
8479 #ifdef SQLITE_TEST
8480 SQLITE_PRIVATE int *sqlite3PagerStats(Pager*);
8481 SQLITE_PRIVATE void sqlite3PagerRefdump(Pager*);
8482 void disable_simulated_io_errors(void);
8483 void enable_simulated_io_errors(void);
8484 #else
8485 # define disable_simulated_io_errors()
8486 # define enable_simulated_io_errors()
8487 #endif
8489 #endif /* _PAGER_H_ */
8491 /************** End of pager.h ***********************************************/
8492 /************** Continuing where we left off in sqliteInt.h ******************/
8493 /************** Include pcache.h in the middle of sqliteInt.h ****************/
8494 /************** Begin file pcache.h ******************************************/
8496 ** 2008 August 05
8498 ** The author disclaims copyright to this source code. In place of
8499 ** a legal notice, here is a blessing:
8501 ** May you do good and not evil.
8502 ** May you find forgiveness for yourself and forgive others.
8503 ** May you share freely, never taking more than you give.
8505 *************************************************************************
8506 ** This header file defines the interface that the sqlite page cache
8507 ** subsystem.
8510 #ifndef _PCACHE_H_
8512 typedef struct PgHdr PgHdr;
8513 typedef struct PCache PCache;
8516 ** Every page in the cache is controlled by an instance of the following
8517 ** structure.
8519 struct PgHdr {
8520 void *pData; /* Content of this page */
8521 void *pExtra; /* Extra content */
8522 PgHdr *pDirty; /* Transient list of dirty pages */
8523 Pgno pgno; /* Page number for this page */
8524 Pager *pPager; /* The pager this page is part of */
8525 #ifdef SQLITE_CHECK_PAGES
8526 u32 pageHash; /* Hash of page content */
8527 #endif
8528 u16 flags; /* PGHDR flags defined below */
8530 /**********************************************************************
8531 ** Elements above are public. All that follows is private to pcache.c
8532 ** and should not be accessed by other modules.
8534 i16 nRef; /* Number of users of this page */
8535 PCache *pCache; /* Cache that owns this page */
8537 PgHdr *pDirtyNext; /* Next element in list of dirty pages */
8538 PgHdr *pDirtyPrev; /* Previous element in list of dirty pages */
8541 /* Bit values for PgHdr.flags */
8542 #define PGHDR_DIRTY 0x002 /* Page has changed */
8543 #define PGHDR_NEED_SYNC 0x004 /* Fsync the rollback journal before
8544 ** writing this page to the database */
8545 #define PGHDR_NEED_READ 0x008 /* Content is unread */
8546 #define PGHDR_REUSE_UNLIKELY 0x010 /* A hint that reuse is unlikely */
8547 #define PGHDR_DONT_WRITE 0x020 /* Do not write content to disk */
8549 /* Initialize and shutdown the page cache subsystem */
8550 SQLITE_PRIVATE int sqlite3PcacheInitialize(void);
8551 SQLITE_PRIVATE void sqlite3PcacheShutdown(void);
8553 /* Page cache buffer management:
8554 ** These routines implement SQLITE_CONFIG_PAGECACHE.
8556 SQLITE_PRIVATE void sqlite3PCacheBufferSetup(void *, int sz, int n);
8558 /* Create a new pager cache.
8559 ** Under memory stress, invoke xStress to try to make pages clean.
8560 ** Only clean and unpinned pages can be reclaimed.
8562 SQLITE_PRIVATE void sqlite3PcacheOpen(
8563 int szPage, /* Size of every page */
8564 int szExtra, /* Extra space associated with each page */
8565 int bPurgeable, /* True if pages are on backing store */
8566 int (*xStress)(void*, PgHdr*), /* Call to try to make pages clean */
8567 void *pStress, /* Argument to xStress */
8568 PCache *pToInit /* Preallocated space for the PCache */
8571 /* Modify the page-size after the cache has been created. */
8572 SQLITE_PRIVATE void sqlite3PcacheSetPageSize(PCache *, int);
8574 /* Return the size in bytes of a PCache object. Used to preallocate
8575 ** storage space.
8577 SQLITE_PRIVATE int sqlite3PcacheSize(void);
8579 /* One release per successful fetch. Page is pinned until released.
8580 ** Reference counted.
8582 SQLITE_PRIVATE int sqlite3PcacheFetch(PCache*, Pgno, int createFlag, PgHdr**);
8583 SQLITE_PRIVATE void sqlite3PcacheRelease(PgHdr*);
8585 SQLITE_PRIVATE void sqlite3PcacheDrop(PgHdr*); /* Remove page from cache */
8586 SQLITE_PRIVATE void sqlite3PcacheMakeDirty(PgHdr*); /* Make sure page is marked dirty */
8587 SQLITE_PRIVATE void sqlite3PcacheMakeClean(PgHdr*); /* Mark a single page as clean */
8588 SQLITE_PRIVATE void sqlite3PcacheCleanAll(PCache*); /* Mark all dirty list pages as clean */
8590 /* Change a page number. Used by incr-vacuum. */
8591 SQLITE_PRIVATE void sqlite3PcacheMove(PgHdr*, Pgno);
8593 /* Remove all pages with pgno>x. Reset the cache if x==0 */
8594 SQLITE_PRIVATE void sqlite3PcacheTruncate(PCache*, Pgno x);
8596 /* Get a list of all dirty pages in the cache, sorted by page number */
8597 SQLITE_PRIVATE PgHdr *sqlite3PcacheDirtyList(PCache*);
8599 /* Reset and close the cache object */
8600 SQLITE_PRIVATE void sqlite3PcacheClose(PCache*);
8602 /* Clear flags from pages of the page cache */
8603 SQLITE_PRIVATE void sqlite3PcacheClearSyncFlags(PCache *);
8605 /* Discard the contents of the cache */
8606 SQLITE_PRIVATE void sqlite3PcacheClear(PCache*);
8608 /* Return the total number of outstanding page references */
8609 SQLITE_PRIVATE int sqlite3PcacheRefCount(PCache*);
8611 /* Increment the reference count of an existing page */
8612 SQLITE_PRIVATE void sqlite3PcacheRef(PgHdr*);
8614 SQLITE_PRIVATE int sqlite3PcachePageRefcount(PgHdr*);
8616 /* Return the total number of pages stored in the cache */
8617 SQLITE_PRIVATE int sqlite3PcachePagecount(PCache*);
8619 #if defined(SQLITE_CHECK_PAGES) || defined(SQLITE_DEBUG)
8620 /* Iterate through all dirty pages currently stored in the cache. This
8621 ** interface is only available if SQLITE_CHECK_PAGES is defined when the
8622 ** library is built.
8624 SQLITE_PRIVATE void sqlite3PcacheIterateDirty(PCache *pCache, void (*xIter)(PgHdr *));
8625 #endif
8627 /* Set and get the suggested cache-size for the specified pager-cache.
8629 ** If no global maximum is configured, then the system attempts to limit
8630 ** the total number of pages cached by purgeable pager-caches to the sum
8631 ** of the suggested cache-sizes.
8633 SQLITE_PRIVATE void sqlite3PcacheSetCachesize(PCache *, int);
8634 SQLITE_PRIVATE int sqlite3PcacheGetCachesize(PCache *);
8636 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
8637 /* Try to return memory used by the pcache module to the main memory heap */
8638 SQLITE_PRIVATE int sqlite3PcacheReleaseMemory(int);
8639 #endif
8641 #ifdef SQLITE_TEST
8642 SQLITE_PRIVATE void sqlite3PcacheStats(int*,int*,int*,int*);
8643 #endif
8645 SQLITE_PRIVATE void sqlite3PCacheSetDefault(void);
8647 #endif /* _PCACHE_H_ */
8649 /************** End of pcache.h **********************************************/
8650 /************** Continuing where we left off in sqliteInt.h ******************/
8652 /************** Include os.h in the middle of sqliteInt.h ********************/
8653 /************** Begin file os.h **********************************************/
8655 ** 2001 September 16
8657 ** The author disclaims copyright to this source code. In place of
8658 ** a legal notice, here is a blessing:
8660 ** May you do good and not evil.
8661 ** May you find forgiveness for yourself and forgive others.
8662 ** May you share freely, never taking more than you give.
8664 ******************************************************************************
8666 ** This header file (together with is companion C source-code file
8667 ** "os.c") attempt to abstract the underlying operating system so that
8668 ** the SQLite library will work on both POSIX and windows systems.
8670 ** This header file is #include-ed by sqliteInt.h and thus ends up
8671 ** being included by every source file.
8673 #ifndef _SQLITE_OS_H_
8674 #define _SQLITE_OS_H_
8677 ** Figure out if we are dealing with Unix, Windows, or some other
8678 ** operating system. After the following block of preprocess macros,
8679 ** all of SQLITE_OS_UNIX, SQLITE_OS_WIN, SQLITE_OS_OS2, and SQLITE_OS_OTHER
8680 ** will defined to either 1 or 0. One of the four will be 1. The other
8681 ** three will be 0.
8683 #if defined(SQLITE_OS_OTHER)
8684 # if SQLITE_OS_OTHER==1
8685 # undef SQLITE_OS_UNIX
8686 # define SQLITE_OS_UNIX 0
8687 # undef SQLITE_OS_WIN
8688 # define SQLITE_OS_WIN 0
8689 # undef SQLITE_OS_OS2
8690 # define SQLITE_OS_OS2 0
8691 # else
8692 # undef SQLITE_OS_OTHER
8693 # endif
8694 #endif
8695 #if !defined(SQLITE_OS_UNIX) && !defined(SQLITE_OS_OTHER)
8696 # define SQLITE_OS_OTHER 0
8697 # ifndef SQLITE_OS_WIN
8698 # if defined(_WIN32) || defined(WIN32) || defined(__CYGWIN__) || defined(__MINGW32__) || defined(__BORLANDC__)
8699 # define SQLITE_OS_WIN 1
8700 # define SQLITE_OS_UNIX 0
8701 # define SQLITE_OS_OS2 0
8702 # elif defined(__EMX__) || defined(_OS2) || defined(OS2) || defined(_OS2_) || defined(__OS2__)
8703 # define SQLITE_OS_WIN 0
8704 # define SQLITE_OS_UNIX 0
8705 # define SQLITE_OS_OS2 1
8706 # else
8707 # define SQLITE_OS_WIN 0
8708 # define SQLITE_OS_UNIX 1
8709 # define SQLITE_OS_OS2 0
8710 # endif
8711 # else
8712 # define SQLITE_OS_UNIX 0
8713 # define SQLITE_OS_OS2 0
8714 # endif
8715 #else
8716 # ifndef SQLITE_OS_WIN
8717 # define SQLITE_OS_WIN 0
8718 # endif
8719 #endif
8722 ** Determine if we are dealing with WindowsCE - which has a much
8723 ** reduced API.
8725 #if defined(_WIN32_WCE)
8726 # define SQLITE_OS_WINCE 1
8727 #else
8728 # define SQLITE_OS_WINCE 0
8729 #endif
8733 ** Define the maximum size of a temporary filename
8735 #if SQLITE_OS_WIN
8736 # include <windows.h>
8737 # define SQLITE_TEMPNAME_SIZE (MAX_PATH+50)
8738 #elif SQLITE_OS_OS2
8739 # if (__GNUC__ > 3 || __GNUC__ == 3 && __GNUC_MINOR__ >= 3) && defined(OS2_HIGH_MEMORY)
8740 # include <os2safe.h> /* has to be included before os2.h for linking to work */
8741 # endif
8742 # define INCL_DOSDATETIME
8743 # define INCL_DOSFILEMGR
8744 # define INCL_DOSERRORS
8745 # define INCL_DOSMISC
8746 # define INCL_DOSPROCESS
8747 # define INCL_DOSMODULEMGR
8748 # define INCL_DOSSEMAPHORES
8749 # include <os2.h>
8750 # include <uconv.h>
8751 # define SQLITE_TEMPNAME_SIZE (CCHMAXPATHCOMP)
8752 #else
8753 # define SQLITE_TEMPNAME_SIZE 200
8754 #endif
8756 /* If the SET_FULLSYNC macro is not defined above, then make it
8757 ** a no-op
8759 #ifndef SET_FULLSYNC
8760 # define SET_FULLSYNC(x,y)
8761 #endif
8764 ** The default size of a disk sector
8766 #ifndef SQLITE_DEFAULT_SECTOR_SIZE
8767 # define SQLITE_DEFAULT_SECTOR_SIZE 512
8768 #endif
8771 ** Temporary files are named starting with this prefix followed by 16 random
8772 ** alphanumeric characters, and no file extension. They are stored in the
8773 ** OS's standard temporary file directory, and are deleted prior to exit.
8774 ** If sqlite is being embedded in another program, you may wish to change the
8775 ** prefix to reflect your program's name, so that if your program exits
8776 ** prematurely, old temporary files can be easily identified. This can be done
8777 ** using -DSQLITE_TEMP_FILE_PREFIX=myprefix_ on the compiler command line.
8779 ** 2006-10-31: The default prefix used to be "sqlite_". But then
8780 ** Mcafee started using SQLite in their anti-virus product and it
8781 ** started putting files with the "sqlite" name in the c:/temp folder.
8782 ** This annoyed many windows users. Those users would then do a
8783 ** Google search for "sqlite", find the telephone numbers of the
8784 ** developers and call to wake them up at night and complain.
8785 ** For this reason, the default name prefix is changed to be "sqlite"
8786 ** spelled backwards. So the temp files are still identified, but
8787 ** anybody smart enough to figure out the code is also likely smart
8788 ** enough to know that calling the developer will not help get rid
8789 ** of the file.
8791 #ifndef SQLITE_TEMP_FILE_PREFIX
8792 # define SQLITE_TEMP_FILE_PREFIX "etilqs_"
8793 #endif
8796 ** The following values may be passed as the second argument to
8797 ** sqlite3OsLock(). The various locks exhibit the following semantics:
8799 ** SHARED: Any number of processes may hold a SHARED lock simultaneously.
8800 ** RESERVED: A single process may hold a RESERVED lock on a file at
8801 ** any time. Other processes may hold and obtain new SHARED locks.
8802 ** PENDING: A single process may hold a PENDING lock on a file at
8803 ** any one time. Existing SHARED locks may persist, but no new
8804 ** SHARED locks may be obtained by other processes.
8805 ** EXCLUSIVE: An EXCLUSIVE lock precludes all other locks.
8807 ** PENDING_LOCK may not be passed directly to sqlite3OsLock(). Instead, a
8808 ** process that requests an EXCLUSIVE lock may actually obtain a PENDING
8809 ** lock. This can be upgraded to an EXCLUSIVE lock by a subsequent call to
8810 ** sqlite3OsLock().
8812 #define NO_LOCK 0
8813 #define SHARED_LOCK 1
8814 #define RESERVED_LOCK 2
8815 #define PENDING_LOCK 3
8816 #define EXCLUSIVE_LOCK 4
8819 ** File Locking Notes: (Mostly about windows but also some info for Unix)
8821 ** We cannot use LockFileEx() or UnlockFileEx() on Win95/98/ME because
8822 ** those functions are not available. So we use only LockFile() and
8823 ** UnlockFile().
8825 ** LockFile() prevents not just writing but also reading by other processes.
8826 ** A SHARED_LOCK is obtained by locking a single randomly-chosen
8827 ** byte out of a specific range of bytes. The lock byte is obtained at
8828 ** random so two separate readers can probably access the file at the
8829 ** same time, unless they are unlucky and choose the same lock byte.
8830 ** An EXCLUSIVE_LOCK is obtained by locking all bytes in the range.
8831 ** There can only be one writer. A RESERVED_LOCK is obtained by locking
8832 ** a single byte of the file that is designated as the reserved lock byte.
8833 ** A PENDING_LOCK is obtained by locking a designated byte different from
8834 ** the RESERVED_LOCK byte.
8836 ** On WinNT/2K/XP systems, LockFileEx() and UnlockFileEx() are available,
8837 ** which means we can use reader/writer locks. When reader/writer locks
8838 ** are used, the lock is placed on the same range of bytes that is used
8839 ** for probabilistic locking in Win95/98/ME. Hence, the locking scheme
8840 ** will support two or more Win95 readers or two or more WinNT readers.
8841 ** But a single Win95 reader will lock out all WinNT readers and a single
8842 ** WinNT reader will lock out all other Win95 readers.
8844 ** The following #defines specify the range of bytes used for locking.
8845 ** SHARED_SIZE is the number of bytes available in the pool from which
8846 ** a random byte is selected for a shared lock. The pool of bytes for
8847 ** shared locks begins at SHARED_FIRST.
8849 ** The same locking strategy and
8850 ** byte ranges are used for Unix. This leaves open the possiblity of having
8851 ** clients on win95, winNT, and unix all talking to the same shared file
8852 ** and all locking correctly. To do so would require that samba (or whatever
8853 ** tool is being used for file sharing) implements locks correctly between
8854 ** windows and unix. I'm guessing that isn't likely to happen, but by
8855 ** using the same locking range we are at least open to the possibility.
8857 ** Locking in windows is manditory. For this reason, we cannot store
8858 ** actual data in the bytes used for locking. The pager never allocates
8859 ** the pages involved in locking therefore. SHARED_SIZE is selected so
8860 ** that all locks will fit on a single page even at the minimum page size.
8861 ** PENDING_BYTE defines the beginning of the locks. By default PENDING_BYTE
8862 ** is set high so that we don't have to allocate an unused page except
8863 ** for very large databases. But one should test the page skipping logic
8864 ** by setting PENDING_BYTE low and running the entire regression suite.
8866 ** Changing the value of PENDING_BYTE results in a subtly incompatible
8867 ** file format. Depending on how it is changed, you might not notice
8868 ** the incompatibility right away, even running a full regression test.
8869 ** The default location of PENDING_BYTE is the first byte past the
8870 ** 1GB boundary.
8873 #ifdef SQLITE_OMIT_WSD
8874 # define PENDING_BYTE (0x40000000)
8875 #else
8876 # define PENDING_BYTE sqlite3PendingByte
8877 #endif
8878 #define RESERVED_BYTE (PENDING_BYTE+1)
8879 #define SHARED_FIRST (PENDING_BYTE+2)
8880 #define SHARED_SIZE 510
8883 ** Wrapper around OS specific sqlite3_os_init() function.
8885 SQLITE_PRIVATE int sqlite3OsInit(void);
8888 ** Functions for accessing sqlite3_file methods
8890 SQLITE_PRIVATE int sqlite3OsClose(sqlite3_file*);
8891 SQLITE_PRIVATE int sqlite3OsRead(sqlite3_file*, void*, int amt, i64 offset);
8892 SQLITE_PRIVATE int sqlite3OsWrite(sqlite3_file*, const void*, int amt, i64 offset);
8893 SQLITE_PRIVATE int sqlite3OsTruncate(sqlite3_file*, i64 size);
8894 SQLITE_PRIVATE int sqlite3OsSync(sqlite3_file*, int);
8895 SQLITE_PRIVATE int sqlite3OsFileSize(sqlite3_file*, i64 *pSize);
8896 SQLITE_PRIVATE int sqlite3OsLock(sqlite3_file*, int);
8897 SQLITE_PRIVATE int sqlite3OsUnlock(sqlite3_file*, int);
8898 SQLITE_PRIVATE int sqlite3OsCheckReservedLock(sqlite3_file *id, int *pResOut);
8899 SQLITE_PRIVATE int sqlite3OsFileControl(sqlite3_file*,int,void*);
8900 #define SQLITE_FCNTL_DB_UNCHANGED 0xca093fa0
8901 SQLITE_PRIVATE int sqlite3OsSectorSize(sqlite3_file *id);
8902 SQLITE_PRIVATE int sqlite3OsDeviceCharacteristics(sqlite3_file *id);
8903 SQLITE_PRIVATE int sqlite3OsShmMap(sqlite3_file *,int,int,int,void volatile **);
8904 SQLITE_PRIVATE int sqlite3OsShmLock(sqlite3_file *id, int, int, int);
8905 SQLITE_PRIVATE void sqlite3OsShmBarrier(sqlite3_file *id);
8906 SQLITE_PRIVATE int sqlite3OsShmUnmap(sqlite3_file *id, int);
8909 ** Functions for accessing sqlite3_vfs methods
8911 SQLITE_PRIVATE int sqlite3OsOpen(sqlite3_vfs *, const char *, sqlite3_file*, int, int *);
8912 SQLITE_PRIVATE int sqlite3OsDelete(sqlite3_vfs *, const char *, int);
8913 SQLITE_PRIVATE int sqlite3OsAccess(sqlite3_vfs *, const char *, int, int *pResOut);
8914 SQLITE_PRIVATE int sqlite3OsFullPathname(sqlite3_vfs *, const char *, int, char *);
8915 #ifndef SQLITE_OMIT_LOAD_EXTENSION
8916 SQLITE_PRIVATE void *sqlite3OsDlOpen(sqlite3_vfs *, const char *);
8917 SQLITE_PRIVATE void sqlite3OsDlError(sqlite3_vfs *, int, char *);
8918 SQLITE_PRIVATE void (*sqlite3OsDlSym(sqlite3_vfs *, void *, const char *))(void);
8919 SQLITE_PRIVATE void sqlite3OsDlClose(sqlite3_vfs *, void *);
8920 #endif /* SQLITE_OMIT_LOAD_EXTENSION */
8921 SQLITE_PRIVATE int sqlite3OsRandomness(sqlite3_vfs *, int, char *);
8922 SQLITE_PRIVATE int sqlite3OsSleep(sqlite3_vfs *, int);
8923 SQLITE_PRIVATE int sqlite3OsCurrentTimeInt64(sqlite3_vfs *, sqlite3_int64*);
8926 ** Convenience functions for opening and closing files using
8927 ** sqlite3_malloc() to obtain space for the file-handle structure.
8929 SQLITE_PRIVATE int sqlite3OsOpenMalloc(sqlite3_vfs *, const char *, sqlite3_file **, int,int*);
8930 SQLITE_PRIVATE int sqlite3OsCloseFree(sqlite3_file *);
8932 #endif /* _SQLITE_OS_H_ */
8934 /************** End of os.h **************************************************/
8935 /************** Continuing where we left off in sqliteInt.h ******************/
8936 /************** Include mutex.h in the middle of sqliteInt.h *****************/
8937 /************** Begin file mutex.h *******************************************/
8939 ** 2007 August 28
8941 ** The author disclaims copyright to this source code. In place of
8942 ** a legal notice, here is a blessing:
8944 ** May you do good and not evil.
8945 ** May you find forgiveness for yourself and forgive others.
8946 ** May you share freely, never taking more than you give.
8948 *************************************************************************
8950 ** This file contains the common header for all mutex implementations.
8951 ** The sqliteInt.h header #includes this file so that it is available
8952 ** to all source files. We break it out in an effort to keep the code
8953 ** better organized.
8955 ** NOTE: source files should *not* #include this header file directly.
8956 ** Source files should #include the sqliteInt.h file and let that file
8957 ** include this one indirectly.
8962 ** Figure out what version of the code to use. The choices are
8964 ** SQLITE_MUTEX_OMIT No mutex logic. Not even stubs. The
8965 ** mutexes implemention cannot be overridden
8966 ** at start-time.
8968 ** SQLITE_MUTEX_NOOP For single-threaded applications. No
8969 ** mutual exclusion is provided. But this
8970 ** implementation can be overridden at
8971 ** start-time.
8973 ** SQLITE_MUTEX_PTHREADS For multi-threaded applications on Unix.
8975 ** SQLITE_MUTEX_W32 For multi-threaded applications on Win32.
8977 ** SQLITE_MUTEX_OS2 For multi-threaded applications on OS/2.
8979 #if !SQLITE_THREADSAFE
8980 # define SQLITE_MUTEX_OMIT
8981 #endif
8982 #if SQLITE_THREADSAFE && !defined(SQLITE_MUTEX_NOOP)
8983 # if SQLITE_OS_UNIX
8984 # define SQLITE_MUTEX_PTHREADS
8985 # elif SQLITE_OS_WIN
8986 # define SQLITE_MUTEX_W32
8987 # elif SQLITE_OS_OS2
8988 # define SQLITE_MUTEX_OS2
8989 # else
8990 # define SQLITE_MUTEX_NOOP
8991 # endif
8992 #endif
8994 #ifdef SQLITE_MUTEX_OMIT
8996 ** If this is a no-op implementation, implement everything as macros.
8998 #define sqlite3_mutex_alloc(X) ((sqlite3_mutex*)8)
8999 #define sqlite3_mutex_free(X)
9000 #define sqlite3_mutex_enter(X)
9001 #define sqlite3_mutex_try(X) SQLITE_OK
9002 #define sqlite3_mutex_leave(X)
9003 #define sqlite3_mutex_held(X) ((void)(X),1)
9004 #define sqlite3_mutex_notheld(X) ((void)(X),1)
9005 #define sqlite3MutexAlloc(X) ((sqlite3_mutex*)8)
9006 #define sqlite3MutexInit() SQLITE_OK
9007 #define sqlite3MutexEnd()
9008 #endif /* defined(SQLITE_MUTEX_OMIT) */
9010 /************** End of mutex.h ***********************************************/
9011 /************** Continuing where we left off in sqliteInt.h ******************/
9015 ** Each database file to be accessed by the system is an instance
9016 ** of the following structure. There are normally two of these structures
9017 ** in the sqlite.aDb[] array. aDb[0] is the main database file and
9018 ** aDb[1] is the database file used to hold temporary tables. Additional
9019 ** databases may be attached.
9021 struct Db {
9022 char *zName; /* Name of this database */
9023 Btree *pBt; /* The B*Tree structure for this database file */
9024 u8 inTrans; /* 0: not writable. 1: Transaction. 2: Checkpoint */
9025 u8 safety_level; /* How aggressive at syncing data to disk */
9026 Schema *pSchema; /* Pointer to database schema (possibly shared) */
9030 ** An instance of the following structure stores a database schema.
9032 ** Most Schema objects are associated with a Btree. The exception is
9033 ** the Schema for the TEMP databaes (sqlite3.aDb[1]) which is free-standing.
9034 ** In shared cache mode, a single Schema object can be shared by multiple
9035 ** Btrees that refer to the same underlying BtShared object.
9037 ** Schema objects are automatically deallocated when the last Btree that
9038 ** references them is destroyed. The TEMP Schema is manually freed by
9039 ** sqlite3_close().
9041 ** A thread must be holding a mutex on the corresponding Btree in order
9042 ** to access Schema content. This implies that the thread must also be
9043 ** holding a mutex on the sqlite3 connection pointer that owns the Btree.
9044 ** For a TEMP Schema, on the connection mutex is required.
9046 struct Schema {
9047 int schema_cookie; /* Database schema version number for this file */
9048 int iGeneration; /* Generation counter. Incremented with each change */
9049 Hash tblHash; /* All tables indexed by name */
9050 Hash idxHash; /* All (named) indices indexed by name */
9051 Hash trigHash; /* All triggers indexed by name */
9052 Hash fkeyHash; /* All foreign keys by referenced table name */
9053 Table *pSeqTab; /* The sqlite_sequence table used by AUTOINCREMENT */
9054 u8 file_format; /* Schema format version for this file */
9055 u8 enc; /* Text encoding used by this database */
9056 u16 flags; /* Flags associated with this schema */
9057 int cache_size; /* Number of pages to use in the cache */
9061 ** These macros can be used to test, set, or clear bits in the
9062 ** Db.pSchema->flags field.
9064 #define DbHasProperty(D,I,P) (((D)->aDb[I].pSchema->flags&(P))==(P))
9065 #define DbHasAnyProperty(D,I,P) (((D)->aDb[I].pSchema->flags&(P))!=0)
9066 #define DbSetProperty(D,I,P) (D)->aDb[I].pSchema->flags|=(P)
9067 #define DbClearProperty(D,I,P) (D)->aDb[I].pSchema->flags&=~(P)
9070 ** Allowed values for the DB.pSchema->flags field.
9072 ** The DB_SchemaLoaded flag is set after the database schema has been
9073 ** read into internal hash tables.
9075 ** DB_UnresetViews means that one or more views have column names that
9076 ** have been filled out. If the schema changes, these column names might
9077 ** changes and so the view will need to be reset.
9079 #define DB_SchemaLoaded 0x0001 /* The schema has been loaded */
9080 #define DB_UnresetViews 0x0002 /* Some views have defined column names */
9081 #define DB_Empty 0x0004 /* The file is empty (length 0 bytes) */
9084 ** The number of different kinds of things that can be limited
9085 ** using the sqlite3_limit() interface.
9087 #define SQLITE_N_LIMIT (SQLITE_LIMIT_TRIGGER_DEPTH+1)
9090 ** Lookaside malloc is a set of fixed-size buffers that can be used
9091 ** to satisfy small transient memory allocation requests for objects
9092 ** associated with a particular database connection. The use of
9093 ** lookaside malloc provides a significant performance enhancement
9094 ** (approx 10%) by avoiding numerous malloc/free requests while parsing
9095 ** SQL statements.
9097 ** The Lookaside structure holds configuration information about the
9098 ** lookaside malloc subsystem. Each available memory allocation in
9099 ** the lookaside subsystem is stored on a linked list of LookasideSlot
9100 ** objects.
9102 ** Lookaside allocations are only allowed for objects that are associated
9103 ** with a particular database connection. Hence, schema information cannot
9104 ** be stored in lookaside because in shared cache mode the schema information
9105 ** is shared by multiple database connections. Therefore, while parsing
9106 ** schema information, the Lookaside.bEnabled flag is cleared so that
9107 ** lookaside allocations are not used to construct the schema objects.
9109 struct Lookaside {
9110 u16 sz; /* Size of each buffer in bytes */
9111 u8 bEnabled; /* False to disable new lookaside allocations */
9112 u8 bMalloced; /* True if pStart obtained from sqlite3_malloc() */
9113 int nOut; /* Number of buffers currently checked out */
9114 int mxOut; /* Highwater mark for nOut */
9115 int anStat[3]; /* 0: hits. 1: size misses. 2: full misses */
9116 LookasideSlot *pFree; /* List of available buffers */
9117 void *pStart; /* First byte of available memory space */
9118 void *pEnd; /* First byte past end of available space */
9120 struct LookasideSlot {
9121 LookasideSlot *pNext; /* Next buffer in the list of free buffers */
9125 ** A hash table for function definitions.
9127 ** Hash each FuncDef structure into one of the FuncDefHash.a[] slots.
9128 ** Collisions are on the FuncDef.pHash chain.
9130 struct FuncDefHash {
9131 FuncDef *a[23]; /* Hash table for functions */
9135 ** Each database connection is an instance of the following structure.
9137 ** The sqlite.lastRowid records the last insert rowid generated by an
9138 ** insert statement. Inserts on views do not affect its value. Each
9139 ** trigger has its own context, so that lastRowid can be updated inside
9140 ** triggers as usual. The previous value will be restored once the trigger
9141 ** exits. Upon entering a before or instead of trigger, lastRowid is no
9142 ** longer (since after version 2.8.12) reset to -1.
9144 ** The sqlite.nChange does not count changes within triggers and keeps no
9145 ** context. It is reset at start of sqlite3_exec.
9146 ** The sqlite.lsChange represents the number of changes made by the last
9147 ** insert, update, or delete statement. It remains constant throughout the
9148 ** length of a statement and is then updated by OP_SetCounts. It keeps a
9149 ** context stack just like lastRowid so that the count of changes
9150 ** within a trigger is not seen outside the trigger. Changes to views do not
9151 ** affect the value of lsChange.
9152 ** The sqlite.csChange keeps track of the number of current changes (since
9153 ** the last statement) and is used to update sqlite_lsChange.
9155 ** The member variables sqlite.errCode, sqlite.zErrMsg and sqlite.zErrMsg16
9156 ** store the most recent error code and, if applicable, string. The
9157 ** internal function sqlite3Error() is used to set these variables
9158 ** consistently.
9160 struct sqlite3 {
9161 sqlite3_vfs *pVfs; /* OS Interface */
9162 int nDb; /* Number of backends currently in use */
9163 Db *aDb; /* All backends */
9164 int flags; /* Miscellaneous flags. See below */
9165 int openFlags; /* Flags passed to sqlite3_vfs.xOpen() */
9166 int errCode; /* Most recent error code (SQLITE_*) */
9167 int errMask; /* & result codes with this before returning */
9168 u8 autoCommit; /* The auto-commit flag. */
9169 u8 temp_store; /* 1: file 2: memory 0: default */
9170 u8 mallocFailed; /* True if we have seen a malloc failure */
9171 u8 dfltLockMode; /* Default locking-mode for attached dbs */
9172 signed char nextAutovac; /* Autovac setting after VACUUM if >=0 */
9173 u8 suppressErr; /* Do not issue error messages if true */
9174 int nextPagesize; /* Pagesize after VACUUM if >0 */
9175 int nTable; /* Number of tables in the database */
9176 CollSeq *pDfltColl; /* The default collating sequence (BINARY) */
9177 i64 lastRowid; /* ROWID of most recent insert (see above) */
9178 u32 magic; /* Magic number for detect library misuse */
9179 int nChange; /* Value returned by sqlite3_changes() */
9180 int nTotalChange; /* Value returned by sqlite3_total_changes() */
9181 sqlite3_mutex *mutex; /* Connection mutex */
9182 int aLimit[SQLITE_N_LIMIT]; /* Limits */
9183 struct sqlite3InitInfo { /* Information used during initialization */
9184 int iDb; /* When back is being initialized */
9185 int newTnum; /* Rootpage of table being initialized */
9186 u8 busy; /* TRUE if currently initializing */
9187 u8 orphanTrigger; /* Last statement is orphaned TEMP trigger */
9188 } init;
9189 int nExtension; /* Number of loaded extensions */
9190 void **aExtension; /* Array of shared library handles */
9191 struct Vdbe *pVdbe; /* List of active virtual machines */
9192 int activeVdbeCnt; /* Number of VDBEs currently executing */
9193 int writeVdbeCnt; /* Number of active VDBEs that are writing */
9194 int vdbeExecCnt; /* Number of nested calls to VdbeExec() */
9195 void (*xTrace)(void*,const char*); /* Trace function */
9196 void *pTraceArg; /* Argument to the trace function */
9197 void (*xProfile)(void*,const char*,u64); /* Profiling function */
9198 void *pProfileArg; /* Argument to profile function */
9199 void *pCommitArg; /* Argument to xCommitCallback() */
9200 int (*xCommitCallback)(void*); /* Invoked at every commit. */
9201 void *pRollbackArg; /* Argument to xRollbackCallback() */
9202 void (*xRollbackCallback)(void*); /* Invoked at every commit. */
9203 void *pUpdateArg;
9204 void (*xUpdateCallback)(void*,int, const char*,const char*,sqlite_int64);
9205 #ifndef SQLITE_OMIT_WAL
9206 int (*xWalCallback)(void *, sqlite3 *, const char *, int);
9207 void *pWalArg;
9208 #endif
9209 void(*xCollNeeded)(void*,sqlite3*,int eTextRep,const char*);
9210 void(*xCollNeeded16)(void*,sqlite3*,int eTextRep,const void*);
9211 void *pCollNeededArg;
9212 sqlite3_value *pErr; /* Most recent error message */
9213 char *zErrMsg; /* Most recent error message (UTF-8 encoded) */
9214 char *zErrMsg16; /* Most recent error message (UTF-16 encoded) */
9215 union {
9216 volatile int isInterrupted; /* True if sqlite3_interrupt has been called */
9217 double notUsed1; /* Spacer */
9218 } u1;
9219 Lookaside lookaside; /* Lookaside malloc configuration */
9220 #ifndef SQLITE_OMIT_AUTHORIZATION
9221 int (*xAuth)(void*,int,const char*,const char*,const char*,const char*);
9222 /* Access authorization function */
9223 void *pAuthArg; /* 1st argument to the access auth function */
9224 #endif
9225 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
9226 int (*xProgress)(void *); /* The progress callback */
9227 void *pProgressArg; /* Argument to the progress callback */
9228 int nProgressOps; /* Number of opcodes for progress callback */
9229 #endif
9230 #ifndef SQLITE_OMIT_VIRTUALTABLE
9231 Hash aModule; /* populated by sqlite3_create_module() */
9232 Table *pVTab; /* vtab with active Connect/Create method */
9233 VTable **aVTrans; /* Virtual tables with open transactions */
9234 int nVTrans; /* Allocated size of aVTrans */
9235 VTable *pDisconnect; /* Disconnect these in next sqlite3_prepare() */
9236 #endif
9237 FuncDefHash aFunc; /* Hash table of connection functions */
9238 Hash aCollSeq; /* All collating sequences */
9239 BusyHandler busyHandler; /* Busy callback */
9240 int busyTimeout; /* Busy handler timeout, in msec */
9241 Db aDbStatic[2]; /* Static space for the 2 default backends */
9242 Savepoint *pSavepoint; /* List of active savepoints */
9243 int nSavepoint; /* Number of non-transaction savepoints */
9244 int nStatement; /* Number of nested statement-transactions */
9245 u8 isTransactionSavepoint; /* True if the outermost savepoint is a TS */
9246 i64 nDeferredCons; /* Net deferred constraints this transaction. */
9247 int *pnBytesFreed; /* If not NULL, increment this in DbFree() */
9249 #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
9250 /* The following variables are all protected by the STATIC_MASTER
9251 ** mutex, not by sqlite3.mutex. They are used by code in notify.c.
9253 ** When X.pUnlockConnection==Y, that means that X is waiting for Y to
9254 ** unlock so that it can proceed.
9256 ** When X.pBlockingConnection==Y, that means that something that X tried
9257 ** tried to do recently failed with an SQLITE_LOCKED error due to locks
9258 ** held by Y.
9260 sqlite3 *pBlockingConnection; /* Connection that caused SQLITE_LOCKED */
9261 sqlite3 *pUnlockConnection; /* Connection to watch for unlock */
9262 void *pUnlockArg; /* Argument to xUnlockNotify */
9263 void (*xUnlockNotify)(void **, int); /* Unlock notify callback */
9264 sqlite3 *pNextBlocked; /* Next in list of all blocked connections */
9265 #endif
9269 ** A macro to discover the encoding of a database.
9271 #define ENC(db) ((db)->aDb[0].pSchema->enc)
9274 ** Possible values for the sqlite3.flags.
9276 #define SQLITE_VdbeTrace 0x00000100 /* True to trace VDBE execution */
9277 #define SQLITE_InternChanges 0x00000200 /* Uncommitted Hash table changes */
9278 #define SQLITE_FullColNames 0x00000400 /* Show full column names on SELECT */
9279 #define SQLITE_ShortColNames 0x00000800 /* Show short columns names */
9280 #define SQLITE_CountRows 0x00001000 /* Count rows changed by INSERT, */
9281 /* DELETE, or UPDATE and return */
9282 /* the count using a callback. */
9283 #define SQLITE_NullCallback 0x00002000 /* Invoke the callback once if the */
9284 /* result set is empty */
9285 #define SQLITE_SqlTrace 0x00004000 /* Debug print SQL as it executes */
9286 #define SQLITE_VdbeListing 0x00008000 /* Debug listings of VDBE programs */
9287 #define SQLITE_WriteSchema 0x00010000 /* OK to update SQLITE_MASTER */
9288 #define SQLITE_NoReadlock 0x00020000 /* Readlocks are omitted when
9289 ** accessing read-only databases */
9290 #define SQLITE_IgnoreChecks 0x00040000 /* Do not enforce check constraints */
9291 #define SQLITE_ReadUncommitted 0x0080000 /* For shared-cache mode */
9292 #define SQLITE_LegacyFileFmt 0x00100000 /* Create new databases in format 1 */
9293 #define SQLITE_FullFSync 0x00200000 /* Use full fsync on the backend */
9294 #define SQLITE_CkptFullFSync 0x00400000 /* Use full fsync for checkpoint */
9295 #define SQLITE_RecoveryMode 0x00800000 /* Ignore schema errors */
9296 #define SQLITE_ReverseOrder 0x01000000 /* Reverse unordered SELECTs */
9297 #define SQLITE_RecTriggers 0x02000000 /* Enable recursive triggers */
9298 #define SQLITE_ForeignKeys 0x04000000 /* Enforce foreign key constraints */
9299 #define SQLITE_AutoIndex 0x08000000 /* Enable automatic indexes */
9300 #define SQLITE_PreferBuiltin 0x10000000 /* Preference to built-in funcs */
9301 #define SQLITE_LoadExtension 0x20000000 /* Enable load_extension */
9302 #define SQLITE_EnableTrigger 0x40000000 /* True to enable triggers */
9305 ** Bits of the sqlite3.flags field that are used by the
9306 ** sqlite3_test_control(SQLITE_TESTCTRL_OPTIMIZATIONS,...) interface.
9307 ** These must be the low-order bits of the flags field.
9309 #define SQLITE_QueryFlattener 0x01 /* Disable query flattening */
9310 #define SQLITE_ColumnCache 0x02 /* Disable the column cache */
9311 #define SQLITE_IndexSort 0x04 /* Disable indexes for sorting */
9312 #define SQLITE_IndexSearch 0x08 /* Disable indexes for searching */
9313 #define SQLITE_IndexCover 0x10 /* Disable index covering table */
9314 #define SQLITE_GroupByOrder 0x20 /* Disable GROUPBY cover of ORDERBY */
9315 #define SQLITE_FactorOutConst 0x40 /* Disable factoring out constants */
9316 #define SQLITE_OptMask 0xff /* Mask of all disablable opts */
9319 ** Possible values for the sqlite.magic field.
9320 ** The numbers are obtained at random and have no special meaning, other
9321 ** than being distinct from one another.
9323 #define SQLITE_MAGIC_OPEN 0xa029a697 /* Database is open */
9324 #define SQLITE_MAGIC_CLOSED 0x9f3c2d33 /* Database is closed */
9325 #define SQLITE_MAGIC_SICK 0x4b771290 /* Error and awaiting close */
9326 #define SQLITE_MAGIC_BUSY 0xf03b7906 /* Database currently in use */
9327 #define SQLITE_MAGIC_ERROR 0xb5357930 /* An SQLITE_MISUSE error occurred */
9330 ** Each SQL function is defined by an instance of the following
9331 ** structure. A pointer to this structure is stored in the sqlite.aFunc
9332 ** hash table. When multiple functions have the same name, the hash table
9333 ** points to a linked list of these structures.
9335 struct FuncDef {
9336 i16 nArg; /* Number of arguments. -1 means unlimited */
9337 u8 iPrefEnc; /* Preferred text encoding (SQLITE_UTF8, 16LE, 16BE) */
9338 u8 flags; /* Some combination of SQLITE_FUNC_* */
9339 void *pUserData; /* User data parameter */
9340 FuncDef *pNext; /* Next function with same name */
9341 void (*xFunc)(sqlite3_context*,int,sqlite3_value**); /* Regular function */
9342 void (*xStep)(sqlite3_context*,int,sqlite3_value**); /* Aggregate step */
9343 void (*xFinalize)(sqlite3_context*); /* Aggregate finalizer */
9344 char *zName; /* SQL name of the function. */
9345 FuncDef *pHash; /* Next with a different name but the same hash */
9346 FuncDestructor *pDestructor; /* Reference counted destructor function */
9350 ** This structure encapsulates a user-function destructor callback (as
9351 ** configured using create_function_v2()) and a reference counter. When
9352 ** create_function_v2() is called to create a function with a destructor,
9353 ** a single object of this type is allocated. FuncDestructor.nRef is set to
9354 ** the number of FuncDef objects created (either 1 or 3, depending on whether
9355 ** or not the specified encoding is SQLITE_ANY). The FuncDef.pDestructor
9356 ** member of each of the new FuncDef objects is set to point to the allocated
9357 ** FuncDestructor.
9359 ** Thereafter, when one of the FuncDef objects is deleted, the reference
9360 ** count on this object is decremented. When it reaches 0, the destructor
9361 ** is invoked and the FuncDestructor structure freed.
9363 struct FuncDestructor {
9364 int nRef;
9365 void (*xDestroy)(void *);
9366 void *pUserData;
9370 ** Possible values for FuncDef.flags
9372 #define SQLITE_FUNC_LIKE 0x01 /* Candidate for the LIKE optimization */
9373 #define SQLITE_FUNC_CASE 0x02 /* Case-sensitive LIKE-type function */
9374 #define SQLITE_FUNC_EPHEM 0x04 /* Ephemeral. Delete with VDBE */
9375 #define SQLITE_FUNC_NEEDCOLL 0x08 /* sqlite3GetFuncCollSeq() might be called */
9376 #define SQLITE_FUNC_PRIVATE 0x10 /* Allowed for internal use only */
9377 #define SQLITE_FUNC_COUNT 0x20 /* Built-in count(*) aggregate */
9378 #define SQLITE_FUNC_COALESCE 0x40 /* Built-in coalesce() or ifnull() function */
9381 ** The following three macros, FUNCTION(), LIKEFUNC() and AGGREGATE() are
9382 ** used to create the initializers for the FuncDef structures.
9384 ** FUNCTION(zName, nArg, iArg, bNC, xFunc)
9385 ** Used to create a scalar function definition of a function zName
9386 ** implemented by C function xFunc that accepts nArg arguments. The
9387 ** value passed as iArg is cast to a (void*) and made available
9388 ** as the user-data (sqlite3_user_data()) for the function. If
9389 ** argument bNC is true, then the SQLITE_FUNC_NEEDCOLL flag is set.
9391 ** AGGREGATE(zName, nArg, iArg, bNC, xStep, xFinal)
9392 ** Used to create an aggregate function definition implemented by
9393 ** the C functions xStep and xFinal. The first four parameters
9394 ** are interpreted in the same way as the first 4 parameters to
9395 ** FUNCTION().
9397 ** LIKEFUNC(zName, nArg, pArg, flags)
9398 ** Used to create a scalar function definition of a function zName
9399 ** that accepts nArg arguments and is implemented by a call to C
9400 ** function likeFunc. Argument pArg is cast to a (void *) and made
9401 ** available as the function user-data (sqlite3_user_data()). The
9402 ** FuncDef.flags variable is set to the value passed as the flags
9403 ** parameter.
9405 #define FUNCTION(zName, nArg, iArg, bNC, xFunc) \
9406 {nArg, SQLITE_UTF8, bNC*SQLITE_FUNC_NEEDCOLL, \
9407 SQLITE_INT_TO_PTR(iArg), 0, xFunc, 0, 0, #zName, 0, 0}
9408 #define STR_FUNCTION(zName, nArg, pArg, bNC, xFunc) \
9409 {nArg, SQLITE_UTF8, bNC*SQLITE_FUNC_NEEDCOLL, \
9410 pArg, 0, xFunc, 0, 0, #zName, 0, 0}
9411 #define LIKEFUNC(zName, nArg, arg, flags) \
9412 {nArg, SQLITE_UTF8, flags, (void *)arg, 0, likeFunc, 0, 0, #zName, 0, 0}
9413 #define AGGREGATE(zName, nArg, arg, nc, xStep, xFinal) \
9414 {nArg, SQLITE_UTF8, nc*SQLITE_FUNC_NEEDCOLL, \
9415 SQLITE_INT_TO_PTR(arg), 0, 0, xStep,xFinal,#zName,0,0}
9418 ** All current savepoints are stored in a linked list starting at
9419 ** sqlite3.pSavepoint. The first element in the list is the most recently
9420 ** opened savepoint. Savepoints are added to the list by the vdbe
9421 ** OP_Savepoint instruction.
9423 struct Savepoint {
9424 char *zName; /* Savepoint name (nul-terminated) */
9425 i64 nDeferredCons; /* Number of deferred fk violations */
9426 Savepoint *pNext; /* Parent savepoint (if any) */
9430 ** The following are used as the second parameter to sqlite3Savepoint(),
9431 ** and as the P1 argument to the OP_Savepoint instruction.
9433 #define SAVEPOINT_BEGIN 0
9434 #define SAVEPOINT_RELEASE 1
9435 #define SAVEPOINT_ROLLBACK 2
9439 ** Each SQLite module (virtual table definition) is defined by an
9440 ** instance of the following structure, stored in the sqlite3.aModule
9441 ** hash table.
9443 struct Module {
9444 const sqlite3_module *pModule; /* Callback pointers */
9445 const char *zName; /* Name passed to create_module() */
9446 void *pAux; /* pAux passed to create_module() */
9447 void (*xDestroy)(void *); /* Module destructor function */
9451 ** information about each column of an SQL table is held in an instance
9452 ** of this structure.
9454 struct Column {
9455 char *zName; /* Name of this column */
9456 Expr *pDflt; /* Default value of this column */
9457 char *zDflt; /* Original text of the default value */
9458 char *zType; /* Data type for this column */
9459 char *zColl; /* Collating sequence. If NULL, use the default */
9460 u8 notNull; /* True if there is a NOT NULL constraint */
9461 u8 isPrimKey; /* True if this column is part of the PRIMARY KEY */
9462 char affinity; /* One of the SQLITE_AFF_... values */
9463 #ifndef SQLITE_OMIT_VIRTUALTABLE
9464 u8 isHidden; /* True if this column is 'hidden' */
9465 #endif
9469 ** A "Collating Sequence" is defined by an instance of the following
9470 ** structure. Conceptually, a collating sequence consists of a name and
9471 ** a comparison routine that defines the order of that sequence.
9473 ** There may two separate implementations of the collation function, one
9474 ** that processes text in UTF-8 encoding (CollSeq.xCmp) and another that
9475 ** processes text encoded in UTF-16 (CollSeq.xCmp16), using the machine
9476 ** native byte order. When a collation sequence is invoked, SQLite selects
9477 ** the version that will require the least expensive encoding
9478 ** translations, if any.
9480 ** The CollSeq.pUser member variable is an extra parameter that passed in
9481 ** as the first argument to the UTF-8 comparison function, xCmp.
9482 ** CollSeq.pUser16 is the equivalent for the UTF-16 comparison function,
9483 ** xCmp16.
9485 ** If both CollSeq.xCmp and CollSeq.xCmp16 are NULL, it means that the
9486 ** collating sequence is undefined. Indices built on an undefined
9487 ** collating sequence may not be read or written.
9489 struct CollSeq {
9490 char *zName; /* Name of the collating sequence, UTF-8 encoded */
9491 u8 enc; /* Text encoding handled by xCmp() */
9492 u8 type; /* One of the SQLITE_COLL_... values below */
9493 void *pUser; /* First argument to xCmp() */
9494 int (*xCmp)(void*,int, const void*, int, const void*);
9495 void (*xDel)(void*); /* Destructor for pUser */
9499 ** Allowed values of CollSeq.type:
9501 #define SQLITE_COLL_BINARY 1 /* The default memcmp() collating sequence */
9502 #define SQLITE_COLL_NOCASE 2 /* The built-in NOCASE collating sequence */
9503 #define SQLITE_COLL_REVERSE 3 /* The built-in REVERSE collating sequence */
9504 #define SQLITE_COLL_USER 0 /* Any other user-defined collating sequence */
9507 ** A sort order can be either ASC or DESC.
9509 #define SQLITE_SO_ASC 0 /* Sort in ascending order */
9510 #define SQLITE_SO_DESC 1 /* Sort in ascending order */
9513 ** Column affinity types.
9515 ** These used to have mnemonic name like 'i' for SQLITE_AFF_INTEGER and
9516 ** 't' for SQLITE_AFF_TEXT. But we can save a little space and improve
9517 ** the speed a little by numbering the values consecutively.
9519 ** But rather than start with 0 or 1, we begin with 'a'. That way,
9520 ** when multiple affinity types are concatenated into a string and
9521 ** used as the P4 operand, they will be more readable.
9523 ** Note also that the numeric types are grouped together so that testing
9524 ** for a numeric type is a single comparison.
9526 #define SQLITE_AFF_TEXT 'a'
9527 #define SQLITE_AFF_NONE 'b'
9528 #define SQLITE_AFF_NUMERIC 'c'
9529 #define SQLITE_AFF_INTEGER 'd'
9530 #define SQLITE_AFF_REAL 'e'
9532 #define sqlite3IsNumericAffinity(X) ((X)>=SQLITE_AFF_NUMERIC)
9535 ** The SQLITE_AFF_MASK values masks off the significant bits of an
9536 ** affinity value.
9538 #define SQLITE_AFF_MASK 0x67
9541 ** Additional bit values that can be ORed with an affinity without
9542 ** changing the affinity.
9544 #define SQLITE_JUMPIFNULL 0x08 /* jumps if either operand is NULL */
9545 #define SQLITE_STOREP2 0x10 /* Store result in reg[P2] rather than jump */
9546 #define SQLITE_NULLEQ 0x80 /* NULL=NULL */
9549 ** An object of this type is created for each virtual table present in
9550 ** the database schema.
9552 ** If the database schema is shared, then there is one instance of this
9553 ** structure for each database connection (sqlite3*) that uses the shared
9554 ** schema. This is because each database connection requires its own unique
9555 ** instance of the sqlite3_vtab* handle used to access the virtual table
9556 ** implementation. sqlite3_vtab* handles can not be shared between
9557 ** database connections, even when the rest of the in-memory database
9558 ** schema is shared, as the implementation often stores the database
9559 ** connection handle passed to it via the xConnect() or xCreate() method
9560 ** during initialization internally. This database connection handle may
9561 ** then be used by the virtual table implementation to access real tables
9562 ** within the database. So that they appear as part of the callers
9563 ** transaction, these accesses need to be made via the same database
9564 ** connection as that used to execute SQL operations on the virtual table.
9566 ** All VTable objects that correspond to a single table in a shared
9567 ** database schema are initially stored in a linked-list pointed to by
9568 ** the Table.pVTable member variable of the corresponding Table object.
9569 ** When an sqlite3_prepare() operation is required to access the virtual
9570 ** table, it searches the list for the VTable that corresponds to the
9571 ** database connection doing the preparing so as to use the correct
9572 ** sqlite3_vtab* handle in the compiled query.
9574 ** When an in-memory Table object is deleted (for example when the
9575 ** schema is being reloaded for some reason), the VTable objects are not
9576 ** deleted and the sqlite3_vtab* handles are not xDisconnect()ed
9577 ** immediately. Instead, they are moved from the Table.pVTable list to
9578 ** another linked list headed by the sqlite3.pDisconnect member of the
9579 ** corresponding sqlite3 structure. They are then deleted/xDisconnected
9580 ** next time a statement is prepared using said sqlite3*. This is done
9581 ** to avoid deadlock issues involving multiple sqlite3.mutex mutexes.
9582 ** Refer to comments above function sqlite3VtabUnlockList() for an
9583 ** explanation as to why it is safe to add an entry to an sqlite3.pDisconnect
9584 ** list without holding the corresponding sqlite3.mutex mutex.
9586 ** The memory for objects of this type is always allocated by
9587 ** sqlite3DbMalloc(), using the connection handle stored in VTable.db as
9588 ** the first argument.
9590 struct VTable {
9591 sqlite3 *db; /* Database connection associated with this table */
9592 Module *pMod; /* Pointer to module implementation */
9593 sqlite3_vtab *pVtab; /* Pointer to vtab instance */
9594 int nRef; /* Number of pointers to this structure */
9595 VTable *pNext; /* Next in linked list (see above) */
9599 ** Each SQL table is represented in memory by an instance of the
9600 ** following structure.
9602 ** Table.zName is the name of the table. The case of the original
9603 ** CREATE TABLE statement is stored, but case is not significant for
9604 ** comparisons.
9606 ** Table.nCol is the number of columns in this table. Table.aCol is a
9607 ** pointer to an array of Column structures, one for each column.
9609 ** If the table has an INTEGER PRIMARY KEY, then Table.iPKey is the index of
9610 ** the column that is that key. Otherwise Table.iPKey is negative. Note
9611 ** that the datatype of the PRIMARY KEY must be INTEGER for this field to
9612 ** be set. An INTEGER PRIMARY KEY is used as the rowid for each row of
9613 ** the table. If a table has no INTEGER PRIMARY KEY, then a random rowid
9614 ** is generated for each row of the table. TF_HasPrimaryKey is set if
9615 ** the table has any PRIMARY KEY, INTEGER or otherwise.
9617 ** Table.tnum is the page number for the root BTree page of the table in the
9618 ** database file. If Table.iDb is the index of the database table backend
9619 ** in sqlite.aDb[]. 0 is for the main database and 1 is for the file that
9620 ** holds temporary tables and indices. If TF_Ephemeral is set
9621 ** then the table is stored in a file that is automatically deleted
9622 ** when the VDBE cursor to the table is closed. In this case Table.tnum
9623 ** refers VDBE cursor number that holds the table open, not to the root
9624 ** page number. Transient tables are used to hold the results of a
9625 ** sub-query that appears instead of a real table name in the FROM clause
9626 ** of a SELECT statement.
9628 struct Table {
9629 char *zName; /* Name of the table or view */
9630 int iPKey; /* If not negative, use aCol[iPKey] as the primary key */
9631 int nCol; /* Number of columns in this table */
9632 Column *aCol; /* Information about each column */
9633 Index *pIndex; /* List of SQL indexes on this table. */
9634 int tnum; /* Root BTree node for this table (see note above) */
9635 unsigned nRowEst; /* Estimated rows in table - from sqlite_stat1 table */
9636 Select *pSelect; /* NULL for tables. Points to definition if a view. */
9637 u16 nRef; /* Number of pointers to this Table */
9638 u8 tabFlags; /* Mask of TF_* values */
9639 u8 keyConf; /* What to do in case of uniqueness conflict on iPKey */
9640 FKey *pFKey; /* Linked list of all foreign keys in this table */
9641 char *zColAff; /* String defining the affinity of each column */
9642 #ifndef SQLITE_OMIT_CHECK
9643 Expr *pCheck; /* The AND of all CHECK constraints */
9644 #endif
9645 #ifndef SQLITE_OMIT_ALTERTABLE
9646 int addColOffset; /* Offset in CREATE TABLE stmt to add a new column */
9647 #endif
9648 #ifndef SQLITE_OMIT_VIRTUALTABLE
9649 VTable *pVTable; /* List of VTable objects. */
9650 int nModuleArg; /* Number of arguments to the module */
9651 char **azModuleArg; /* Text of all module args. [0] is module name */
9652 #endif
9653 Trigger *pTrigger; /* List of triggers stored in pSchema */
9654 Schema *pSchema; /* Schema that contains this table */
9655 Table *pNextZombie; /* Next on the Parse.pZombieTab list */
9659 ** Allowed values for Tabe.tabFlags.
9661 #define TF_Readonly 0x01 /* Read-only system table */
9662 #define TF_Ephemeral 0x02 /* An ephemeral table */
9663 #define TF_HasPrimaryKey 0x04 /* Table has a primary key */
9664 #define TF_Autoincrement 0x08 /* Integer primary key is autoincrement */
9665 #define TF_Virtual 0x10 /* Is a virtual table */
9666 #define TF_NeedMetadata 0x20 /* aCol[].zType and aCol[].pColl missing */
9671 ** Test to see whether or not a table is a virtual table. This is
9672 ** done as a macro so that it will be optimized out when virtual
9673 ** table support is omitted from the build.
9675 #ifndef SQLITE_OMIT_VIRTUALTABLE
9676 # define IsVirtual(X) (((X)->tabFlags & TF_Virtual)!=0)
9677 # define IsHiddenColumn(X) ((X)->isHidden)
9678 #else
9679 # define IsVirtual(X) 0
9680 # define IsHiddenColumn(X) 0
9681 #endif
9684 ** Each foreign key constraint is an instance of the following structure.
9686 ** A foreign key is associated with two tables. The "from" table is
9687 ** the table that contains the REFERENCES clause that creates the foreign
9688 ** key. The "to" table is the table that is named in the REFERENCES clause.
9689 ** Consider this example:
9691 ** CREATE TABLE ex1(
9692 ** a INTEGER PRIMARY KEY,
9693 ** b INTEGER CONSTRAINT fk1 REFERENCES ex2(x)
9694 ** );
9696 ** For foreign key "fk1", the from-table is "ex1" and the to-table is "ex2".
9698 ** Each REFERENCES clause generates an instance of the following structure
9699 ** which is attached to the from-table. The to-table need not exist when
9700 ** the from-table is created. The existence of the to-table is not checked.
9702 struct FKey {
9703 Table *pFrom; /* Table containing the REFERENCES clause (aka: Child) */
9704 FKey *pNextFrom; /* Next foreign key in pFrom */
9705 char *zTo; /* Name of table that the key points to (aka: Parent) */
9706 FKey *pNextTo; /* Next foreign key on table named zTo */
9707 FKey *pPrevTo; /* Previous foreign key on table named zTo */
9708 int nCol; /* Number of columns in this key */
9709 /* EV: R-30323-21917 */
9710 u8 isDeferred; /* True if constraint checking is deferred till COMMIT */
9711 u8 aAction[2]; /* ON DELETE and ON UPDATE actions, respectively */
9712 Trigger *apTrigger[2]; /* Triggers for aAction[] actions */
9713 struct sColMap { /* Mapping of columns in pFrom to columns in zTo */
9714 int iFrom; /* Index of column in pFrom */
9715 char *zCol; /* Name of column in zTo. If 0 use PRIMARY KEY */
9716 } aCol[1]; /* One entry for each of nCol column s */
9720 ** SQLite supports many different ways to resolve a constraint
9721 ** error. ROLLBACK processing means that a constraint violation
9722 ** causes the operation in process to fail and for the current transaction
9723 ** to be rolled back. ABORT processing means the operation in process
9724 ** fails and any prior changes from that one operation are backed out,
9725 ** but the transaction is not rolled back. FAIL processing means that
9726 ** the operation in progress stops and returns an error code. But prior
9727 ** changes due to the same operation are not backed out and no rollback
9728 ** occurs. IGNORE means that the particular row that caused the constraint
9729 ** error is not inserted or updated. Processing continues and no error
9730 ** is returned. REPLACE means that preexisting database rows that caused
9731 ** a UNIQUE constraint violation are removed so that the new insert or
9732 ** update can proceed. Processing continues and no error is reported.
9734 ** RESTRICT, SETNULL, and CASCADE actions apply only to foreign keys.
9735 ** RESTRICT is the same as ABORT for IMMEDIATE foreign keys and the
9736 ** same as ROLLBACK for DEFERRED keys. SETNULL means that the foreign
9737 ** key is set to NULL. CASCADE means that a DELETE or UPDATE of the
9738 ** referenced table row is propagated into the row that holds the
9739 ** foreign key.
9741 ** The following symbolic values are used to record which type
9742 ** of action to take.
9744 #define OE_None 0 /* There is no constraint to check */
9745 #define OE_Rollback 1 /* Fail the operation and rollback the transaction */
9746 #define OE_Abort 2 /* Back out changes but do no rollback transaction */
9747 #define OE_Fail 3 /* Stop the operation but leave all prior changes */
9748 #define OE_Ignore 4 /* Ignore the error. Do not do the INSERT or UPDATE */
9749 #define OE_Replace 5 /* Delete existing record, then do INSERT or UPDATE */
9751 #define OE_Restrict 6 /* OE_Abort for IMMEDIATE, OE_Rollback for DEFERRED */
9752 #define OE_SetNull 7 /* Set the foreign key value to NULL */
9753 #define OE_SetDflt 8 /* Set the foreign key value to its default */
9754 #define OE_Cascade 9 /* Cascade the changes */
9756 #define OE_Default 99 /* Do whatever the default action is */
9760 ** An instance of the following structure is passed as the first
9761 ** argument to sqlite3VdbeKeyCompare and is used to control the
9762 ** comparison of the two index keys.
9764 struct KeyInfo {
9765 sqlite3 *db; /* The database connection */
9766 u8 enc; /* Text encoding - one of the SQLITE_UTF* values */
9767 u16 nField; /* Number of entries in aColl[] */
9768 u8 *aSortOrder; /* Sort order for each column. May be NULL */
9769 CollSeq *aColl[1]; /* Collating sequence for each term of the key */
9773 ** An instance of the following structure holds information about a
9774 ** single index record that has already been parsed out into individual
9775 ** values.
9777 ** A record is an object that contains one or more fields of data.
9778 ** Records are used to store the content of a table row and to store
9779 ** the key of an index. A blob encoding of a record is created by
9780 ** the OP_MakeRecord opcode of the VDBE and is disassembled by the
9781 ** OP_Column opcode.
9783 ** This structure holds a record that has already been disassembled
9784 ** into its constituent fields.
9786 struct UnpackedRecord {
9787 KeyInfo *pKeyInfo; /* Collation and sort-order information */
9788 u16 nField; /* Number of entries in apMem[] */
9789 u16 flags; /* Boolean settings. UNPACKED_... below */
9790 i64 rowid; /* Used by UNPACKED_PREFIX_SEARCH */
9791 Mem *aMem; /* Values */
9795 ** Allowed values of UnpackedRecord.flags
9797 #define UNPACKED_NEED_FREE 0x0001 /* Memory is from sqlite3Malloc() */
9798 #define UNPACKED_NEED_DESTROY 0x0002 /* apMem[]s should all be destroyed */
9799 #define UNPACKED_IGNORE_ROWID 0x0004 /* Ignore trailing rowid on key1 */
9800 #define UNPACKED_INCRKEY 0x0008 /* Make this key an epsilon larger */
9801 #define UNPACKED_PREFIX_MATCH 0x0010 /* A prefix match is considered OK */
9802 #define UNPACKED_PREFIX_SEARCH 0x0020 /* A prefix match is considered OK */
9805 ** Each SQL index is represented in memory by an
9806 ** instance of the following structure.
9808 ** The columns of the table that are to be indexed are described
9809 ** by the aiColumn[] field of this structure. For example, suppose
9810 ** we have the following table and index:
9812 ** CREATE TABLE Ex1(c1 int, c2 int, c3 text);
9813 ** CREATE INDEX Ex2 ON Ex1(c3,c1);
9815 ** In the Table structure describing Ex1, nCol==3 because there are
9816 ** three columns in the table. In the Index structure describing
9817 ** Ex2, nColumn==2 since 2 of the 3 columns of Ex1 are indexed.
9818 ** The value of aiColumn is {2, 0}. aiColumn[0]==2 because the
9819 ** first column to be indexed (c3) has an index of 2 in Ex1.aCol[].
9820 ** The second column to be indexed (c1) has an index of 0 in
9821 ** Ex1.aCol[], hence Ex2.aiColumn[1]==0.
9823 ** The Index.onError field determines whether or not the indexed columns
9824 ** must be unique and what to do if they are not. When Index.onError=OE_None,
9825 ** it means this is not a unique index. Otherwise it is a unique index
9826 ** and the value of Index.onError indicate the which conflict resolution
9827 ** algorithm to employ whenever an attempt is made to insert a non-unique
9828 ** element.
9830 struct Index {
9831 char *zName; /* Name of this index */
9832 int nColumn; /* Number of columns in the table used by this index */
9833 int *aiColumn; /* Which columns are used by this index. 1st is 0 */
9834 unsigned *aiRowEst; /* Result of ANALYZE: Est. rows selected by each column */
9835 Table *pTable; /* The SQL table being indexed */
9836 int tnum; /* Page containing root of this index in database file */
9837 u8 onError; /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */
9838 u8 autoIndex; /* True if is automatically created (ex: by UNIQUE) */
9839 u8 bUnordered; /* Use this index for == or IN queries only */
9840 char *zColAff; /* String defining the affinity of each column */
9841 Index *pNext; /* The next index associated with the same table */
9842 Schema *pSchema; /* Schema containing this index */
9843 u8 *aSortOrder; /* Array of size Index.nColumn. True==DESC, False==ASC */
9844 char **azColl; /* Array of collation sequence names for index */
9845 IndexSample *aSample; /* Array of SQLITE_INDEX_SAMPLES samples */
9849 ** Each sample stored in the sqlite_stat2 table is represented in memory
9850 ** using a structure of this type.
9852 struct IndexSample {
9853 union {
9854 char *z; /* Value if eType is SQLITE_TEXT or SQLITE_BLOB */
9855 double r; /* Value if eType is SQLITE_FLOAT or SQLITE_INTEGER */
9856 } u;
9857 u8 eType; /* SQLITE_NULL, SQLITE_INTEGER ... etc. */
9858 u8 nByte; /* Size in byte of text or blob. */
9862 ** Each token coming out of the lexer is an instance of
9863 ** this structure. Tokens are also used as part of an expression.
9865 ** Note if Token.z==0 then Token.dyn and Token.n are undefined and
9866 ** may contain random values. Do not make any assumptions about Token.dyn
9867 ** and Token.n when Token.z==0.
9869 struct Token {
9870 const char *z; /* Text of the token. Not NULL-terminated! */
9871 unsigned int n; /* Number of characters in this token */
9875 ** An instance of this structure contains information needed to generate
9876 ** code for a SELECT that contains aggregate functions.
9878 ** If Expr.op==TK_AGG_COLUMN or TK_AGG_FUNCTION then Expr.pAggInfo is a
9879 ** pointer to this structure. The Expr.iColumn field is the index in
9880 ** AggInfo.aCol[] or AggInfo.aFunc[] of information needed to generate
9881 ** code for that node.
9883 ** AggInfo.pGroupBy and AggInfo.aFunc.pExpr point to fields within the
9884 ** original Select structure that describes the SELECT statement. These
9885 ** fields do not need to be freed when deallocating the AggInfo structure.
9887 struct AggInfo {
9888 u8 directMode; /* Direct rendering mode means take data directly
9889 ** from source tables rather than from accumulators */
9890 u8 useSortingIdx; /* In direct mode, reference the sorting index rather
9891 ** than the source table */
9892 int sortingIdx; /* Cursor number of the sorting index */
9893 ExprList *pGroupBy; /* The group by clause */
9894 int nSortingColumn; /* Number of columns in the sorting index */
9895 struct AggInfo_col { /* For each column used in source tables */
9896 Table *pTab; /* Source table */
9897 int iTable; /* Cursor number of the source table */
9898 int iColumn; /* Column number within the source table */
9899 int iSorterColumn; /* Column number in the sorting index */
9900 int iMem; /* Memory location that acts as accumulator */
9901 Expr *pExpr; /* The original expression */
9902 } *aCol;
9903 int nColumn; /* Number of used entries in aCol[] */
9904 int nColumnAlloc; /* Number of slots allocated for aCol[] */
9905 int nAccumulator; /* Number of columns that show through to the output.
9906 ** Additional columns are used only as parameters to
9907 ** aggregate functions */
9908 struct AggInfo_func { /* For each aggregate function */
9909 Expr *pExpr; /* Expression encoding the function */
9910 FuncDef *pFunc; /* The aggregate function implementation */
9911 int iMem; /* Memory location that acts as accumulator */
9912 int iDistinct; /* Ephemeral table used to enforce DISTINCT */
9913 } *aFunc;
9914 int nFunc; /* Number of entries in aFunc[] */
9915 int nFuncAlloc; /* Number of slots allocated for aFunc[] */
9919 ** The datatype ynVar is a signed integer, either 16-bit or 32-bit.
9920 ** Usually it is 16-bits. But if SQLITE_MAX_VARIABLE_NUMBER is greater
9921 ** than 32767 we have to make it 32-bit. 16-bit is preferred because
9922 ** it uses less memory in the Expr object, which is a big memory user
9923 ** in systems with lots of prepared statements. And few applications
9924 ** need more than about 10 or 20 variables. But some extreme users want
9925 ** to have prepared statements with over 32767 variables, and for them
9926 ** the option is available (at compile-time).
9928 #if SQLITE_MAX_VARIABLE_NUMBER<=32767
9929 typedef i16 ynVar;
9930 #else
9931 typedef int ynVar;
9932 #endif
9935 ** Each node of an expression in the parse tree is an instance
9936 ** of this structure.
9938 ** Expr.op is the opcode. The integer parser token codes are reused
9939 ** as opcodes here. For example, the parser defines TK_GE to be an integer
9940 ** code representing the ">=" operator. This same integer code is reused
9941 ** to represent the greater-than-or-equal-to operator in the expression
9942 ** tree.
9944 ** If the expression is an SQL literal (TK_INTEGER, TK_FLOAT, TK_BLOB,
9945 ** or TK_STRING), then Expr.token contains the text of the SQL literal. If
9946 ** the expression is a variable (TK_VARIABLE), then Expr.token contains the
9947 ** variable name. Finally, if the expression is an SQL function (TK_FUNCTION),
9948 ** then Expr.token contains the name of the function.
9950 ** Expr.pRight and Expr.pLeft are the left and right subexpressions of a
9951 ** binary operator. Either or both may be NULL.
9953 ** Expr.x.pList is a list of arguments if the expression is an SQL function,
9954 ** a CASE expression or an IN expression of the form "<lhs> IN (<y>, <z>...)".
9955 ** Expr.x.pSelect is used if the expression is a sub-select or an expression of
9956 ** the form "<lhs> IN (SELECT ...)". If the EP_xIsSelect bit is set in the
9957 ** Expr.flags mask, then Expr.x.pSelect is valid. Otherwise, Expr.x.pList is
9958 ** valid.
9960 ** An expression of the form ID or ID.ID refers to a column in a table.
9961 ** For such expressions, Expr.op is set to TK_COLUMN and Expr.iTable is
9962 ** the integer cursor number of a VDBE cursor pointing to that table and
9963 ** Expr.iColumn is the column number for the specific column. If the
9964 ** expression is used as a result in an aggregate SELECT, then the
9965 ** value is also stored in the Expr.iAgg column in the aggregate so that
9966 ** it can be accessed after all aggregates are computed.
9968 ** If the expression is an unbound variable marker (a question mark
9969 ** character '?' in the original SQL) then the Expr.iTable holds the index
9970 ** number for that variable.
9972 ** If the expression is a subquery then Expr.iColumn holds an integer
9973 ** register number containing the result of the subquery. If the
9974 ** subquery gives a constant result, then iTable is -1. If the subquery
9975 ** gives a different answer at different times during statement processing
9976 ** then iTable is the address of a subroutine that computes the subquery.
9978 ** If the Expr is of type OP_Column, and the table it is selecting from
9979 ** is a disk table or the "old.*" pseudo-table, then pTab points to the
9980 ** corresponding table definition.
9982 ** ALLOCATION NOTES:
9984 ** Expr objects can use a lot of memory space in database schema. To
9985 ** help reduce memory requirements, sometimes an Expr object will be
9986 ** truncated. And to reduce the number of memory allocations, sometimes
9987 ** two or more Expr objects will be stored in a single memory allocation,
9988 ** together with Expr.zToken strings.
9990 ** If the EP_Reduced and EP_TokenOnly flags are set when
9991 ** an Expr object is truncated. When EP_Reduced is set, then all
9992 ** the child Expr objects in the Expr.pLeft and Expr.pRight subtrees
9993 ** are contained within the same memory allocation. Note, however, that
9994 ** the subtrees in Expr.x.pList or Expr.x.pSelect are always separately
9995 ** allocated, regardless of whether or not EP_Reduced is set.
9997 struct Expr {
9998 u8 op; /* Operation performed by this node */
9999 char affinity; /* The affinity of the column or 0 if not a column */
10000 u16 flags; /* Various flags. EP_* See below */
10001 union {
10002 char *zToken; /* Token value. Zero terminated and dequoted */
10003 int iValue; /* Non-negative integer value if EP_IntValue */
10004 } u;
10006 /* If the EP_TokenOnly flag is set in the Expr.flags mask, then no
10007 ** space is allocated for the fields below this point. An attempt to
10008 ** access them will result in a segfault or malfunction.
10009 *********************************************************************/
10011 Expr *pLeft; /* Left subnode */
10012 Expr *pRight; /* Right subnode */
10013 union {
10014 ExprList *pList; /* Function arguments or in "<expr> IN (<expr-list)" */
10015 Select *pSelect; /* Used for sub-selects and "<expr> IN (<select>)" */
10016 } x;
10017 CollSeq *pColl; /* The collation type of the column or 0 */
10019 /* If the EP_Reduced flag is set in the Expr.flags mask, then no
10020 ** space is allocated for the fields below this point. An attempt to
10021 ** access them will result in a segfault or malfunction.
10022 *********************************************************************/
10024 int iTable; /* TK_COLUMN: cursor number of table holding column
10025 ** TK_REGISTER: register number
10026 ** TK_TRIGGER: 1 -> new, 0 -> old */
10027 ynVar iColumn; /* TK_COLUMN: column index. -1 for rowid.
10028 ** TK_VARIABLE: variable number (always >= 1). */
10029 i16 iAgg; /* Which entry in pAggInfo->aCol[] or ->aFunc[] */
10030 i16 iRightJoinTable; /* If EP_FromJoin, the right table of the join */
10031 u8 flags2; /* Second set of flags. EP2_... */
10032 u8 op2; /* If a TK_REGISTER, the original value of Expr.op */
10033 AggInfo *pAggInfo; /* Used by TK_AGG_COLUMN and TK_AGG_FUNCTION */
10034 Table *pTab; /* Table for TK_COLUMN expressions. */
10035 #if SQLITE_MAX_EXPR_DEPTH>0
10036 int nHeight; /* Height of the tree headed by this node */
10037 #endif
10041 ** The following are the meanings of bits in the Expr.flags field.
10043 #define EP_FromJoin 0x0001 /* Originated in ON or USING clause of a join */
10044 #define EP_Agg 0x0002 /* Contains one or more aggregate functions */
10045 #define EP_Resolved 0x0004 /* IDs have been resolved to COLUMNs */
10046 #define EP_Error 0x0008 /* Expression contains one or more errors */
10047 #define EP_Distinct 0x0010 /* Aggregate function with DISTINCT keyword */
10048 #define EP_VarSelect 0x0020 /* pSelect is correlated, not constant */
10049 #define EP_DblQuoted 0x0040 /* token.z was originally in "..." */
10050 #define EP_InfixFunc 0x0080 /* True for an infix function: LIKE, GLOB, etc */
10051 #define EP_ExpCollate 0x0100 /* Collating sequence specified explicitly */
10052 #define EP_FixedDest 0x0200 /* Result needed in a specific register */
10053 #define EP_IntValue 0x0400 /* Integer value contained in u.iValue */
10054 #define EP_xIsSelect 0x0800 /* x.pSelect is valid (otherwise x.pList is) */
10056 #define EP_Reduced 0x1000 /* Expr struct is EXPR_REDUCEDSIZE bytes only */
10057 #define EP_TokenOnly 0x2000 /* Expr struct is EXPR_TOKENONLYSIZE bytes only */
10058 #define EP_Static 0x4000 /* Held in memory not obtained from malloc() */
10061 ** The following are the meanings of bits in the Expr.flags2 field.
10063 #define EP2_MallocedToken 0x0001 /* Need to sqlite3DbFree() Expr.zToken */
10064 #define EP2_Irreducible 0x0002 /* Cannot EXPRDUP_REDUCE this Expr */
10067 ** The pseudo-routine sqlite3ExprSetIrreducible sets the EP2_Irreducible
10068 ** flag on an expression structure. This flag is used for VV&A only. The
10069 ** routine is implemented as a macro that only works when in debugging mode,
10070 ** so as not to burden production code.
10072 #ifdef SQLITE_DEBUG
10073 # define ExprSetIrreducible(X) (X)->flags2 |= EP2_Irreducible
10074 #else
10075 # define ExprSetIrreducible(X)
10076 #endif
10079 ** These macros can be used to test, set, or clear bits in the
10080 ** Expr.flags field.
10082 #define ExprHasProperty(E,P) (((E)->flags&(P))==(P))
10083 #define ExprHasAnyProperty(E,P) (((E)->flags&(P))!=0)
10084 #define ExprSetProperty(E,P) (E)->flags|=(P)
10085 #define ExprClearProperty(E,P) (E)->flags&=~(P)
10088 ** Macros to determine the number of bytes required by a normal Expr
10089 ** struct, an Expr struct with the EP_Reduced flag set in Expr.flags
10090 ** and an Expr struct with the EP_TokenOnly flag set.
10092 #define EXPR_FULLSIZE sizeof(Expr) /* Full size */
10093 #define EXPR_REDUCEDSIZE offsetof(Expr,iTable) /* Common features */
10094 #define EXPR_TOKENONLYSIZE offsetof(Expr,pLeft) /* Fewer features */
10097 ** Flags passed to the sqlite3ExprDup() function. See the header comment
10098 ** above sqlite3ExprDup() for details.
10100 #define EXPRDUP_REDUCE 0x0001 /* Used reduced-size Expr nodes */
10103 ** A list of expressions. Each expression may optionally have a
10104 ** name. An expr/name combination can be used in several ways, such
10105 ** as the list of "expr AS ID" fields following a "SELECT" or in the
10106 ** list of "ID = expr" items in an UPDATE. A list of expressions can
10107 ** also be used as the argument to a function, in which case the a.zName
10108 ** field is not used.
10110 struct ExprList {
10111 int nExpr; /* Number of expressions on the list */
10112 int nAlloc; /* Number of entries allocated below */
10113 int iECursor; /* VDBE Cursor associated with this ExprList */
10114 struct ExprList_item {
10115 Expr *pExpr; /* The list of expressions */
10116 char *zName; /* Token associated with this expression */
10117 char *zSpan; /* Original text of the expression */
10118 u8 sortOrder; /* 1 for DESC or 0 for ASC */
10119 u8 done; /* A flag to indicate when processing is finished */
10120 u16 iCol; /* For ORDER BY, column number in result set */
10121 u16 iAlias; /* Index into Parse.aAlias[] for zName */
10122 } *a; /* One entry for each expression */
10126 ** An instance of this structure is used by the parser to record both
10127 ** the parse tree for an expression and the span of input text for an
10128 ** expression.
10130 struct ExprSpan {
10131 Expr *pExpr; /* The expression parse tree */
10132 const char *zStart; /* First character of input text */
10133 const char *zEnd; /* One character past the end of input text */
10137 ** An instance of this structure can hold a simple list of identifiers,
10138 ** such as the list "a,b,c" in the following statements:
10140 ** INSERT INTO t(a,b,c) VALUES ...;
10141 ** CREATE INDEX idx ON t(a,b,c);
10142 ** CREATE TRIGGER trig BEFORE UPDATE ON t(a,b,c) ...;
10144 ** The IdList.a.idx field is used when the IdList represents the list of
10145 ** column names after a table name in an INSERT statement. In the statement
10147 ** INSERT INTO t(a,b,c) ...
10149 ** If "a" is the k-th column of table "t", then IdList.a[0].idx==k.
10151 struct IdList {
10152 struct IdList_item {
10153 char *zName; /* Name of the identifier */
10154 int idx; /* Index in some Table.aCol[] of a column named zName */
10155 } *a;
10156 int nId; /* Number of identifiers on the list */
10157 int nAlloc; /* Number of entries allocated for a[] below */
10161 ** The bitmask datatype defined below is used for various optimizations.
10163 ** Changing this from a 64-bit to a 32-bit type limits the number of
10164 ** tables in a join to 32 instead of 64. But it also reduces the size
10165 ** of the library by 738 bytes on ix86.
10167 typedef u64 Bitmask;
10170 ** The number of bits in a Bitmask. "BMS" means "BitMask Size".
10172 #define BMS ((int)(sizeof(Bitmask)*8))
10175 ** The following structure describes the FROM clause of a SELECT statement.
10176 ** Each table or subquery in the FROM clause is a separate element of
10177 ** the SrcList.a[] array.
10179 ** With the addition of multiple database support, the following structure
10180 ** can also be used to describe a particular table such as the table that
10181 ** is modified by an INSERT, DELETE, or UPDATE statement. In standard SQL,
10182 ** such a table must be a simple name: ID. But in SQLite, the table can
10183 ** now be identified by a database name, a dot, then the table name: ID.ID.
10185 ** The jointype starts out showing the join type between the current table
10186 ** and the next table on the list. The parser builds the list this way.
10187 ** But sqlite3SrcListShiftJoinType() later shifts the jointypes so that each
10188 ** jointype expresses the join between the table and the previous table.
10190 ** In the colUsed field, the high-order bit (bit 63) is set if the table
10191 ** contains more than 63 columns and the 64-th or later column is used.
10193 struct SrcList {
10194 i16 nSrc; /* Number of tables or subqueries in the FROM clause */
10195 i16 nAlloc; /* Number of entries allocated in a[] below */
10196 struct SrcList_item {
10197 char *zDatabase; /* Name of database holding this table */
10198 char *zName; /* Name of the table */
10199 char *zAlias; /* The "B" part of a "A AS B" phrase. zName is the "A" */
10200 Table *pTab; /* An SQL table corresponding to zName */
10201 Select *pSelect; /* A SELECT statement used in place of a table name */
10202 u8 isPopulated; /* Temporary table associated with SELECT is populated */
10203 u8 jointype; /* Type of join between this able and the previous */
10204 u8 notIndexed; /* True if there is a NOT INDEXED clause */
10205 #ifndef SQLITE_OMIT_EXPLAIN
10206 u8 iSelectId; /* If pSelect!=0, the id of the sub-select in EQP */
10207 #endif
10208 int iCursor; /* The VDBE cursor number used to access this table */
10209 Expr *pOn; /* The ON clause of a join */
10210 IdList *pUsing; /* The USING clause of a join */
10211 Bitmask colUsed; /* Bit N (1<<N) set if column N of pTab is used */
10212 char *zIndex; /* Identifier from "INDEXED BY <zIndex>" clause */
10213 Index *pIndex; /* Index structure corresponding to zIndex, if any */
10214 } a[1]; /* One entry for each identifier on the list */
10218 ** Permitted values of the SrcList.a.jointype field
10220 #define JT_INNER 0x0001 /* Any kind of inner or cross join */
10221 #define JT_CROSS 0x0002 /* Explicit use of the CROSS keyword */
10222 #define JT_NATURAL 0x0004 /* True for a "natural" join */
10223 #define JT_LEFT 0x0008 /* Left outer join */
10224 #define JT_RIGHT 0x0010 /* Right outer join */
10225 #define JT_OUTER 0x0020 /* The "OUTER" keyword is present */
10226 #define JT_ERROR 0x0040 /* unknown or unsupported join type */
10230 ** A WherePlan object holds information that describes a lookup
10231 ** strategy.
10233 ** This object is intended to be opaque outside of the where.c module.
10234 ** It is included here only so that that compiler will know how big it
10235 ** is. None of the fields in this object should be used outside of
10236 ** the where.c module.
10238 ** Within the union, pIdx is only used when wsFlags&WHERE_INDEXED is true.
10239 ** pTerm is only used when wsFlags&WHERE_MULTI_OR is true. And pVtabIdx
10240 ** is only used when wsFlags&WHERE_VIRTUALTABLE is true. It is never the
10241 ** case that more than one of these conditions is true.
10243 struct WherePlan {
10244 u32 wsFlags; /* WHERE_* flags that describe the strategy */
10245 u32 nEq; /* Number of == constraints */
10246 double nRow; /* Estimated number of rows (for EQP) */
10247 union {
10248 Index *pIdx; /* Index when WHERE_INDEXED is true */
10249 struct WhereTerm *pTerm; /* WHERE clause term for OR-search */
10250 sqlite3_index_info *pVtabIdx; /* Virtual table index to use */
10251 } u;
10255 ** For each nested loop in a WHERE clause implementation, the WhereInfo
10256 ** structure contains a single instance of this structure. This structure
10257 ** is intended to be private the the where.c module and should not be
10258 ** access or modified by other modules.
10260 ** The pIdxInfo field is used to help pick the best index on a
10261 ** virtual table. The pIdxInfo pointer contains indexing
10262 ** information for the i-th table in the FROM clause before reordering.
10263 ** All the pIdxInfo pointers are freed by whereInfoFree() in where.c.
10264 ** All other information in the i-th WhereLevel object for the i-th table
10265 ** after FROM clause ordering.
10267 struct WhereLevel {
10268 WherePlan plan; /* query plan for this element of the FROM clause */
10269 int iLeftJoin; /* Memory cell used to implement LEFT OUTER JOIN */
10270 int iTabCur; /* The VDBE cursor used to access the table */
10271 int iIdxCur; /* The VDBE cursor used to access pIdx */
10272 int addrBrk; /* Jump here to break out of the loop */
10273 int addrNxt; /* Jump here to start the next IN combination */
10274 int addrCont; /* Jump here to continue with the next loop cycle */
10275 int addrFirst; /* First instruction of interior of the loop */
10276 u8 iFrom; /* Which entry in the FROM clause */
10277 u8 op, p5; /* Opcode and P5 of the opcode that ends the loop */
10278 int p1, p2; /* Operands of the opcode used to ends the loop */
10279 union { /* Information that depends on plan.wsFlags */
10280 struct {
10281 int nIn; /* Number of entries in aInLoop[] */
10282 struct InLoop {
10283 int iCur; /* The VDBE cursor used by this IN operator */
10284 int addrInTop; /* Top of the IN loop */
10285 } *aInLoop; /* Information about each nested IN operator */
10286 } in; /* Used when plan.wsFlags&WHERE_IN_ABLE */
10287 } u;
10289 /* The following field is really not part of the current level. But
10290 ** we need a place to cache virtual table index information for each
10291 ** virtual table in the FROM clause and the WhereLevel structure is
10292 ** a convenient place since there is one WhereLevel for each FROM clause
10293 ** element.
10295 sqlite3_index_info *pIdxInfo; /* Index info for n-th source table */
10299 ** Flags appropriate for the wctrlFlags parameter of sqlite3WhereBegin()
10300 ** and the WhereInfo.wctrlFlags member.
10302 #define WHERE_ORDERBY_NORMAL 0x0000 /* No-op */
10303 #define WHERE_ORDERBY_MIN 0x0001 /* ORDER BY processing for min() func */
10304 #define WHERE_ORDERBY_MAX 0x0002 /* ORDER BY processing for max() func */
10305 #define WHERE_ONEPASS_DESIRED 0x0004 /* Want to do one-pass UPDATE/DELETE */
10306 #define WHERE_DUPLICATES_OK 0x0008 /* Ok to return a row more than once */
10307 #define WHERE_OMIT_OPEN 0x0010 /* Table cursors are already open */
10308 #define WHERE_OMIT_CLOSE 0x0020 /* Omit close of table & index cursors */
10309 #define WHERE_FORCE_TABLE 0x0040 /* Do not use an index-only search */
10310 #define WHERE_ONETABLE_ONLY 0x0080 /* Only code the 1st table in pTabList */
10313 ** The WHERE clause processing routine has two halves. The
10314 ** first part does the start of the WHERE loop and the second
10315 ** half does the tail of the WHERE loop. An instance of
10316 ** this structure is returned by the first half and passed
10317 ** into the second half to give some continuity.
10319 struct WhereInfo {
10320 Parse *pParse; /* Parsing and code generating context */
10321 u16 wctrlFlags; /* Flags originally passed to sqlite3WhereBegin() */
10322 u8 okOnePass; /* Ok to use one-pass algorithm for UPDATE or DELETE */
10323 u8 untestedTerms; /* Not all WHERE terms resolved by outer loop */
10324 SrcList *pTabList; /* List of tables in the join */
10325 int iTop; /* The very beginning of the WHERE loop */
10326 int iContinue; /* Jump here to continue with next record */
10327 int iBreak; /* Jump here to break out of the loop */
10328 int nLevel; /* Number of nested loop */
10329 struct WhereClause *pWC; /* Decomposition of the WHERE clause */
10330 double savedNQueryLoop; /* pParse->nQueryLoop outside the WHERE loop */
10331 double nRowOut; /* Estimated number of output rows */
10332 WhereLevel a[1]; /* Information about each nest loop in WHERE */
10336 ** A NameContext defines a context in which to resolve table and column
10337 ** names. The context consists of a list of tables (the pSrcList) field and
10338 ** a list of named expression (pEList). The named expression list may
10339 ** be NULL. The pSrc corresponds to the FROM clause of a SELECT or
10340 ** to the table being operated on by INSERT, UPDATE, or DELETE. The
10341 ** pEList corresponds to the result set of a SELECT and is NULL for
10342 ** other statements.
10344 ** NameContexts can be nested. When resolving names, the inner-most
10345 ** context is searched first. If no match is found, the next outer
10346 ** context is checked. If there is still no match, the next context
10347 ** is checked. This process continues until either a match is found
10348 ** or all contexts are check. When a match is found, the nRef member of
10349 ** the context containing the match is incremented.
10351 ** Each subquery gets a new NameContext. The pNext field points to the
10352 ** NameContext in the parent query. Thus the process of scanning the
10353 ** NameContext list corresponds to searching through successively outer
10354 ** subqueries looking for a match.
10356 struct NameContext {
10357 Parse *pParse; /* The parser */
10358 SrcList *pSrcList; /* One or more tables used to resolve names */
10359 ExprList *pEList; /* Optional list of named expressions */
10360 int nRef; /* Number of names resolved by this context */
10361 int nErr; /* Number of errors encountered while resolving names */
10362 u8 allowAgg; /* Aggregate functions allowed here */
10363 u8 hasAgg; /* True if aggregates are seen */
10364 u8 isCheck; /* True if resolving names in a CHECK constraint */
10365 int nDepth; /* Depth of subquery recursion. 1 for no recursion */
10366 AggInfo *pAggInfo; /* Information about aggregates at this level */
10367 NameContext *pNext; /* Next outer name context. NULL for outermost */
10371 ** An instance of the following structure contains all information
10372 ** needed to generate code for a single SELECT statement.
10374 ** nLimit is set to -1 if there is no LIMIT clause. nOffset is set to 0.
10375 ** If there is a LIMIT clause, the parser sets nLimit to the value of the
10376 ** limit and nOffset to the value of the offset (or 0 if there is not
10377 ** offset). But later on, nLimit and nOffset become the memory locations
10378 ** in the VDBE that record the limit and offset counters.
10380 ** addrOpenEphm[] entries contain the address of OP_OpenEphemeral opcodes.
10381 ** These addresses must be stored so that we can go back and fill in
10382 ** the P4_KEYINFO and P2 parameters later. Neither the KeyInfo nor
10383 ** the number of columns in P2 can be computed at the same time
10384 ** as the OP_OpenEphm instruction is coded because not
10385 ** enough information about the compound query is known at that point.
10386 ** The KeyInfo for addrOpenTran[0] and [1] contains collating sequences
10387 ** for the result set. The KeyInfo for addrOpenTran[2] contains collating
10388 ** sequences for the ORDER BY clause.
10390 struct Select {
10391 ExprList *pEList; /* The fields of the result */
10392 u8 op; /* One of: TK_UNION TK_ALL TK_INTERSECT TK_EXCEPT */
10393 char affinity; /* MakeRecord with this affinity for SRT_Set */
10394 u16 selFlags; /* Various SF_* values */
10395 SrcList *pSrc; /* The FROM clause */
10396 Expr *pWhere; /* The WHERE clause */
10397 ExprList *pGroupBy; /* The GROUP BY clause */
10398 Expr *pHaving; /* The HAVING clause */
10399 ExprList *pOrderBy; /* The ORDER BY clause */
10400 Select *pPrior; /* Prior select in a compound select statement */
10401 Select *pNext; /* Next select to the left in a compound */
10402 Select *pRightmost; /* Right-most select in a compound select statement */
10403 Expr *pLimit; /* LIMIT expression. NULL means not used. */
10404 Expr *pOffset; /* OFFSET expression. NULL means not used. */
10405 int iLimit, iOffset; /* Memory registers holding LIMIT & OFFSET counters */
10406 int addrOpenEphm[3]; /* OP_OpenEphem opcodes related to this select */
10407 double nSelectRow; /* Estimated number of result rows */
10411 ** Allowed values for Select.selFlags. The "SF" prefix stands for
10412 ** "Select Flag".
10414 #define SF_Distinct 0x0001 /* Output should be DISTINCT */
10415 #define SF_Resolved 0x0002 /* Identifiers have been resolved */
10416 #define SF_Aggregate 0x0004 /* Contains aggregate functions */
10417 #define SF_UsesEphemeral 0x0008 /* Uses the OpenEphemeral opcode */
10418 #define SF_Expanded 0x0010 /* sqlite3SelectExpand() called on this */
10419 #define SF_HasTypeInfo 0x0020 /* FROM subqueries have Table metadata */
10423 ** The results of a select can be distributed in several ways. The
10424 ** "SRT" prefix means "SELECT Result Type".
10426 #define SRT_Union 1 /* Store result as keys in an index */
10427 #define SRT_Except 2 /* Remove result from a UNION index */
10428 #define SRT_Exists 3 /* Store 1 if the result is not empty */
10429 #define SRT_Discard 4 /* Do not save the results anywhere */
10431 /* The ORDER BY clause is ignored for all of the above */
10432 #define IgnorableOrderby(X) ((X->eDest)<=SRT_Discard)
10434 #define SRT_Output 5 /* Output each row of result */
10435 #define SRT_Mem 6 /* Store result in a memory cell */
10436 #define SRT_Set 7 /* Store results as keys in an index */
10437 #define SRT_Table 8 /* Store result as data with an automatic rowid */
10438 #define SRT_EphemTab 9 /* Create transient tab and store like SRT_Table */
10439 #define SRT_Coroutine 10 /* Generate a single row of result */
10442 ** A structure used to customize the behavior of sqlite3Select(). See
10443 ** comments above sqlite3Select() for details.
10445 typedef struct SelectDest SelectDest;
10446 struct SelectDest {
10447 u8 eDest; /* How to dispose of the results */
10448 u8 affinity; /* Affinity used when eDest==SRT_Set */
10449 int iParm; /* A parameter used by the eDest disposal method */
10450 int iMem; /* Base register where results are written */
10451 int nMem; /* Number of registers allocated */
10455 ** During code generation of statements that do inserts into AUTOINCREMENT
10456 ** tables, the following information is attached to the Table.u.autoInc.p
10457 ** pointer of each autoincrement table to record some side information that
10458 ** the code generator needs. We have to keep per-table autoincrement
10459 ** information in case inserts are down within triggers. Triggers do not
10460 ** normally coordinate their activities, but we do need to coordinate the
10461 ** loading and saving of autoincrement information.
10463 struct AutoincInfo {
10464 AutoincInfo *pNext; /* Next info block in a list of them all */
10465 Table *pTab; /* Table this info block refers to */
10466 int iDb; /* Index in sqlite3.aDb[] of database holding pTab */
10467 int regCtr; /* Memory register holding the rowid counter */
10471 ** Size of the column cache
10473 #ifndef SQLITE_N_COLCACHE
10474 # define SQLITE_N_COLCACHE 10
10475 #endif
10478 ** At least one instance of the following structure is created for each
10479 ** trigger that may be fired while parsing an INSERT, UPDATE or DELETE
10480 ** statement. All such objects are stored in the linked list headed at
10481 ** Parse.pTriggerPrg and deleted once statement compilation has been
10482 ** completed.
10484 ** A Vdbe sub-program that implements the body and WHEN clause of trigger
10485 ** TriggerPrg.pTrigger, assuming a default ON CONFLICT clause of
10486 ** TriggerPrg.orconf, is stored in the TriggerPrg.pProgram variable.
10487 ** The Parse.pTriggerPrg list never contains two entries with the same
10488 ** values for both pTrigger and orconf.
10490 ** The TriggerPrg.aColmask[0] variable is set to a mask of old.* columns
10491 ** accessed (or set to 0 for triggers fired as a result of INSERT
10492 ** statements). Similarly, the TriggerPrg.aColmask[1] variable is set to
10493 ** a mask of new.* columns used by the program.
10495 struct TriggerPrg {
10496 Trigger *pTrigger; /* Trigger this program was coded from */
10497 int orconf; /* Default ON CONFLICT policy */
10498 SubProgram *pProgram; /* Program implementing pTrigger/orconf */
10499 u32 aColmask[2]; /* Masks of old.*, new.* columns accessed */
10500 TriggerPrg *pNext; /* Next entry in Parse.pTriggerPrg list */
10504 ** The yDbMask datatype for the bitmask of all attached databases.
10506 #if SQLITE_MAX_ATTACHED>30
10507 typedef sqlite3_uint64 yDbMask;
10508 #else
10509 typedef unsigned int yDbMask;
10510 #endif
10513 ** An SQL parser context. A copy of this structure is passed through
10514 ** the parser and down into all the parser action routine in order to
10515 ** carry around information that is global to the entire parse.
10517 ** The structure is divided into two parts. When the parser and code
10518 ** generate call themselves recursively, the first part of the structure
10519 ** is constant but the second part is reset at the beginning and end of
10520 ** each recursion.
10522 ** The nTableLock and aTableLock variables are only used if the shared-cache
10523 ** feature is enabled (if sqlite3Tsd()->useSharedData is true). They are
10524 ** used to store the set of table-locks required by the statement being
10525 ** compiled. Function sqlite3TableLock() is used to add entries to the
10526 ** list.
10528 struct Parse {
10529 sqlite3 *db; /* The main database structure */
10530 int rc; /* Return code from execution */
10531 char *zErrMsg; /* An error message */
10532 Vdbe *pVdbe; /* An engine for executing database bytecode */
10533 u8 colNamesSet; /* TRUE after OP_ColumnName has been issued to pVdbe */
10534 u8 nameClash; /* A permanent table name clashes with temp table name */
10535 u8 checkSchema; /* Causes schema cookie check after an error */
10536 u8 nested; /* Number of nested calls to the parser/code generator */
10537 u8 parseError; /* True after a parsing error. Ticket #1794 */
10538 u8 nTempReg; /* Number of temporary registers in aTempReg[] */
10539 u8 nTempInUse; /* Number of aTempReg[] currently checked out */
10540 int aTempReg[8]; /* Holding area for temporary registers */
10541 int nRangeReg; /* Size of the temporary register block */
10542 int iRangeReg; /* First register in temporary register block */
10543 int nErr; /* Number of errors seen */
10544 int nTab; /* Number of previously allocated VDBE cursors */
10545 int nMem; /* Number of memory cells used so far */
10546 int nSet; /* Number of sets used so far */
10547 int ckBase; /* Base register of data during check constraints */
10548 int iCacheLevel; /* ColCache valid when aColCache[].iLevel<=iCacheLevel */
10549 int iCacheCnt; /* Counter used to generate aColCache[].lru values */
10550 u8 nColCache; /* Number of entries in the column cache */
10551 u8 iColCache; /* Next entry of the cache to replace */
10552 struct yColCache {
10553 int iTable; /* Table cursor number */
10554 int iColumn; /* Table column number */
10555 u8 tempReg; /* iReg is a temp register that needs to be freed */
10556 int iLevel; /* Nesting level */
10557 int iReg; /* Reg with value of this column. 0 means none. */
10558 int lru; /* Least recently used entry has the smallest value */
10559 } aColCache[SQLITE_N_COLCACHE]; /* One for each column cache entry */
10560 yDbMask writeMask; /* Start a write transaction on these databases */
10561 yDbMask cookieMask; /* Bitmask of schema verified databases */
10562 u8 isMultiWrite; /* True if statement may affect/insert multiple rows */
10563 u8 mayAbort; /* True if statement may throw an ABORT exception */
10564 int cookieGoto; /* Address of OP_Goto to cookie verifier subroutine */
10565 int cookieValue[SQLITE_MAX_ATTACHED+2]; /* Values of cookies to verify */
10566 #ifndef SQLITE_OMIT_SHARED_CACHE
10567 int nTableLock; /* Number of locks in aTableLock */
10568 TableLock *aTableLock; /* Required table locks for shared-cache mode */
10569 #endif
10570 int regRowid; /* Register holding rowid of CREATE TABLE entry */
10571 int regRoot; /* Register holding root page number for new objects */
10572 AutoincInfo *pAinc; /* Information about AUTOINCREMENT counters */
10573 int nMaxArg; /* Max args passed to user function by sub-program */
10575 /* Information used while coding trigger programs. */
10576 Parse *pToplevel; /* Parse structure for main program (or NULL) */
10577 Table *pTriggerTab; /* Table triggers are being coded for */
10578 u32 oldmask; /* Mask of old.* columns referenced */
10579 u32 newmask; /* Mask of new.* columns referenced */
10580 u8 eTriggerOp; /* TK_UPDATE, TK_INSERT or TK_DELETE */
10581 u8 eOrconf; /* Default ON CONFLICT policy for trigger steps */
10582 u8 disableTriggers; /* True to disable triggers */
10583 double nQueryLoop; /* Estimated number of iterations of a query */
10585 /* Above is constant between recursions. Below is reset before and after
10586 ** each recursion */
10588 int nVar; /* Number of '?' variables seen in the SQL so far */
10589 int nVarExpr; /* Number of used slots in apVarExpr[] */
10590 int nVarExprAlloc; /* Number of allocated slots in apVarExpr[] */
10591 Expr **apVarExpr; /* Pointers to :aaa and $aaaa wildcard expressions */
10592 Vdbe *pReprepare; /* VM being reprepared (sqlite3Reprepare()) */
10593 int nAlias; /* Number of aliased result set columns */
10594 int nAliasAlloc; /* Number of allocated slots for aAlias[] */
10595 int *aAlias; /* Register used to hold aliased result */
10596 u8 explain; /* True if the EXPLAIN flag is found on the query */
10597 Token sNameToken; /* Token with unqualified schema object name */
10598 Token sLastToken; /* The last token parsed */
10599 const char *zTail; /* All SQL text past the last semicolon parsed */
10600 Table *pNewTable; /* A table being constructed by CREATE TABLE */
10601 Trigger *pNewTrigger; /* Trigger under construct by a CREATE TRIGGER */
10602 const char *zAuthContext; /* The 6th parameter to db->xAuth callbacks */
10603 #ifndef SQLITE_OMIT_VIRTUALTABLE
10604 Token sArg; /* Complete text of a module argument */
10605 u8 declareVtab; /* True if inside sqlite3_declare_vtab() */
10606 int nVtabLock; /* Number of virtual tables to lock */
10607 Table **apVtabLock; /* Pointer to virtual tables needing locking */
10608 #endif
10609 int nHeight; /* Expression tree height of current sub-select */
10610 Table *pZombieTab; /* List of Table objects to delete after code gen */
10611 TriggerPrg *pTriggerPrg; /* Linked list of coded triggers */
10613 #ifndef SQLITE_OMIT_EXPLAIN
10614 int iSelectId;
10615 int iNextSelectId;
10616 #endif
10619 #ifdef SQLITE_OMIT_VIRTUALTABLE
10620 #define IN_DECLARE_VTAB 0
10621 #else
10622 #define IN_DECLARE_VTAB (pParse->declareVtab)
10623 #endif
10626 ** An instance of the following structure can be declared on a stack and used
10627 ** to save the Parse.zAuthContext value so that it can be restored later.
10629 struct AuthContext {
10630 const char *zAuthContext; /* Put saved Parse.zAuthContext here */
10631 Parse *pParse; /* The Parse structure */
10635 ** Bitfield flags for P5 value in OP_Insert and OP_Delete
10637 #define OPFLAG_NCHANGE 0x01 /* Set to update db->nChange */
10638 #define OPFLAG_LASTROWID 0x02 /* Set to update db->lastRowid */
10639 #define OPFLAG_ISUPDATE 0x04 /* This OP_Insert is an sql UPDATE */
10640 #define OPFLAG_APPEND 0x08 /* This is likely to be an append */
10641 #define OPFLAG_USESEEKRESULT 0x10 /* Try to avoid a seek in BtreeInsert() */
10642 #define OPFLAG_CLEARCACHE 0x20 /* Clear pseudo-table cache in OP_Column */
10645 * Each trigger present in the database schema is stored as an instance of
10646 * struct Trigger.
10648 * Pointers to instances of struct Trigger are stored in two ways.
10649 * 1. In the "trigHash" hash table (part of the sqlite3* that represents the
10650 * database). This allows Trigger structures to be retrieved by name.
10651 * 2. All triggers associated with a single table form a linked list, using the
10652 * pNext member of struct Trigger. A pointer to the first element of the
10653 * linked list is stored as the "pTrigger" member of the associated
10654 * struct Table.
10656 * The "step_list" member points to the first element of a linked list
10657 * containing the SQL statements specified as the trigger program.
10659 struct Trigger {
10660 char *zName; /* The name of the trigger */
10661 char *table; /* The table or view to which the trigger applies */
10662 u8 op; /* One of TK_DELETE, TK_UPDATE, TK_INSERT */
10663 u8 tr_tm; /* One of TRIGGER_BEFORE, TRIGGER_AFTER */
10664 Expr *pWhen; /* The WHEN clause of the expression (may be NULL) */
10665 IdList *pColumns; /* If this is an UPDATE OF <column-list> trigger,
10666 the <column-list> is stored here */
10667 Schema *pSchema; /* Schema containing the trigger */
10668 Schema *pTabSchema; /* Schema containing the table */
10669 TriggerStep *step_list; /* Link list of trigger program steps */
10670 Trigger *pNext; /* Next trigger associated with the table */
10674 ** A trigger is either a BEFORE or an AFTER trigger. The following constants
10675 ** determine which.
10677 ** If there are multiple triggers, you might of some BEFORE and some AFTER.
10678 ** In that cases, the constants below can be ORed together.
10680 #define TRIGGER_BEFORE 1
10681 #define TRIGGER_AFTER 2
10684 * An instance of struct TriggerStep is used to store a single SQL statement
10685 * that is a part of a trigger-program.
10687 * Instances of struct TriggerStep are stored in a singly linked list (linked
10688 * using the "pNext" member) referenced by the "step_list" member of the
10689 * associated struct Trigger instance. The first element of the linked list is
10690 * the first step of the trigger-program.
10692 * The "op" member indicates whether this is a "DELETE", "INSERT", "UPDATE" or
10693 * "SELECT" statement. The meanings of the other members is determined by the
10694 * value of "op" as follows:
10696 * (op == TK_INSERT)
10697 * orconf -> stores the ON CONFLICT algorithm
10698 * pSelect -> If this is an INSERT INTO ... SELECT ... statement, then
10699 * this stores a pointer to the SELECT statement. Otherwise NULL.
10700 * target -> A token holding the quoted name of the table to insert into.
10701 * pExprList -> If this is an INSERT INTO ... VALUES ... statement, then
10702 * this stores values to be inserted. Otherwise NULL.
10703 * pIdList -> If this is an INSERT INTO ... (<column-names>) VALUES ...
10704 * statement, then this stores the column-names to be
10705 * inserted into.
10707 * (op == TK_DELETE)
10708 * target -> A token holding the quoted name of the table to delete from.
10709 * pWhere -> The WHERE clause of the DELETE statement if one is specified.
10710 * Otherwise NULL.
10712 * (op == TK_UPDATE)
10713 * target -> A token holding the quoted name of the table to update rows of.
10714 * pWhere -> The WHERE clause of the UPDATE statement if one is specified.
10715 * Otherwise NULL.
10716 * pExprList -> A list of the columns to update and the expressions to update
10717 * them to. See sqlite3Update() documentation of "pChanges"
10718 * argument.
10721 struct TriggerStep {
10722 u8 op; /* One of TK_DELETE, TK_UPDATE, TK_INSERT, TK_SELECT */
10723 u8 orconf; /* OE_Rollback etc. */
10724 Trigger *pTrig; /* The trigger that this step is a part of */
10725 Select *pSelect; /* SELECT statment or RHS of INSERT INTO .. SELECT ... */
10726 Token target; /* Target table for DELETE, UPDATE, INSERT */
10727 Expr *pWhere; /* The WHERE clause for DELETE or UPDATE steps */
10728 ExprList *pExprList; /* SET clause for UPDATE. VALUES clause for INSERT */
10729 IdList *pIdList; /* Column names for INSERT */
10730 TriggerStep *pNext; /* Next in the link-list */
10731 TriggerStep *pLast; /* Last element in link-list. Valid for 1st elem only */
10735 ** The following structure contains information used by the sqliteFix...
10736 ** routines as they walk the parse tree to make database references
10737 ** explicit.
10739 typedef struct DbFixer DbFixer;
10740 struct DbFixer {
10741 Parse *pParse; /* The parsing context. Error messages written here */
10742 const char *zDb; /* Make sure all objects are contained in this database */
10743 const char *zType; /* Type of the container - used for error messages */
10744 const Token *pName; /* Name of the container - used for error messages */
10748 ** An objected used to accumulate the text of a string where we
10749 ** do not necessarily know how big the string will be in the end.
10751 struct StrAccum {
10752 sqlite3 *db; /* Optional database for lookaside. Can be NULL */
10753 char *zBase; /* A base allocation. Not from malloc. */
10754 char *zText; /* The string collected so far */
10755 int nChar; /* Length of the string so far */
10756 int nAlloc; /* Amount of space allocated in zText */
10757 int mxAlloc; /* Maximum allowed string length */
10758 u8 mallocFailed; /* Becomes true if any memory allocation fails */
10759 u8 useMalloc; /* 0: none, 1: sqlite3DbMalloc, 2: sqlite3_malloc */
10760 u8 tooBig; /* Becomes true if string size exceeds limits */
10764 ** A pointer to this structure is used to communicate information
10765 ** from sqlite3Init and OP_ParseSchema into the sqlite3InitCallback.
10767 typedef struct {
10768 sqlite3 *db; /* The database being initialized */
10769 int iDb; /* 0 for main database. 1 for TEMP, 2.. for ATTACHed */
10770 char **pzErrMsg; /* Error message stored here */
10771 int rc; /* Result code stored here */
10772 } InitData;
10775 ** Structure containing global configuration data for the SQLite library.
10777 ** This structure also contains some state information.
10779 struct Sqlite3Config {
10780 int bMemstat; /* True to enable memory status */
10781 int bCoreMutex; /* True to enable core mutexing */
10782 int bFullMutex; /* True to enable full mutexing */
10783 int mxStrlen; /* Maximum string length */
10784 int szLookaside; /* Default lookaside buffer size */
10785 int nLookaside; /* Default lookaside buffer count */
10786 sqlite3_mem_methods m; /* Low-level memory allocation interface */
10787 sqlite3_mutex_methods mutex; /* Low-level mutex interface */
10788 sqlite3_pcache_methods pcache; /* Low-level page-cache interface */
10789 void *pHeap; /* Heap storage space */
10790 int nHeap; /* Size of pHeap[] */
10791 int mnReq, mxReq; /* Min and max heap requests sizes */
10792 void *pScratch; /* Scratch memory */
10793 int szScratch; /* Size of each scratch buffer */
10794 int nScratch; /* Number of scratch buffers */
10795 void *pPage; /* Page cache memory */
10796 int szPage; /* Size of each page in pPage[] */
10797 int nPage; /* Number of pages in pPage[] */
10798 int mxParserStack; /* maximum depth of the parser stack */
10799 int sharedCacheEnabled; /* true if shared-cache mode enabled */
10800 /* The above might be initialized to non-zero. The following need to always
10801 ** initially be zero, however. */
10802 int isInit; /* True after initialization has finished */
10803 int inProgress; /* True while initialization in progress */
10804 int isMutexInit; /* True after mutexes are initialized */
10805 int isMallocInit; /* True after malloc is initialized */
10806 int isPCacheInit; /* True after malloc is initialized */
10807 sqlite3_mutex *pInitMutex; /* Mutex used by sqlite3_initialize() */
10808 int nRefInitMutex; /* Number of users of pInitMutex */
10809 void (*xLog)(void*,int,const char*); /* Function for logging */
10810 void *pLogArg; /* First argument to xLog() */
10814 ** Context pointer passed down through the tree-walk.
10816 struct Walker {
10817 int (*xExprCallback)(Walker*, Expr*); /* Callback for expressions */
10818 int (*xSelectCallback)(Walker*,Select*); /* Callback for SELECTs */
10819 Parse *pParse; /* Parser context. */
10820 union { /* Extra data for callback */
10821 NameContext *pNC; /* Naming context */
10822 int i; /* Integer value */
10823 } u;
10826 /* Forward declarations */
10827 SQLITE_PRIVATE int sqlite3WalkExpr(Walker*, Expr*);
10828 SQLITE_PRIVATE int sqlite3WalkExprList(Walker*, ExprList*);
10829 SQLITE_PRIVATE int sqlite3WalkSelect(Walker*, Select*);
10830 SQLITE_PRIVATE int sqlite3WalkSelectExpr(Walker*, Select*);
10831 SQLITE_PRIVATE int sqlite3WalkSelectFrom(Walker*, Select*);
10834 ** Return code from the parse-tree walking primitives and their
10835 ** callbacks.
10837 #define WRC_Continue 0 /* Continue down into children */
10838 #define WRC_Prune 1 /* Omit children but continue walking siblings */
10839 #define WRC_Abort 2 /* Abandon the tree walk */
10842 ** Assuming zIn points to the first byte of a UTF-8 character,
10843 ** advance zIn to point to the first byte of the next UTF-8 character.
10845 #define SQLITE_SKIP_UTF8(zIn) { \
10846 if( (*(zIn++))>=0xc0 ){ \
10847 while( (*zIn & 0xc0)==0x80 ){ zIn++; } \
10852 ** The SQLITE_*_BKPT macros are substitutes for the error codes with
10853 ** the same name but without the _BKPT suffix. These macros invoke
10854 ** routines that report the line-number on which the error originated
10855 ** using sqlite3_log(). The routines also provide a convenient place
10856 ** to set a debugger breakpoint.
10858 SQLITE_PRIVATE int sqlite3CorruptError(int);
10859 SQLITE_PRIVATE int sqlite3MisuseError(int);
10860 SQLITE_PRIVATE int sqlite3CantopenError(int);
10861 #define SQLITE_CORRUPT_BKPT sqlite3CorruptError(__LINE__)
10862 #define SQLITE_MISUSE_BKPT sqlite3MisuseError(__LINE__)
10863 #define SQLITE_CANTOPEN_BKPT sqlite3CantopenError(__LINE__)
10867 ** FTS4 is really an extension for FTS3. It is enabled using the
10868 ** SQLITE_ENABLE_FTS3 macro. But to avoid confusion we also all
10869 ** the SQLITE_ENABLE_FTS4 macro to serve as an alisse for SQLITE_ENABLE_FTS3.
10871 #if defined(SQLITE_ENABLE_FTS4) && !defined(SQLITE_ENABLE_FTS3)
10872 # define SQLITE_ENABLE_FTS3
10873 #endif
10876 ** The ctype.h header is needed for non-ASCII systems. It is also
10877 ** needed by FTS3 when FTS3 is included in the amalgamation.
10879 #if !defined(SQLITE_ASCII) || \
10880 (defined(SQLITE_ENABLE_FTS3) && defined(SQLITE_AMALGAMATION))
10881 # include <ctype.h>
10882 #endif
10885 ** The CoreServices.h and CoreFoundation.h headers are needed for excluding a
10886 ** -journal file from Time Machine backups when its associated database has
10887 ** previously been excluded by the client code.
10889 #if defined(__APPLE__)
10890 #include <CoreServices/CoreServices.h>
10891 #include <CoreFoundation/CoreFoundation.h>
10892 #endif
10895 ** The following macros mimic the standard library functions toupper(),
10896 ** isspace(), isalnum(), isdigit() and isxdigit(), respectively. The
10897 ** sqlite versions only work for ASCII characters, regardless of locale.
10899 #ifdef SQLITE_ASCII
10900 # define sqlite3Toupper(x) ((x)&~(sqlite3CtypeMap[(unsigned char)(x)]&0x20))
10901 # define sqlite3Isspace(x) (sqlite3CtypeMap[(unsigned char)(x)]&0x01)
10902 # define sqlite3Isalnum(x) (sqlite3CtypeMap[(unsigned char)(x)]&0x06)
10903 # define sqlite3Isalpha(x) (sqlite3CtypeMap[(unsigned char)(x)]&0x02)
10904 # define sqlite3Isdigit(x) (sqlite3CtypeMap[(unsigned char)(x)]&0x04)
10905 # define sqlite3Isxdigit(x) (sqlite3CtypeMap[(unsigned char)(x)]&0x08)
10906 # define sqlite3Tolower(x) (sqlite3UpperToLower[(unsigned char)(x)])
10907 #else
10908 # define sqlite3Toupper(x) toupper((unsigned char)(x))
10909 # define sqlite3Isspace(x) isspace((unsigned char)(x))
10910 # define sqlite3Isalnum(x) isalnum((unsigned char)(x))
10911 # define sqlite3Isalpha(x) isalpha((unsigned char)(x))
10912 # define sqlite3Isdigit(x) isdigit((unsigned char)(x))
10913 # define sqlite3Isxdigit(x) isxdigit((unsigned char)(x))
10914 # define sqlite3Tolower(x) tolower((unsigned char)(x))
10915 #endif
10918 ** Internal function prototypes
10920 SQLITE_PRIVATE int sqlite3StrICmp(const char *, const char *);
10921 SQLITE_PRIVATE int sqlite3Strlen30(const char*);
10922 #define sqlite3StrNICmp sqlite3_strnicmp
10924 SQLITE_PRIVATE int sqlite3MallocInit(void);
10925 SQLITE_PRIVATE void sqlite3MallocEnd(void);
10926 SQLITE_PRIVATE void *sqlite3Malloc(int);
10927 SQLITE_PRIVATE void *sqlite3MallocZero(int);
10928 SQLITE_PRIVATE void *sqlite3DbMallocZero(sqlite3*, int);
10929 SQLITE_PRIVATE void *sqlite3DbMallocRaw(sqlite3*, int);
10930 SQLITE_PRIVATE char *sqlite3DbStrDup(sqlite3*,const char*);
10931 SQLITE_PRIVATE char *sqlite3DbStrNDup(sqlite3*,const char*, int);
10932 SQLITE_PRIVATE void *sqlite3Realloc(void*, int);
10933 SQLITE_PRIVATE void *sqlite3DbReallocOrFree(sqlite3 *, void *, int);
10934 SQLITE_PRIVATE void *sqlite3DbRealloc(sqlite3 *, void *, int);
10935 SQLITE_PRIVATE void sqlite3DbFree(sqlite3*, void*);
10936 SQLITE_PRIVATE int sqlite3MallocSize(void*);
10937 SQLITE_PRIVATE int sqlite3DbMallocSize(sqlite3*, void*);
10938 SQLITE_PRIVATE void *sqlite3ScratchMalloc(int);
10939 SQLITE_PRIVATE void sqlite3ScratchFree(void*);
10940 SQLITE_PRIVATE void *sqlite3PageMalloc(int);
10941 SQLITE_PRIVATE void sqlite3PageFree(void*);
10942 SQLITE_PRIVATE void sqlite3MemSetDefault(void);
10943 SQLITE_PRIVATE void sqlite3BenignMallocHooks(void (*)(void), void (*)(void));
10944 SQLITE_PRIVATE int sqlite3HeapNearlyFull(void);
10947 ** On systems with ample stack space and that support alloca(), make
10948 ** use of alloca() to obtain space for large automatic objects. By default,
10949 ** obtain space from malloc().
10951 ** The alloca() routine never returns NULL. This will cause code paths
10952 ** that deal with sqlite3StackAlloc() failures to be unreachable.
10954 #ifdef SQLITE_USE_ALLOCA
10955 # define sqlite3StackAllocRaw(D,N) alloca(N)
10956 # define sqlite3StackAllocZero(D,N) memset(alloca(N), 0, N)
10957 # define sqlite3StackFree(D,P)
10958 #else
10959 # define sqlite3StackAllocRaw(D,N) sqlite3DbMallocRaw(D,N)
10960 # define sqlite3StackAllocZero(D,N) sqlite3DbMallocZero(D,N)
10961 # define sqlite3StackFree(D,P) sqlite3DbFree(D,P)
10962 #endif
10964 #ifdef SQLITE_ENABLE_MEMSYS3
10965 SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys3(void);
10966 #endif
10967 #ifdef SQLITE_ENABLE_MEMSYS5
10968 SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys5(void);
10969 #endif
10972 #ifndef SQLITE_MUTEX_OMIT
10973 SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void);
10974 SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3NoopMutex(void);
10975 SQLITE_PRIVATE sqlite3_mutex *sqlite3MutexAlloc(int);
10976 SQLITE_PRIVATE int sqlite3MutexInit(void);
10977 SQLITE_PRIVATE int sqlite3MutexEnd(void);
10978 #endif
10980 SQLITE_PRIVATE int sqlite3StatusValue(int);
10981 SQLITE_PRIVATE void sqlite3StatusAdd(int, int);
10982 SQLITE_PRIVATE void sqlite3StatusSet(int, int);
10984 #ifndef SQLITE_OMIT_FLOATING_POINT
10985 SQLITE_PRIVATE int sqlite3IsNaN(double);
10986 #else
10987 # define sqlite3IsNaN(X) 0
10988 #endif
10990 SQLITE_PRIVATE void sqlite3VXPrintf(StrAccum*, int, const char*, va_list);
10991 #ifndef SQLITE_OMIT_TRACE
10992 SQLITE_PRIVATE void sqlite3XPrintf(StrAccum*, const char*, ...);
10993 #endif
10994 SQLITE_PRIVATE char *sqlite3MPrintf(sqlite3*,const char*, ...);
10995 SQLITE_PRIVATE char *sqlite3VMPrintf(sqlite3*,const char*, va_list);
10996 SQLITE_PRIVATE char *sqlite3MAppendf(sqlite3*,char*,const char*,...);
10997 #if defined(SQLITE_TEST) || defined(SQLITE_DEBUG)
10998 SQLITE_PRIVATE void sqlite3DebugPrintf(const char*, ...);
10999 #endif
11000 #if defined(SQLITE_TEST)
11001 SQLITE_PRIVATE void *sqlite3TestTextToPtr(const char*);
11002 #endif
11003 SQLITE_PRIVATE void sqlite3SetString(char **, sqlite3*, const char*, ...);
11004 SQLITE_PRIVATE void sqlite3ErrorMsg(Parse*, const char*, ...);
11005 SQLITE_PRIVATE int sqlite3Dequote(char*);
11006 SQLITE_PRIVATE int sqlite3KeywordCode(const unsigned char*, int);
11007 SQLITE_PRIVATE int sqlite3RunParser(Parse*, const char*, char **);
11008 SQLITE_PRIVATE void sqlite3FinishCoding(Parse*);
11009 SQLITE_PRIVATE int sqlite3GetTempReg(Parse*);
11010 SQLITE_PRIVATE void sqlite3ReleaseTempReg(Parse*,int);
11011 SQLITE_PRIVATE int sqlite3GetTempRange(Parse*,int);
11012 SQLITE_PRIVATE void sqlite3ReleaseTempRange(Parse*,int,int);
11013 SQLITE_PRIVATE Expr *sqlite3ExprAlloc(sqlite3*,int,const Token*,int);
11014 SQLITE_PRIVATE Expr *sqlite3Expr(sqlite3*,int,const char*);
11015 SQLITE_PRIVATE void sqlite3ExprAttachSubtrees(sqlite3*,Expr*,Expr*,Expr*);
11016 SQLITE_PRIVATE Expr *sqlite3PExpr(Parse*, int, Expr*, Expr*, const Token*);
11017 SQLITE_PRIVATE Expr *sqlite3ExprAnd(sqlite3*,Expr*, Expr*);
11018 SQLITE_PRIVATE Expr *sqlite3ExprFunction(Parse*,ExprList*, Token*);
11019 SQLITE_PRIVATE void sqlite3ExprAssignVarNumber(Parse*, Expr*);
11020 SQLITE_PRIVATE void sqlite3ExprDelete(sqlite3*, Expr*);
11021 SQLITE_PRIVATE ExprList *sqlite3ExprListAppend(Parse*,ExprList*,Expr*);
11022 SQLITE_PRIVATE void sqlite3ExprListSetName(Parse*,ExprList*,Token*,int);
11023 SQLITE_PRIVATE void sqlite3ExprListSetSpan(Parse*,ExprList*,ExprSpan*);
11024 SQLITE_PRIVATE void sqlite3ExprListDelete(sqlite3*, ExprList*);
11025 SQLITE_PRIVATE int sqlite3Init(sqlite3*, char**);
11026 SQLITE_PRIVATE int sqlite3InitCallback(void*, int, char**, char**);
11027 SQLITE_PRIVATE void sqlite3Pragma(Parse*,Token*,Token*,Token*,int);
11028 SQLITE_PRIVATE void sqlite3ResetInternalSchema(sqlite3*, int);
11029 SQLITE_PRIVATE void sqlite3BeginParse(Parse*,int);
11030 SQLITE_PRIVATE void sqlite3CommitInternalChanges(sqlite3*);
11031 SQLITE_PRIVATE Table *sqlite3ResultSetOfSelect(Parse*,Select*);
11032 SQLITE_PRIVATE void sqlite3OpenMasterTable(Parse *, int);
11033 SQLITE_PRIVATE void sqlite3StartTable(Parse*,Token*,Token*,int,int,int,int);
11034 SQLITE_PRIVATE void sqlite3AddColumn(Parse*,Token*);
11035 SQLITE_PRIVATE void sqlite3AddNotNull(Parse*, int);
11036 SQLITE_PRIVATE void sqlite3AddPrimaryKey(Parse*, ExprList*, int, int, int);
11037 SQLITE_PRIVATE void sqlite3AddCheckConstraint(Parse*, Expr*);
11038 SQLITE_PRIVATE void sqlite3AddColumnType(Parse*,Token*);
11039 SQLITE_PRIVATE void sqlite3AddDefaultValue(Parse*,ExprSpan*);
11040 SQLITE_PRIVATE void sqlite3AddCollateType(Parse*, Token*);
11041 SQLITE_PRIVATE void sqlite3EndTable(Parse*,Token*,Token*,Select*);
11043 SQLITE_PRIVATE Bitvec *sqlite3BitvecCreate(u32);
11044 SQLITE_PRIVATE int sqlite3BitvecTest(Bitvec*, u32);
11045 SQLITE_PRIVATE int sqlite3BitvecSet(Bitvec*, u32);
11046 SQLITE_PRIVATE void sqlite3BitvecClear(Bitvec*, u32, void*);
11047 SQLITE_PRIVATE void sqlite3BitvecDestroy(Bitvec*);
11048 SQLITE_PRIVATE u32 sqlite3BitvecSize(Bitvec*);
11049 SQLITE_PRIVATE int sqlite3BitvecBuiltinTest(int,int*);
11051 SQLITE_PRIVATE RowSet *sqlite3RowSetInit(sqlite3*, void*, unsigned int);
11052 SQLITE_PRIVATE void sqlite3RowSetClear(RowSet*);
11053 SQLITE_PRIVATE void sqlite3RowSetInsert(RowSet*, i64);
11054 SQLITE_PRIVATE int sqlite3RowSetTest(RowSet*, u8 iBatch, i64);
11055 SQLITE_PRIVATE int sqlite3RowSetNext(RowSet*, i64*);
11057 SQLITE_PRIVATE void sqlite3CreateView(Parse*,Token*,Token*,Token*,Select*,int,int);
11059 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
11060 SQLITE_PRIVATE int sqlite3ViewGetColumnNames(Parse*,Table*);
11061 #else
11062 # define sqlite3ViewGetColumnNames(A,B) 0
11063 #endif
11065 SQLITE_PRIVATE void sqlite3DropTable(Parse*, SrcList*, int, int);
11066 SQLITE_PRIVATE void sqlite3DeleteTable(sqlite3*, Table*);
11067 #ifndef SQLITE_OMIT_AUTOINCREMENT
11068 SQLITE_PRIVATE void sqlite3AutoincrementBegin(Parse *pParse);
11069 SQLITE_PRIVATE void sqlite3AutoincrementEnd(Parse *pParse);
11070 #else
11071 # define sqlite3AutoincrementBegin(X)
11072 # define sqlite3AutoincrementEnd(X)
11073 #endif
11074 SQLITE_PRIVATE void sqlite3Insert(Parse*, SrcList*, ExprList*, Select*, IdList*, int);
11075 SQLITE_PRIVATE void *sqlite3ArrayAllocate(sqlite3*,void*,int,int,int*,int*,int*);
11076 SQLITE_PRIVATE IdList *sqlite3IdListAppend(sqlite3*, IdList*, Token*);
11077 SQLITE_PRIVATE int sqlite3IdListIndex(IdList*,const char*);
11078 SQLITE_PRIVATE SrcList *sqlite3SrcListEnlarge(sqlite3*, SrcList*, int, int);
11079 SQLITE_PRIVATE SrcList *sqlite3SrcListAppend(sqlite3*, SrcList*, Token*, Token*);
11080 SQLITE_PRIVATE SrcList *sqlite3SrcListAppendFromTerm(Parse*, SrcList*, Token*, Token*,
11081 Token*, Select*, Expr*, IdList*);
11082 SQLITE_PRIVATE void sqlite3SrcListIndexedBy(Parse *, SrcList *, Token *);
11083 SQLITE_PRIVATE int sqlite3IndexedByLookup(Parse *, struct SrcList_item *);
11084 SQLITE_PRIVATE void sqlite3SrcListShiftJoinType(SrcList*);
11085 SQLITE_PRIVATE void sqlite3SrcListAssignCursors(Parse*, SrcList*);
11086 SQLITE_PRIVATE void sqlite3IdListDelete(sqlite3*, IdList*);
11087 SQLITE_PRIVATE void sqlite3SrcListDelete(sqlite3*, SrcList*);
11088 SQLITE_PRIVATE Index *sqlite3CreateIndex(Parse*,Token*,Token*,SrcList*,ExprList*,int,Token*,
11089 Token*, int, int);
11090 SQLITE_PRIVATE void sqlite3DropIndex(Parse*, SrcList*, int);
11091 SQLITE_PRIVATE int sqlite3Select(Parse*, Select*, SelectDest*);
11092 SQLITE_PRIVATE Select *sqlite3SelectNew(Parse*,ExprList*,SrcList*,Expr*,ExprList*,
11093 Expr*,ExprList*,int,Expr*,Expr*);
11094 SQLITE_PRIVATE void sqlite3SelectDelete(sqlite3*, Select*);
11095 SQLITE_PRIVATE Table *sqlite3SrcListLookup(Parse*, SrcList*);
11096 SQLITE_PRIVATE int sqlite3IsReadOnly(Parse*, Table*, int);
11097 SQLITE_PRIVATE void sqlite3OpenTable(Parse*, int iCur, int iDb, Table*, int);
11098 #if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY)
11099 SQLITE_PRIVATE Expr *sqlite3LimitWhere(Parse *, SrcList *, Expr *, ExprList *, Expr *, Expr *, char *);
11100 #endif
11101 SQLITE_PRIVATE void sqlite3DeleteFrom(Parse*, SrcList*, Expr*);
11102 SQLITE_PRIVATE void sqlite3Update(Parse*, SrcList*, ExprList*, Expr*, int);
11103 SQLITE_PRIVATE WhereInfo *sqlite3WhereBegin(Parse*, SrcList*, Expr*, ExprList**, u16);
11104 SQLITE_PRIVATE void sqlite3WhereEnd(WhereInfo*);
11105 SQLITE_PRIVATE int sqlite3ExprCodeGetColumn(Parse*, Table*, int, int, int);
11106 SQLITE_PRIVATE void sqlite3ExprCodeGetColumnOfTable(Vdbe*, Table*, int, int, int);
11107 SQLITE_PRIVATE void sqlite3ExprCodeMove(Parse*, int, int, int);
11108 SQLITE_PRIVATE void sqlite3ExprCodeCopy(Parse*, int, int, int);
11109 SQLITE_PRIVATE void sqlite3ExprCacheStore(Parse*, int, int, int);
11110 SQLITE_PRIVATE void sqlite3ExprCachePush(Parse*);
11111 SQLITE_PRIVATE void sqlite3ExprCachePop(Parse*, int);
11112 SQLITE_PRIVATE void sqlite3ExprCacheRemove(Parse*, int, int);
11113 SQLITE_PRIVATE void sqlite3ExprCacheClear(Parse*);
11114 SQLITE_PRIVATE void sqlite3ExprCacheAffinityChange(Parse*, int, int);
11115 SQLITE_PRIVATE int sqlite3ExprCode(Parse*, Expr*, int);
11116 SQLITE_PRIVATE int sqlite3ExprCodeTemp(Parse*, Expr*, int*);
11117 SQLITE_PRIVATE int sqlite3ExprCodeTarget(Parse*, Expr*, int);
11118 SQLITE_PRIVATE int sqlite3ExprCodeAndCache(Parse*, Expr*, int);
11119 SQLITE_PRIVATE void sqlite3ExprCodeConstants(Parse*, Expr*);
11120 SQLITE_PRIVATE int sqlite3ExprCodeExprList(Parse*, ExprList*, int, int);
11121 SQLITE_PRIVATE void sqlite3ExprIfTrue(Parse*, Expr*, int, int);
11122 SQLITE_PRIVATE void sqlite3ExprIfFalse(Parse*, Expr*, int, int);
11123 SQLITE_PRIVATE Table *sqlite3FindTable(sqlite3*,const char*, const char*);
11124 SQLITE_PRIVATE Table *sqlite3LocateTable(Parse*,int isView,const char*, const char*);
11125 SQLITE_PRIVATE Index *sqlite3FindIndex(sqlite3*,const char*, const char*);
11126 SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTable(sqlite3*,int,const char*);
11127 SQLITE_PRIVATE void sqlite3UnlinkAndDeleteIndex(sqlite3*,int,const char*);
11128 SQLITE_PRIVATE void sqlite3Vacuum(Parse*);
11129 SQLITE_PRIVATE int sqlite3RunVacuum(char**, sqlite3*);
11130 SQLITE_PRIVATE char *sqlite3NameFromToken(sqlite3*, Token*);
11131 SQLITE_PRIVATE int sqlite3ExprCompare(Expr*, Expr*);
11132 SQLITE_PRIVATE int sqlite3ExprListCompare(ExprList*, ExprList*);
11133 SQLITE_PRIVATE void sqlite3ExprAnalyzeAggregates(NameContext*, Expr*);
11134 SQLITE_PRIVATE void sqlite3ExprAnalyzeAggList(NameContext*,ExprList*);
11135 SQLITE_PRIVATE Vdbe *sqlite3GetVdbe(Parse*);
11136 SQLITE_PRIVATE void sqlite3PrngSaveState(void);
11137 SQLITE_PRIVATE void sqlite3PrngRestoreState(void);
11138 SQLITE_PRIVATE void sqlite3PrngResetState(void);
11139 SQLITE_PRIVATE void sqlite3RollbackAll(sqlite3*);
11140 SQLITE_PRIVATE void sqlite3CodeVerifySchema(Parse*, int);
11141 SQLITE_PRIVATE void sqlite3CodeVerifyNamedSchema(Parse*, const char *zDb);
11142 SQLITE_PRIVATE void sqlite3BeginTransaction(Parse*, int);
11143 SQLITE_PRIVATE void sqlite3CommitTransaction(Parse*);
11144 SQLITE_PRIVATE void sqlite3RollbackTransaction(Parse*);
11145 SQLITE_PRIVATE void sqlite3Savepoint(Parse*, int, Token*);
11146 SQLITE_PRIVATE void sqlite3CloseSavepoints(sqlite3 *);
11147 SQLITE_PRIVATE int sqlite3ExprIsConstant(Expr*);
11148 SQLITE_PRIVATE int sqlite3ExprIsConstantNotJoin(Expr*);
11149 SQLITE_PRIVATE int sqlite3ExprIsConstantOrFunction(Expr*);
11150 SQLITE_PRIVATE int sqlite3ExprIsInteger(Expr*, int*);
11151 SQLITE_PRIVATE int sqlite3ExprCanBeNull(const Expr*);
11152 SQLITE_PRIVATE void sqlite3ExprCodeIsNullJump(Vdbe*, const Expr*, int, int);
11153 SQLITE_PRIVATE int sqlite3ExprNeedsNoAffinityChange(const Expr*, char);
11154 SQLITE_PRIVATE int sqlite3IsRowid(const char*);
11155 SQLITE_PRIVATE void sqlite3GenerateRowDelete(Parse*, Table*, int, int, int, Trigger *, int);
11156 SQLITE_PRIVATE void sqlite3GenerateRowIndexDelete(Parse*, Table*, int, int*);
11157 SQLITE_PRIVATE int sqlite3GenerateIndexKey(Parse*, Index*, int, int, int);
11158 SQLITE_PRIVATE void sqlite3GenerateConstraintChecks(Parse*,Table*,int,int,
11159 int*,int,int,int,int,int*);
11160 SQLITE_PRIVATE void sqlite3CompleteInsertion(Parse*, Table*, int, int, int*, int, int, int);
11161 SQLITE_PRIVATE int sqlite3OpenTableAndIndices(Parse*, Table*, int, int);
11162 SQLITE_PRIVATE void sqlite3BeginWriteOperation(Parse*, int, int);
11163 SQLITE_PRIVATE void sqlite3MultiWrite(Parse*);
11164 SQLITE_PRIVATE void sqlite3MayAbort(Parse*);
11165 SQLITE_PRIVATE void sqlite3HaltConstraint(Parse*, int, char*, int);
11166 SQLITE_PRIVATE Expr *sqlite3ExprDup(sqlite3*,Expr*,int);
11167 SQLITE_PRIVATE ExprList *sqlite3ExprListDup(sqlite3*,ExprList*,int);
11168 SQLITE_PRIVATE SrcList *sqlite3SrcListDup(sqlite3*,SrcList*,int);
11169 SQLITE_PRIVATE IdList *sqlite3IdListDup(sqlite3*,IdList*);
11170 SQLITE_PRIVATE Select *sqlite3SelectDup(sqlite3*,Select*,int);
11171 SQLITE_PRIVATE void sqlite3FuncDefInsert(FuncDefHash*, FuncDef*);
11172 SQLITE_PRIVATE FuncDef *sqlite3FindFunction(sqlite3*,const char*,int,int,u8,int);
11173 SQLITE_PRIVATE void sqlite3RegisterBuiltinFunctions(sqlite3*);
11174 SQLITE_PRIVATE void sqlite3RegisterDateTimeFunctions(void);
11175 SQLITE_PRIVATE void sqlite3RegisterGlobalFunctions(void);
11176 SQLITE_PRIVATE int sqlite3SafetyCheckOk(sqlite3*);
11177 SQLITE_PRIVATE int sqlite3SafetyCheckSickOrOk(sqlite3*);
11178 SQLITE_PRIVATE void sqlite3ChangeCookie(Parse*, int);
11180 #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
11181 SQLITE_PRIVATE void sqlite3MaterializeView(Parse*, Table*, Expr*, int);
11182 #endif
11184 #ifndef SQLITE_OMIT_TRIGGER
11185 SQLITE_PRIVATE void sqlite3BeginTrigger(Parse*, Token*,Token*,int,int,IdList*,SrcList*,
11186 Expr*,int, int);
11187 SQLITE_PRIVATE void sqlite3FinishTrigger(Parse*, TriggerStep*, Token*);
11188 SQLITE_PRIVATE void sqlite3DropTrigger(Parse*, SrcList*, int);
11189 SQLITE_PRIVATE void sqlite3DropTriggerPtr(Parse*, Trigger*);
11190 SQLITE_PRIVATE Trigger *sqlite3TriggersExist(Parse *, Table*, int, ExprList*, int *pMask);
11191 SQLITE_PRIVATE Trigger *sqlite3TriggerList(Parse *, Table *);
11192 SQLITE_PRIVATE void sqlite3CodeRowTrigger(Parse*, Trigger *, int, ExprList*, int, Table *,
11193 int, int, int);
11194 SQLITE_PRIVATE void sqlite3CodeRowTriggerDirect(Parse *, Trigger *, Table *, int, int, int);
11195 void sqliteViewTriggers(Parse*, Table*, Expr*, int, ExprList*);
11196 SQLITE_PRIVATE void sqlite3DeleteTriggerStep(sqlite3*, TriggerStep*);
11197 SQLITE_PRIVATE TriggerStep *sqlite3TriggerSelectStep(sqlite3*,Select*);
11198 SQLITE_PRIVATE TriggerStep *sqlite3TriggerInsertStep(sqlite3*,Token*, IdList*,
11199 ExprList*,Select*,u8);
11200 SQLITE_PRIVATE TriggerStep *sqlite3TriggerUpdateStep(sqlite3*,Token*,ExprList*, Expr*, u8);
11201 SQLITE_PRIVATE TriggerStep *sqlite3TriggerDeleteStep(sqlite3*,Token*, Expr*);
11202 SQLITE_PRIVATE void sqlite3DeleteTrigger(sqlite3*, Trigger*);
11203 SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTrigger(sqlite3*,int,const char*);
11204 SQLITE_PRIVATE u32 sqlite3TriggerColmask(Parse*,Trigger*,ExprList*,int,int,Table*,int);
11205 # define sqlite3ParseToplevel(p) ((p)->pToplevel ? (p)->pToplevel : (p))
11206 #else
11207 # define sqlite3TriggersExist(B,C,D,E,F) 0
11208 # define sqlite3DeleteTrigger(A,B)
11209 # define sqlite3DropTriggerPtr(A,B)
11210 # define sqlite3UnlinkAndDeleteTrigger(A,B,C)
11211 # define sqlite3CodeRowTrigger(A,B,C,D,E,F,G,H,I)
11212 # define sqlite3CodeRowTriggerDirect(A,B,C,D,E,F)
11213 # define sqlite3TriggerList(X, Y) 0
11214 # define sqlite3ParseToplevel(p) p
11215 # define sqlite3TriggerColmask(A,B,C,D,E,F,G) 0
11216 #endif
11218 SQLITE_PRIVATE int sqlite3JoinType(Parse*, Token*, Token*, Token*);
11219 SQLITE_PRIVATE void sqlite3CreateForeignKey(Parse*, ExprList*, Token*, ExprList*, int);
11220 SQLITE_PRIVATE void sqlite3DeferForeignKey(Parse*, int);
11221 #ifndef SQLITE_OMIT_AUTHORIZATION
11222 SQLITE_PRIVATE void sqlite3AuthRead(Parse*,Expr*,Schema*,SrcList*);
11223 SQLITE_PRIVATE int sqlite3AuthCheck(Parse*,int, const char*, const char*, const char*);
11224 SQLITE_PRIVATE void sqlite3AuthContextPush(Parse*, AuthContext*, const char*);
11225 SQLITE_PRIVATE void sqlite3AuthContextPop(AuthContext*);
11226 SQLITE_PRIVATE int sqlite3AuthReadCol(Parse*, const char *, const char *, int);
11227 #else
11228 # define sqlite3AuthRead(a,b,c,d)
11229 # define sqlite3AuthCheck(a,b,c,d,e) SQLITE_OK
11230 # define sqlite3AuthContextPush(a,b,c)
11231 # define sqlite3AuthContextPop(a) ((void)(a))
11232 #endif
11233 SQLITE_PRIVATE void sqlite3Attach(Parse*, Expr*, Expr*, Expr*);
11234 SQLITE_PRIVATE void sqlite3Detach(Parse*, Expr*);
11235 SQLITE_PRIVATE int sqlite3FixInit(DbFixer*, Parse*, int, const char*, const Token*);
11236 SQLITE_PRIVATE int sqlite3FixSrcList(DbFixer*, SrcList*);
11237 SQLITE_PRIVATE int sqlite3FixSelect(DbFixer*, Select*);
11238 SQLITE_PRIVATE int sqlite3FixExpr(DbFixer*, Expr*);
11239 SQLITE_PRIVATE int sqlite3FixExprList(DbFixer*, ExprList*);
11240 SQLITE_PRIVATE int sqlite3FixTriggerStep(DbFixer*, TriggerStep*);
11241 SQLITE_PRIVATE int sqlite3AtoF(const char *z, double*, int, u8);
11242 SQLITE_PRIVATE int sqlite3GetInt32(const char *, int*);
11243 SQLITE_PRIVATE int sqlite3Atoi(const char*);
11244 SQLITE_PRIVATE int sqlite3Utf16ByteLen(const void *pData, int nChar);
11245 SQLITE_PRIVATE int sqlite3Utf8CharLen(const char *pData, int nByte);
11246 SQLITE_PRIVATE int sqlite3Utf8Read(const u8*, const u8**);
11249 ** Routines to read and write variable-length integers. These used to
11250 ** be defined locally, but now we use the varint routines in the util.c
11251 ** file. Code should use the MACRO forms below, as the Varint32 versions
11252 ** are coded to assume the single byte case is already handled (which
11253 ** the MACRO form does).
11255 SQLITE_PRIVATE int sqlite3PutVarint(unsigned char*, u64);
11256 SQLITE_PRIVATE int sqlite3PutVarint32(unsigned char*, u32);
11257 SQLITE_PRIVATE u8 sqlite3GetVarint(const unsigned char *, u64 *);
11258 SQLITE_PRIVATE u8 sqlite3GetVarint32(const unsigned char *, u32 *);
11259 SQLITE_PRIVATE int sqlite3VarintLen(u64 v);
11262 ** The header of a record consists of a sequence variable-length integers.
11263 ** These integers are almost always small and are encoded as a single byte.
11264 ** The following macros take advantage this fact to provide a fast encode
11265 ** and decode of the integers in a record header. It is faster for the common
11266 ** case where the integer is a single byte. It is a little slower when the
11267 ** integer is two or more bytes. But overall it is faster.
11269 ** The following expressions are equivalent:
11271 ** x = sqlite3GetVarint32( A, &B );
11272 ** x = sqlite3PutVarint32( A, B );
11274 ** x = getVarint32( A, B );
11275 ** x = putVarint32( A, B );
11278 #define getVarint32(A,B) (u8)((*(A)<(u8)0x80) ? ((B) = (u32)*(A)),1 : sqlite3GetVarint32((A), (u32 *)&(B)))
11279 #define putVarint32(A,B) (u8)(((u32)(B)<(u32)0x80) ? (*(A) = (unsigned char)(B)),1 : sqlite3PutVarint32((A), (B)))
11280 #define getVarint sqlite3GetVarint
11281 #define putVarint sqlite3PutVarint
11284 SQLITE_PRIVATE const char *sqlite3IndexAffinityStr(Vdbe *, Index *);
11285 SQLITE_PRIVATE void sqlite3TableAffinityStr(Vdbe *, Table *);
11286 SQLITE_PRIVATE char sqlite3CompareAffinity(Expr *pExpr, char aff2);
11287 SQLITE_PRIVATE int sqlite3IndexAffinityOk(Expr *pExpr, char idx_affinity);
11288 SQLITE_PRIVATE char sqlite3ExprAffinity(Expr *pExpr);
11289 SQLITE_PRIVATE int sqlite3Atoi64(const char*, i64*, int, u8);
11290 SQLITE_PRIVATE void sqlite3Error(sqlite3*, int, const char*,...);
11291 SQLITE_PRIVATE void *sqlite3HexToBlob(sqlite3*, const char *z, int n);
11292 SQLITE_PRIVATE int sqlite3TwoPartName(Parse *, Token *, Token *, Token **);
11293 SQLITE_PRIVATE const char *sqlite3ErrStr(int);
11294 SQLITE_PRIVATE int sqlite3ReadSchema(Parse *pParse);
11295 SQLITE_PRIVATE CollSeq *sqlite3FindCollSeq(sqlite3*,u8 enc, const char*,int);
11296 SQLITE_PRIVATE CollSeq *sqlite3LocateCollSeq(Parse *pParse, const char*zName);
11297 SQLITE_PRIVATE CollSeq *sqlite3ExprCollSeq(Parse *pParse, Expr *pExpr);
11298 SQLITE_PRIVATE Expr *sqlite3ExprSetColl(Expr*, CollSeq*);
11299 SQLITE_PRIVATE Expr *sqlite3ExprSetCollByToken(Parse *pParse, Expr*, Token*);
11300 SQLITE_PRIVATE int sqlite3CheckCollSeq(Parse *, CollSeq *);
11301 SQLITE_PRIVATE int sqlite3CheckObjectName(Parse *, const char *);
11302 SQLITE_PRIVATE void sqlite3VdbeSetChanges(sqlite3 *, int);
11303 SQLITE_PRIVATE int sqlite3AddInt64(i64*,i64);
11304 SQLITE_PRIVATE int sqlite3SubInt64(i64*,i64);
11305 SQLITE_PRIVATE int sqlite3MulInt64(i64*,i64);
11306 SQLITE_PRIVATE int sqlite3AbsInt32(int);
11308 SQLITE_PRIVATE const void *sqlite3ValueText(sqlite3_value*, u8);
11309 SQLITE_PRIVATE int sqlite3ValueBytes(sqlite3_value*, u8);
11310 SQLITE_PRIVATE void sqlite3ValueSetStr(sqlite3_value*, int, const void *,u8,
11311 void(*)(void*));
11312 SQLITE_PRIVATE void sqlite3ValueFree(sqlite3_value*);
11313 SQLITE_PRIVATE sqlite3_value *sqlite3ValueNew(sqlite3 *);
11314 SQLITE_PRIVATE char *sqlite3Utf16to8(sqlite3 *, const void*, int, u8);
11315 #ifdef SQLITE_ENABLE_STAT2
11316 SQLITE_PRIVATE char *sqlite3Utf8to16(sqlite3 *, u8, char *, int, int *);
11317 #endif
11318 SQLITE_PRIVATE int sqlite3ValueFromExpr(sqlite3 *, Expr *, u8, u8, sqlite3_value **);
11319 SQLITE_PRIVATE void sqlite3ValueApplyAffinity(sqlite3_value *, u8, u8);
11320 #ifndef SQLITE_AMALGAMATION
11321 SQLITE_PRIVATE const unsigned char sqlite3OpcodeProperty[];
11322 SQLITE_PRIVATE const unsigned char sqlite3UpperToLower[];
11323 SQLITE_PRIVATE const unsigned char sqlite3CtypeMap[];
11324 SQLITE_PRIVATE const Token sqlite3IntTokens[];
11325 SQLITE_PRIVATE SQLITE_WSD struct Sqlite3Config sqlite3Config;
11326 SQLITE_PRIVATE SQLITE_WSD FuncDefHash sqlite3GlobalFunctions;
11327 #ifndef SQLITE_OMIT_WSD
11328 SQLITE_PRIVATE int sqlite3PendingByte;
11329 #endif
11330 #endif
11331 SQLITE_PRIVATE void sqlite3RootPageMoved(sqlite3*, int, int, int);
11332 SQLITE_PRIVATE void sqlite3Reindex(Parse*, Token*, Token*);
11333 SQLITE_PRIVATE void sqlite3AlterFunctions(void);
11334 SQLITE_PRIVATE void sqlite3AlterRenameTable(Parse*, SrcList*, Token*);
11335 SQLITE_PRIVATE int sqlite3GetToken(const unsigned char *, int *);
11336 SQLITE_PRIVATE void sqlite3NestedParse(Parse*, const char*, ...);
11337 SQLITE_PRIVATE void sqlite3ExpirePreparedStatements(sqlite3*);
11338 SQLITE_PRIVATE int sqlite3CodeSubselect(Parse *, Expr *, int, int);
11339 SQLITE_PRIVATE void sqlite3SelectPrep(Parse*, Select*, NameContext*);
11340 SQLITE_PRIVATE int sqlite3ResolveExprNames(NameContext*, Expr*);
11341 SQLITE_PRIVATE void sqlite3ResolveSelectNames(Parse*, Select*, NameContext*);
11342 SQLITE_PRIVATE int sqlite3ResolveOrderGroupBy(Parse*, Select*, ExprList*, const char*);
11343 SQLITE_PRIVATE void sqlite3ColumnDefault(Vdbe *, Table *, int, int);
11344 SQLITE_PRIVATE void sqlite3AlterFinishAddColumn(Parse *, Token *);
11345 SQLITE_PRIVATE void sqlite3AlterBeginAddColumn(Parse *, SrcList *);
11346 SQLITE_PRIVATE CollSeq *sqlite3GetCollSeq(sqlite3*, u8, CollSeq *, const char*);
11347 SQLITE_PRIVATE char sqlite3AffinityType(const char*);
11348 SQLITE_PRIVATE void sqlite3Analyze(Parse*, Token*, Token*);
11349 SQLITE_PRIVATE int sqlite3InvokeBusyHandler(BusyHandler*);
11350 SQLITE_PRIVATE int sqlite3FindDb(sqlite3*, Token*);
11351 SQLITE_PRIVATE int sqlite3FindDbName(sqlite3 *, const char *);
11352 SQLITE_PRIVATE int sqlite3AnalysisLoad(sqlite3*,int iDB);
11353 SQLITE_PRIVATE void sqlite3DeleteIndexSamples(sqlite3*,Index*);
11354 SQLITE_PRIVATE void sqlite3DefaultRowEst(Index*);
11355 SQLITE_PRIVATE void sqlite3RegisterLikeFunctions(sqlite3*, int);
11356 SQLITE_PRIVATE int sqlite3IsLikeFunction(sqlite3*,Expr*,int*,char*);
11357 SQLITE_PRIVATE void sqlite3MinimumFileFormat(Parse*, int, int);
11358 SQLITE_PRIVATE void sqlite3SchemaClear(void *);
11359 SQLITE_PRIVATE Schema *sqlite3SchemaGet(sqlite3 *, Btree *);
11360 SQLITE_PRIVATE int sqlite3SchemaToIndex(sqlite3 *db, Schema *);
11361 SQLITE_PRIVATE KeyInfo *sqlite3IndexKeyinfo(Parse *, Index *);
11362 SQLITE_PRIVATE int sqlite3CreateFunc(sqlite3 *, const char *, int, int, void *,
11363 void (*)(sqlite3_context*,int,sqlite3_value **),
11364 void (*)(sqlite3_context*,int,sqlite3_value **), void (*)(sqlite3_context*),
11365 FuncDestructor *pDestructor
11367 SQLITE_PRIVATE int sqlite3ApiExit(sqlite3 *db, int);
11368 SQLITE_PRIVATE int sqlite3OpenTempDatabase(Parse *);
11370 SQLITE_PRIVATE void sqlite3StrAccumInit(StrAccum*, char*, int, int);
11371 SQLITE_PRIVATE void sqlite3StrAccumAppend(StrAccum*,const char*,int);
11372 SQLITE_PRIVATE char *sqlite3StrAccumFinish(StrAccum*);
11373 SQLITE_PRIVATE void sqlite3StrAccumReset(StrAccum*);
11374 SQLITE_PRIVATE void sqlite3SelectDestInit(SelectDest*,int,int);
11375 SQLITE_PRIVATE Expr *sqlite3CreateColumnExpr(sqlite3 *, SrcList *, int, int);
11377 SQLITE_PRIVATE void sqlite3BackupRestart(sqlite3_backup *);
11378 SQLITE_PRIVATE void sqlite3BackupUpdate(sqlite3_backup *, Pgno, const u8 *);
11381 ** The interface to the LEMON-generated parser
11383 SQLITE_PRIVATE void *sqlite3ParserAlloc(void*(*)(size_t));
11384 SQLITE_PRIVATE void sqlite3ParserFree(void*, void(*)(void*));
11385 SQLITE_PRIVATE void sqlite3Parser(void*, int, Token, Parse*);
11386 #ifdef YYTRACKMAXSTACKDEPTH
11387 SQLITE_PRIVATE int sqlite3ParserStackPeak(void*);
11388 #endif
11390 SQLITE_PRIVATE void sqlite3AutoLoadExtensions(sqlite3*);
11391 #ifndef SQLITE_OMIT_LOAD_EXTENSION
11392 SQLITE_PRIVATE void sqlite3CloseExtensions(sqlite3*);
11393 #else
11394 # define sqlite3CloseExtensions(X)
11395 #endif
11397 #ifndef SQLITE_OMIT_SHARED_CACHE
11398 SQLITE_PRIVATE void sqlite3TableLock(Parse *, int, int, u8, const char *);
11399 #else
11400 #define sqlite3TableLock(v,w,x,y,z)
11401 #endif
11403 #ifdef SQLITE_TEST
11404 SQLITE_PRIVATE int sqlite3Utf8To8(unsigned char*);
11405 #endif
11407 #ifdef SQLITE_OMIT_VIRTUALTABLE
11408 # define sqlite3VtabClear(Y)
11409 # define sqlite3VtabSync(X,Y) SQLITE_OK
11410 # define sqlite3VtabRollback(X)
11411 # define sqlite3VtabCommit(X)
11412 # define sqlite3VtabInSync(db) 0
11413 # define sqlite3VtabLock(X)
11414 # define sqlite3VtabUnlock(X)
11415 # define sqlite3VtabUnlockList(X)
11416 #else
11417 SQLITE_PRIVATE void sqlite3VtabClear(sqlite3 *db, Table*);
11418 SQLITE_PRIVATE int sqlite3VtabSync(sqlite3 *db, char **);
11419 SQLITE_PRIVATE int sqlite3VtabRollback(sqlite3 *db);
11420 SQLITE_PRIVATE int sqlite3VtabCommit(sqlite3 *db);
11421 SQLITE_PRIVATE void sqlite3VtabLock(VTable *);
11422 SQLITE_PRIVATE void sqlite3VtabUnlock(VTable *);
11423 SQLITE_PRIVATE void sqlite3VtabUnlockList(sqlite3*);
11424 # define sqlite3VtabInSync(db) ((db)->nVTrans>0 && (db)->aVTrans==0)
11425 #endif
11426 SQLITE_PRIVATE void sqlite3VtabMakeWritable(Parse*,Table*);
11427 SQLITE_PRIVATE void sqlite3VtabBeginParse(Parse*, Token*, Token*, Token*);
11428 SQLITE_PRIVATE void sqlite3VtabFinishParse(Parse*, Token*);
11429 SQLITE_PRIVATE void sqlite3VtabArgInit(Parse*);
11430 SQLITE_PRIVATE void sqlite3VtabArgExtend(Parse*, Token*);
11431 SQLITE_PRIVATE int sqlite3VtabCallCreate(sqlite3*, int, const char *, char **);
11432 SQLITE_PRIVATE int sqlite3VtabCallConnect(Parse*, Table*);
11433 SQLITE_PRIVATE int sqlite3VtabCallDestroy(sqlite3*, int, const char *);
11434 SQLITE_PRIVATE int sqlite3VtabBegin(sqlite3 *, VTable *);
11435 SQLITE_PRIVATE FuncDef *sqlite3VtabOverloadFunction(sqlite3 *,FuncDef*, int nArg, Expr*);
11436 SQLITE_PRIVATE void sqlite3InvalidFunction(sqlite3_context*,int,sqlite3_value**);
11437 SQLITE_PRIVATE int sqlite3VdbeParameterIndex(Vdbe*, const char*, int);
11438 SQLITE_PRIVATE int sqlite3TransferBindings(sqlite3_stmt *, sqlite3_stmt *);
11439 SQLITE_PRIVATE int sqlite3Reprepare(Vdbe*);
11440 SQLITE_PRIVATE void sqlite3ExprListCheckLength(Parse*, ExprList*, const char*);
11441 SQLITE_PRIVATE CollSeq *sqlite3BinaryCompareCollSeq(Parse *, Expr *, Expr *);
11442 SQLITE_PRIVATE int sqlite3TempInMemory(const sqlite3*);
11443 SQLITE_PRIVATE VTable *sqlite3GetVTable(sqlite3*, Table*);
11444 SQLITE_PRIVATE const char *sqlite3JournalModename(int);
11445 SQLITE_PRIVATE int sqlite3Checkpoint(sqlite3*, int, int, int*, int*);
11446 SQLITE_PRIVATE int sqlite3WalDefaultHook(void*,sqlite3*,const char*,int);
11448 /* Declarations for functions in fkey.c. All of these are replaced by
11449 ** no-op macros if OMIT_FOREIGN_KEY is defined. In this case no foreign
11450 ** key functionality is available. If OMIT_TRIGGER is defined but
11451 ** OMIT_FOREIGN_KEY is not, only some of the functions are no-oped. In
11452 ** this case foreign keys are parsed, but no other functionality is
11453 ** provided (enforcement of FK constraints requires the triggers sub-system).
11455 #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
11456 SQLITE_PRIVATE void sqlite3FkCheck(Parse*, Table*, int, int);
11457 SQLITE_PRIVATE void sqlite3FkDropTable(Parse*, SrcList *, Table*);
11458 SQLITE_PRIVATE void sqlite3FkActions(Parse*, Table*, ExprList*, int);
11459 SQLITE_PRIVATE int sqlite3FkRequired(Parse*, Table*, int*, int);
11460 SQLITE_PRIVATE u32 sqlite3FkOldmask(Parse*, Table*);
11461 SQLITE_PRIVATE FKey *sqlite3FkReferences(Table *);
11462 #else
11463 #define sqlite3FkActions(a,b,c,d)
11464 #define sqlite3FkCheck(a,b,c,d)
11465 #define sqlite3FkDropTable(a,b,c)
11466 #define sqlite3FkOldmask(a,b) 0
11467 #define sqlite3FkRequired(a,b,c,d) 0
11468 #endif
11469 #ifndef SQLITE_OMIT_FOREIGN_KEY
11470 SQLITE_PRIVATE void sqlite3FkDelete(sqlite3 *, Table*);
11471 #else
11472 #define sqlite3FkDelete(a,b)
11473 #endif
11477 ** Available fault injectors. Should be numbered beginning with 0.
11479 #define SQLITE_FAULTINJECTOR_MALLOC 0
11480 #define SQLITE_FAULTINJECTOR_COUNT 1
11483 ** The interface to the code in fault.c used for identifying "benign"
11484 ** malloc failures. This is only present if SQLITE_OMIT_BUILTIN_TEST
11485 ** is not defined.
11487 #ifndef SQLITE_OMIT_BUILTIN_TEST
11488 SQLITE_PRIVATE void sqlite3BeginBenignMalloc(void);
11489 SQLITE_PRIVATE void sqlite3EndBenignMalloc(void);
11490 #else
11491 #define sqlite3BeginBenignMalloc()
11492 #define sqlite3EndBenignMalloc()
11493 #endif
11495 #define IN_INDEX_ROWID 1
11496 #define IN_INDEX_EPH 2
11497 #define IN_INDEX_INDEX 3
11498 SQLITE_PRIVATE int sqlite3FindInIndex(Parse *, Expr *, int*);
11500 #ifdef SQLITE_ENABLE_ATOMIC_WRITE
11501 SQLITE_PRIVATE int sqlite3JournalOpen(sqlite3_vfs *, const char *, sqlite3_file *, int, int);
11502 SQLITE_PRIVATE int sqlite3JournalSize(sqlite3_vfs *);
11503 SQLITE_PRIVATE int sqlite3JournalCreate(sqlite3_file *);
11504 #else
11505 #define sqlite3JournalSize(pVfs) ((pVfs)->szOsFile)
11506 #endif
11508 SQLITE_PRIVATE void sqlite3MemJournalOpen(sqlite3_file *);
11509 SQLITE_PRIVATE int sqlite3MemJournalSize(void);
11510 SQLITE_PRIVATE int sqlite3IsMemJournal(sqlite3_file *);
11512 #if SQLITE_MAX_EXPR_DEPTH>0
11513 SQLITE_PRIVATE void sqlite3ExprSetHeight(Parse *pParse, Expr *p);
11514 SQLITE_PRIVATE int sqlite3SelectExprHeight(Select *);
11515 SQLITE_PRIVATE int sqlite3ExprCheckHeight(Parse*, int);
11516 #else
11517 #define sqlite3ExprSetHeight(x,y)
11518 #define sqlite3SelectExprHeight(x) 0
11519 #define sqlite3ExprCheckHeight(x,y)
11520 #endif
11522 SQLITE_PRIVATE u32 sqlite3Get4byte(const u8*);
11523 SQLITE_PRIVATE void sqlite3Put4byte(u8*, u32);
11525 #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
11526 SQLITE_PRIVATE void sqlite3ConnectionBlocked(sqlite3 *, sqlite3 *);
11527 SQLITE_PRIVATE void sqlite3ConnectionUnlocked(sqlite3 *db);
11528 SQLITE_PRIVATE void sqlite3ConnectionClosed(sqlite3 *db);
11529 #else
11530 #define sqlite3ConnectionBlocked(x,y)
11531 #define sqlite3ConnectionUnlocked(x)
11532 #define sqlite3ConnectionClosed(x)
11533 #endif
11535 #ifdef SQLITE_DEBUG
11536 SQLITE_PRIVATE void sqlite3ParserTrace(FILE*, char *);
11537 #endif
11540 ** If the SQLITE_ENABLE IOTRACE exists then the global variable
11541 ** sqlite3IoTrace is a pointer to a printf-like routine used to
11542 ** print I/O tracing messages.
11544 #ifdef SQLITE_ENABLE_IOTRACE
11545 # define IOTRACE(A) if( sqlite3IoTrace ){ sqlite3IoTrace A; }
11546 SQLITE_PRIVATE void sqlite3VdbeIOTraceSql(Vdbe*);
11547 SQLITE_PRIVATE void (*sqlite3IoTrace)(const char*,...);
11548 #else
11549 # define IOTRACE(A)
11550 # define sqlite3VdbeIOTraceSql(X)
11551 #endif
11554 ** These routines are available for the mem2.c debugging memory allocator
11555 ** only. They are used to verify that different "types" of memory
11556 ** allocations are properly tracked by the system.
11558 ** sqlite3MemdebugSetType() sets the "type" of an allocation to one of
11559 ** the MEMTYPE_* macros defined below. The type must be a bitmask with
11560 ** a single bit set.
11562 ** sqlite3MemdebugHasType() returns true if any of the bits in its second
11563 ** argument match the type set by the previous sqlite3MemdebugSetType().
11564 ** sqlite3MemdebugHasType() is intended for use inside assert() statements.
11566 ** sqlite3MemdebugNoType() returns true if none of the bits in its second
11567 ** argument match the type set by the previous sqlite3MemdebugSetType().
11569 ** Perhaps the most important point is the difference between MEMTYPE_HEAP
11570 ** and MEMTYPE_LOOKASIDE. If an allocation is MEMTYPE_LOOKASIDE, that means
11571 ** it might have been allocated by lookaside, except the allocation was
11572 ** too large or lookaside was already full. It is important to verify
11573 ** that allocations that might have been satisfied by lookaside are not
11574 ** passed back to non-lookaside free() routines. Asserts such as the
11575 ** example above are placed on the non-lookaside free() routines to verify
11576 ** this constraint.
11578 ** All of this is no-op for a production build. It only comes into
11579 ** play when the SQLITE_MEMDEBUG compile-time option is used.
11581 #ifdef SQLITE_MEMDEBUG
11582 SQLITE_PRIVATE void sqlite3MemdebugSetType(void*,u8);
11583 SQLITE_PRIVATE int sqlite3MemdebugHasType(void*,u8);
11584 SQLITE_PRIVATE int sqlite3MemdebugNoType(void*,u8);
11585 #else
11586 # define sqlite3MemdebugSetType(X,Y) /* no-op */
11587 # define sqlite3MemdebugHasType(X,Y) 1
11588 # define sqlite3MemdebugNoType(X,Y) 1
11589 #endif
11590 #define MEMTYPE_HEAP 0x01 /* General heap allocations */
11591 #define MEMTYPE_LOOKASIDE 0x02 /* Might have been lookaside memory */
11592 #define MEMTYPE_SCRATCH 0x04 /* Scratch allocations */
11593 #define MEMTYPE_PCACHE 0x08 /* Page cache allocations */
11594 #define MEMTYPE_DB 0x10 /* Uses sqlite3DbMalloc, not sqlite_malloc */
11596 #endif /* _SQLITEINT_H_ */
11598 /************** End of sqliteInt.h *******************************************/
11599 /************** Begin file global.c ******************************************/
11601 ** 2008 June 13
11603 ** The author disclaims copyright to this source code. In place of
11604 ** a legal notice, here is a blessing:
11606 ** May you do good and not evil.
11607 ** May you find forgiveness for yourself and forgive others.
11608 ** May you share freely, never taking more than you give.
11610 *************************************************************************
11612 ** This file contains definitions of global variables and contants.
11615 /* An array to map all upper-case characters into their corresponding
11616 ** lower-case character.
11618 ** SQLite only considers US-ASCII (or EBCDIC) characters. We do not
11619 ** handle case conversions for the UTF character set since the tables
11620 ** involved are nearly as big or bigger than SQLite itself.
11622 SQLITE_PRIVATE const unsigned char sqlite3UpperToLower[] = {
11623 #ifdef SQLITE_ASCII
11624 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17,
11625 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35,
11626 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53,
11627 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 97, 98, 99,100,101,102,103,
11628 104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119,120,121,
11629 122, 91, 92, 93, 94, 95, 96, 97, 98, 99,100,101,102,103,104,105,106,107,
11630 108,109,110,111,112,113,114,115,116,117,118,119,120,121,122,123,124,125,
11631 126,127,128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,
11632 144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159,160,161,
11633 162,163,164,165,166,167,168,169,170,171,172,173,174,175,176,177,178,179,
11634 180,181,182,183,184,185,186,187,188,189,190,191,192,193,194,195,196,197,
11635 198,199,200,201,202,203,204,205,206,207,208,209,210,211,212,213,214,215,
11636 216,217,218,219,220,221,222,223,224,225,226,227,228,229,230,231,232,233,
11637 234,235,236,237,238,239,240,241,242,243,244,245,246,247,248,249,250,251,
11638 252,253,254,255
11639 #endif
11640 #ifdef SQLITE_EBCDIC
11641 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, /* 0x */
11642 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, /* 1x */
11643 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, /* 2x */
11644 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, /* 3x */
11645 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, /* 4x */
11646 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, /* 5x */
11647 96, 97, 66, 67, 68, 69, 70, 71, 72, 73,106,107,108,109,110,111, /* 6x */
11648 112, 81, 82, 83, 84, 85, 86, 87, 88, 89,122,123,124,125,126,127, /* 7x */
11649 128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143, /* 8x */
11650 144,145,146,147,148,149,150,151,152,153,154,155,156,157,156,159, /* 9x */
11651 160,161,162,163,164,165,166,167,168,169,170,171,140,141,142,175, /* Ax */
11652 176,177,178,179,180,181,182,183,184,185,186,187,188,189,190,191, /* Bx */
11653 192,129,130,131,132,133,134,135,136,137,202,203,204,205,206,207, /* Cx */
11654 208,145,146,147,148,149,150,151,152,153,218,219,220,221,222,223, /* Dx */
11655 224,225,162,163,164,165,166,167,168,169,232,203,204,205,206,207, /* Ex */
11656 239,240,241,242,243,244,245,246,247,248,249,219,220,221,222,255, /* Fx */
11657 #endif
11661 ** The following 256 byte lookup table is used to support SQLites built-in
11662 ** equivalents to the following standard library functions:
11664 ** isspace() 0x01
11665 ** isalpha() 0x02
11666 ** isdigit() 0x04
11667 ** isalnum() 0x06
11668 ** isxdigit() 0x08
11669 ** toupper() 0x20
11670 ** SQLite identifier character 0x40
11672 ** Bit 0x20 is set if the mapped character requires translation to upper
11673 ** case. i.e. if the character is a lower-case ASCII character.
11674 ** If x is a lower-case ASCII character, then its upper-case equivalent
11675 ** is (x - 0x20). Therefore toupper() can be implemented as:
11677 ** (x & ~(map[x]&0x20))
11679 ** Standard function tolower() is implemented using the sqlite3UpperToLower[]
11680 ** array. tolower() is used more often than toupper() by SQLite.
11682 ** Bit 0x40 is set if the character non-alphanumeric and can be used in an
11683 ** SQLite identifier. Identifiers are alphanumerics, "_", "$", and any
11684 ** non-ASCII UTF character. Hence the test for whether or not a character is
11685 ** part of an identifier is 0x46.
11687 ** SQLite's versions are identical to the standard versions assuming a
11688 ** locale of "C". They are implemented as macros in sqliteInt.h.
11690 #ifdef SQLITE_ASCII
11691 SQLITE_PRIVATE const unsigned char sqlite3CtypeMap[256] = {
11692 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 00..07 ........ */
11693 0x00, 0x01, 0x01, 0x01, 0x01, 0x01, 0x00, 0x00, /* 08..0f ........ */
11694 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 10..17 ........ */
11695 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 18..1f ........ */
11696 0x01, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00, /* 20..27 !"#$%&' */
11697 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 28..2f ()*+,-./ */
11698 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, /* 30..37 01234567 */
11699 0x0c, 0x0c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 38..3f 89:;<=>? */
11701 0x00, 0x0a, 0x0a, 0x0a, 0x0a, 0x0a, 0x0a, 0x02, /* 40..47 @ABCDEFG */
11702 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, /* 48..4f HIJKLMNO */
11703 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, /* 50..57 PQRSTUVW */
11704 0x02, 0x02, 0x02, 0x00, 0x00, 0x00, 0x00, 0x40, /* 58..5f XYZ[\]^_ */
11705 0x00, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x22, /* 60..67 `abcdefg */
11706 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, /* 68..6f hijklmno */
11707 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, /* 70..77 pqrstuvw */
11708 0x22, 0x22, 0x22, 0x00, 0x00, 0x00, 0x00, 0x00, /* 78..7f xyz{|}~. */
11710 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* 80..87 ........ */
11711 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* 88..8f ........ */
11712 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* 90..97 ........ */
11713 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* 98..9f ........ */
11714 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* a0..a7 ........ */
11715 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* a8..af ........ */
11716 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* b0..b7 ........ */
11717 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* b8..bf ........ */
11719 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* c0..c7 ........ */
11720 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* c8..cf ........ */
11721 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* d0..d7 ........ */
11722 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* d8..df ........ */
11723 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* e0..e7 ........ */
11724 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* e8..ef ........ */
11725 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* f0..f7 ........ */
11726 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40 /* f8..ff ........ */
11728 #endif
11733 ** The following singleton contains the global configuration for
11734 ** the SQLite library.
11736 SQLITE_PRIVATE SQLITE_WSD struct Sqlite3Config sqlite3Config = {
11737 SQLITE_DEFAULT_MEMSTATUS, /* bMemstat */
11738 1, /* bCoreMutex */
11739 SQLITE_THREADSAFE==1, /* bFullMutex */
11740 0x7ffffffe, /* mxStrlen */
11741 100, /* szLookaside */
11742 500, /* nLookaside */
11743 {0,0,0,0,0,0,0,0}, /* m */
11744 {0,0,0,0,0,0,0,0,0}, /* mutex */
11745 {0,0,0,0,0,0,0,0,0,0,0}, /* pcache */
11746 (void*)0, /* pHeap */
11747 0, /* nHeap */
11748 0, 0, /* mnHeap, mxHeap */
11749 (void*)0, /* pScratch */
11750 0, /* szScratch */
11751 0, /* nScratch */
11752 (void*)0, /* pPage */
11753 0, /* szPage */
11754 0, /* nPage */
11755 0, /* mxParserStack */
11756 0, /* sharedCacheEnabled */
11757 /* All the rest should always be initialized to zero */
11758 0, /* isInit */
11759 0, /* inProgress */
11760 0, /* isMutexInit */
11761 0, /* isMallocInit */
11762 0, /* isPCacheInit */
11763 0, /* pInitMutex */
11764 0, /* nRefInitMutex */
11765 0, /* xLog */
11766 0, /* pLogArg */
11771 ** Hash table for global functions - functions common to all
11772 ** database connections. After initialization, this table is
11773 ** read-only.
11775 SQLITE_PRIVATE SQLITE_WSD FuncDefHash sqlite3GlobalFunctions;
11778 ** Constant tokens for values 0 and 1.
11780 SQLITE_PRIVATE const Token sqlite3IntTokens[] = {
11781 { "0", 1 },
11782 { "1", 1 }
11787 ** The value of the "pending" byte must be 0x40000000 (1 byte past the
11788 ** 1-gibabyte boundary) in a compatible database. SQLite never uses
11789 ** the database page that contains the pending byte. It never attempts
11790 ** to read or write that page. The pending byte page is set assign
11791 ** for use by the VFS layers as space for managing file locks.
11793 ** During testing, it is often desirable to move the pending byte to
11794 ** a different position in the file. This allows code that has to
11795 ** deal with the pending byte to run on files that are much smaller
11796 ** than 1 GiB. The sqlite3_test_control() interface can be used to
11797 ** move the pending byte.
11799 ** IMPORTANT: Changing the pending byte to any value other than
11800 ** 0x40000000 results in an incompatible database file format!
11801 ** Changing the pending byte during operating results in undefined
11802 ** and dileterious behavior.
11804 #ifndef SQLITE_OMIT_WSD
11805 SQLITE_PRIVATE int sqlite3PendingByte = 0x40000000;
11806 #endif
11809 ** Properties of opcodes. The OPFLG_INITIALIZER macro is
11810 ** created by mkopcodeh.awk during compilation. Data is obtained
11811 ** from the comments following the "case OP_xxxx:" statements in
11812 ** the vdbe.c file.
11814 SQLITE_PRIVATE const unsigned char sqlite3OpcodeProperty[] = OPFLG_INITIALIZER;
11816 /************** End of global.c **********************************************/
11817 /************** Begin file ctime.c *******************************************/
11819 ** 2010 February 23
11821 ** The author disclaims copyright to this source code. In place of
11822 ** a legal notice, here is a blessing:
11824 ** May you do good and not evil.
11825 ** May you find forgiveness for yourself and forgive others.
11826 ** May you share freely, never taking more than you give.
11828 *************************************************************************
11830 ** This file implements routines used to report what compile-time options
11831 ** SQLite was built with.
11834 #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
11838 ** An array of names of all compile-time options. This array should
11839 ** be sorted A-Z.
11841 ** This array looks large, but in a typical installation actually uses
11842 ** only a handful of compile-time options, so most times this array is usually
11843 ** rather short and uses little memory space.
11845 static const char * const azCompileOpt[] = {
11847 /* These macros are provided to "stringify" the value of the define
11848 ** for those options in which the value is meaningful. */
11849 #define CTIMEOPT_VAL_(opt) #opt
11850 #define CTIMEOPT_VAL(opt) CTIMEOPT_VAL_(opt)
11852 #ifdef SQLITE_32BIT_ROWID
11853 "32BIT_ROWID",
11854 #endif
11855 #ifdef SQLITE_4_BYTE_ALIGNED_MALLOC
11856 "4_BYTE_ALIGNED_MALLOC",
11857 #endif
11858 #ifdef SQLITE_CASE_SENSITIVE_LIKE
11859 "CASE_SENSITIVE_LIKE",
11860 #endif
11861 #ifdef SQLITE_CHECK_PAGES
11862 "CHECK_PAGES",
11863 #endif
11864 #ifdef SQLITE_COVERAGE_TEST
11865 "COVERAGE_TEST",
11866 #endif
11867 #ifdef SQLITE_DEBUG
11868 "DEBUG",
11869 #endif
11870 #ifdef SQLITE_DEFAULT_LOCKING_MODE
11871 "DEFAULT_LOCKING_MODE=" CTIMEOPT_VAL(SQLITE_DEFAULT_LOCKING_MODE),
11872 #endif
11873 #ifdef SQLITE_DISABLE_DIRSYNC
11874 "DISABLE_DIRSYNC",
11875 #endif
11876 #ifdef SQLITE_DISABLE_LFS
11877 "DISABLE_LFS",
11878 #endif
11879 #ifdef SQLITE_ENABLE_ATOMIC_WRITE
11880 "ENABLE_ATOMIC_WRITE",
11881 #endif
11882 #ifdef SQLITE_ENABLE_CEROD
11883 "ENABLE_CEROD",
11884 #endif
11885 #ifdef SQLITE_ENABLE_COLUMN_METADATA
11886 "ENABLE_COLUMN_METADATA",
11887 #endif
11888 #ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
11889 "ENABLE_EXPENSIVE_ASSERT",
11890 #endif
11891 #ifdef SQLITE_ENABLE_FTS1
11892 "ENABLE_FTS1",
11893 #endif
11894 #ifdef SQLITE_ENABLE_FTS2
11895 "ENABLE_FTS2",
11896 #endif
11897 #ifdef SQLITE_ENABLE_FTS3
11898 "ENABLE_FTS3",
11899 #endif
11900 #ifdef SQLITE_ENABLE_FTS3_PARENTHESIS
11901 "ENABLE_FTS3_PARENTHESIS",
11902 #endif
11903 #ifdef SQLITE_ENABLE_FTS4
11904 "ENABLE_FTS4",
11905 #endif
11906 #ifdef SQLITE_ENABLE_ICU
11907 "ENABLE_ICU",
11908 #endif
11909 #ifdef SQLITE_ENABLE_IOTRACE
11910 "ENABLE_IOTRACE",
11911 #endif
11912 #ifdef SQLITE_ENABLE_LOAD_EXTENSION
11913 "ENABLE_LOAD_EXTENSION",
11914 #endif
11915 #ifdef SQLITE_ENABLE_LOCKING_STYLE
11916 "ENABLE_LOCKING_STYLE=" CTIMEOPT_VAL(SQLITE_ENABLE_LOCKING_STYLE),
11917 #endif
11918 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
11919 "ENABLE_MEMORY_MANAGEMENT",
11920 #endif
11921 #ifdef SQLITE_ENABLE_MEMSYS3
11922 "ENABLE_MEMSYS3",
11923 #endif
11924 #ifdef SQLITE_ENABLE_MEMSYS5
11925 "ENABLE_MEMSYS5",
11926 #endif
11927 #ifdef SQLITE_ENABLE_OVERSIZE_CELL_CHECK
11928 "ENABLE_OVERSIZE_CELL_CHECK",
11929 #endif
11930 #ifdef SQLITE_ENABLE_RTREE
11931 "ENABLE_RTREE",
11932 #endif
11933 #ifdef SQLITE_ENABLE_STAT2
11934 "ENABLE_STAT2",
11935 #endif
11936 #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
11937 "ENABLE_UNLOCK_NOTIFY",
11938 #endif
11939 #ifdef SQLITE_ENABLE_UPDATE_DELETE_LIMIT
11940 "ENABLE_UPDATE_DELETE_LIMIT",
11941 #endif
11942 #ifdef SQLITE_HAS_CODEC
11943 "HAS_CODEC",
11944 #endif
11945 #ifdef SQLITE_HAVE_ISNAN
11946 "HAVE_ISNAN",
11947 #endif
11948 #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
11949 "HOMEGROWN_RECURSIVE_MUTEX",
11950 #endif
11951 #ifdef SQLITE_IGNORE_AFP_LOCK_ERRORS
11952 "IGNORE_AFP_LOCK_ERRORS",
11953 #endif
11954 #ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
11955 "IGNORE_FLOCK_LOCK_ERRORS",
11956 #endif
11957 #ifdef SQLITE_INT64_TYPE
11958 "INT64_TYPE",
11959 #endif
11960 #ifdef SQLITE_LOCK_TRACE
11961 "LOCK_TRACE",
11962 #endif
11963 #ifdef SQLITE_MEMDEBUG
11964 "MEMDEBUG",
11965 #endif
11966 #ifdef SQLITE_MIXED_ENDIAN_64BIT_FLOAT
11967 "MIXED_ENDIAN_64BIT_FLOAT",
11968 #endif
11969 #ifdef SQLITE_NO_SYNC
11970 "NO_SYNC",
11971 #endif
11972 #ifdef SQLITE_OMIT_ALTERTABLE
11973 "OMIT_ALTERTABLE",
11974 #endif
11975 #ifdef SQLITE_OMIT_ANALYZE
11976 "OMIT_ANALYZE",
11977 #endif
11978 #ifdef SQLITE_OMIT_ATTACH
11979 "OMIT_ATTACH",
11980 #endif
11981 #ifdef SQLITE_OMIT_AUTHORIZATION
11982 "OMIT_AUTHORIZATION",
11983 #endif
11984 #ifdef SQLITE_OMIT_AUTOINCREMENT
11985 "OMIT_AUTOINCREMENT",
11986 #endif
11987 #ifdef SQLITE_OMIT_AUTOINIT
11988 "OMIT_AUTOINIT",
11989 #endif
11990 #ifdef SQLITE_OMIT_AUTOMATIC_INDEX
11991 "OMIT_AUTOMATIC_INDEX",
11992 #endif
11993 #ifdef SQLITE_OMIT_AUTORESET
11994 "OMIT_AUTORESET",
11995 #endif
11996 #ifdef SQLITE_OMIT_AUTOVACUUM
11997 "OMIT_AUTOVACUUM",
11998 #endif
11999 #ifdef SQLITE_OMIT_BETWEEN_OPTIMIZATION
12000 "OMIT_BETWEEN_OPTIMIZATION",
12001 #endif
12002 #ifdef SQLITE_OMIT_BLOB_LITERAL
12003 "OMIT_BLOB_LITERAL",
12004 #endif
12005 #ifdef SQLITE_OMIT_BTREECOUNT
12006 "OMIT_BTREECOUNT",
12007 #endif
12008 #ifdef SQLITE_OMIT_BUILTIN_TEST
12009 "OMIT_BUILTIN_TEST",
12010 #endif
12011 #ifdef SQLITE_OMIT_CAST
12012 "OMIT_CAST",
12013 #endif
12014 #ifdef SQLITE_OMIT_CHECK
12015 "OMIT_CHECK",
12016 #endif
12017 /* // redundant
12018 ** #ifdef SQLITE_OMIT_COMPILEOPTION_DIAGS
12019 ** "OMIT_COMPILEOPTION_DIAGS",
12020 ** #endif
12022 #ifdef SQLITE_OMIT_COMPLETE
12023 "OMIT_COMPLETE",
12024 #endif
12025 #ifdef SQLITE_OMIT_COMPOUND_SELECT
12026 "OMIT_COMPOUND_SELECT",
12027 #endif
12028 #ifdef SQLITE_OMIT_DATETIME_FUNCS
12029 "OMIT_DATETIME_FUNCS",
12030 #endif
12031 #ifdef SQLITE_OMIT_DECLTYPE
12032 "OMIT_DECLTYPE",
12033 #endif
12034 #ifdef SQLITE_OMIT_DEPRECATED
12035 "OMIT_DEPRECATED",
12036 #endif
12037 #ifdef SQLITE_OMIT_DISKIO
12038 "OMIT_DISKIO",
12039 #endif
12040 #ifdef SQLITE_OMIT_EXPLAIN
12041 "OMIT_EXPLAIN",
12042 #endif
12043 #ifdef SQLITE_OMIT_FLAG_PRAGMAS
12044 "OMIT_FLAG_PRAGMAS",
12045 #endif
12046 #ifdef SQLITE_OMIT_FLOATING_POINT
12047 "OMIT_FLOATING_POINT",
12048 #endif
12049 #ifdef SQLITE_OMIT_FOREIGN_KEY
12050 "OMIT_FOREIGN_KEY",
12051 #endif
12052 #ifdef SQLITE_OMIT_GET_TABLE
12053 "OMIT_GET_TABLE",
12054 #endif
12055 #ifdef SQLITE_OMIT_INCRBLOB
12056 "OMIT_INCRBLOB",
12057 #endif
12058 #ifdef SQLITE_OMIT_INTEGRITY_CHECK
12059 "OMIT_INTEGRITY_CHECK",
12060 #endif
12061 #ifdef SQLITE_OMIT_LIKE_OPTIMIZATION
12062 "OMIT_LIKE_OPTIMIZATION",
12063 #endif
12064 #ifdef SQLITE_OMIT_LOAD_EXTENSION
12065 "OMIT_LOAD_EXTENSION",
12066 #endif
12067 #ifdef SQLITE_OMIT_LOCALTIME
12068 "OMIT_LOCALTIME",
12069 #endif
12070 #ifdef SQLITE_OMIT_LOOKASIDE
12071 "OMIT_LOOKASIDE",
12072 #endif
12073 #ifdef SQLITE_OMIT_MEMORYDB
12074 "OMIT_MEMORYDB",
12075 #endif
12076 #ifdef SQLITE_OMIT_OR_OPTIMIZATION
12077 "OMIT_OR_OPTIMIZATION",
12078 #endif
12079 #ifdef SQLITE_OMIT_PAGER_PRAGMAS
12080 "OMIT_PAGER_PRAGMAS",
12081 #endif
12082 #ifdef SQLITE_OMIT_PRAGMA
12083 "OMIT_PRAGMA",
12084 #endif
12085 #ifdef SQLITE_OMIT_PROGRESS_CALLBACK
12086 "OMIT_PROGRESS_CALLBACK",
12087 #endif
12088 #ifdef SQLITE_OMIT_QUICKBALANCE
12089 "OMIT_QUICKBALANCE",
12090 #endif
12091 #ifdef SQLITE_OMIT_REINDEX
12092 "OMIT_REINDEX",
12093 #endif
12094 #ifdef SQLITE_OMIT_SCHEMA_PRAGMAS
12095 "OMIT_SCHEMA_PRAGMAS",
12096 #endif
12097 #ifdef SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS
12098 "OMIT_SCHEMA_VERSION_PRAGMAS",
12099 #endif
12100 #ifdef SQLITE_OMIT_SHARED_CACHE
12101 "OMIT_SHARED_CACHE",
12102 #endif
12103 #ifdef SQLITE_OMIT_SUBQUERY
12104 "OMIT_SUBQUERY",
12105 #endif
12106 #ifdef SQLITE_OMIT_TCL_VARIABLE
12107 "OMIT_TCL_VARIABLE",
12108 #endif
12109 #ifdef SQLITE_OMIT_TEMPDB
12110 "OMIT_TEMPDB",
12111 #endif
12112 #ifdef SQLITE_OMIT_TRACE
12113 "OMIT_TRACE",
12114 #endif
12115 #ifdef SQLITE_OMIT_TRIGGER
12116 "OMIT_TRIGGER",
12117 #endif
12118 #ifdef SQLITE_OMIT_TRUNCATE_OPTIMIZATION
12119 "OMIT_TRUNCATE_OPTIMIZATION",
12120 #endif
12121 #ifdef SQLITE_OMIT_UTF16
12122 "OMIT_UTF16",
12123 #endif
12124 #ifdef SQLITE_OMIT_VACUUM
12125 "OMIT_VACUUM",
12126 #endif
12127 #ifdef SQLITE_OMIT_VIEW
12128 "OMIT_VIEW",
12129 #endif
12130 #ifdef SQLITE_OMIT_VIRTUALTABLE
12131 "OMIT_VIRTUALTABLE",
12132 #endif
12133 #ifdef SQLITE_OMIT_WAL
12134 "OMIT_WAL",
12135 #endif
12136 #ifdef SQLITE_OMIT_WSD
12137 "OMIT_WSD",
12138 #endif
12139 #ifdef SQLITE_OMIT_XFER_OPT
12140 "OMIT_XFER_OPT",
12141 #endif
12142 #ifdef SQLITE_PERFORMANCE_TRACE
12143 "PERFORMANCE_TRACE",
12144 #endif
12145 #ifdef SQLITE_PROXY_DEBUG
12146 "PROXY_DEBUG",
12147 #endif
12148 #ifdef SQLITE_SECURE_DELETE
12149 "SECURE_DELETE",
12150 #endif
12151 #ifdef SQLITE_SMALL_STACK
12152 "SMALL_STACK",
12153 #endif
12154 #ifdef SQLITE_SOUNDEX
12155 "SOUNDEX",
12156 #endif
12157 #ifdef SQLITE_TCL
12158 "TCL",
12159 #endif
12160 #ifdef SQLITE_TEMP_STORE
12161 "TEMP_STORE=" CTIMEOPT_VAL(SQLITE_TEMP_STORE),
12162 #endif
12163 #ifdef SQLITE_TEST
12164 "TEST",
12165 #endif
12166 #ifdef SQLITE_THREADSAFE
12167 "THREADSAFE=" CTIMEOPT_VAL(SQLITE_THREADSAFE),
12168 #endif
12169 #ifdef SQLITE_USE_ALLOCA
12170 "USE_ALLOCA",
12171 #endif
12172 #ifdef SQLITE_ZERO_MALLOC
12173 "ZERO_MALLOC"
12174 #endif
12178 ** Given the name of a compile-time option, return true if that option
12179 ** was used and false if not.
12181 ** The name can optionally begin with "SQLITE_" but the "SQLITE_" prefix
12182 ** is not required for a match.
12184 SQLITE_API int sqlite3_compileoption_used(const char *zOptName){
12185 int i, n;
12186 if( sqlite3StrNICmp(zOptName, "SQLITE_", 7)==0 ) zOptName += 7;
12187 n = sqlite3Strlen30(zOptName);
12189 /* Since ArraySize(azCompileOpt) is normally in single digits, a
12190 ** linear search is adequate. No need for a binary search. */
12191 for(i=0; i<ArraySize(azCompileOpt); i++){
12192 if( (sqlite3StrNICmp(zOptName, azCompileOpt[i], n)==0)
12193 && ( (azCompileOpt[i][n]==0) || (azCompileOpt[i][n]=='=') ) ) return 1;
12195 return 0;
12199 ** Return the N-th compile-time option string. If N is out of range,
12200 ** return a NULL pointer.
12202 SQLITE_API const char *sqlite3_compileoption_get(int N){
12203 if( N>=0 && N<ArraySize(azCompileOpt) ){
12204 return azCompileOpt[N];
12206 return 0;
12209 #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
12211 /************** End of ctime.c ***********************************************/
12212 /************** Begin file status.c ******************************************/
12214 ** 2008 June 18
12216 ** The author disclaims copyright to this source code. In place of
12217 ** a legal notice, here is a blessing:
12219 ** May you do good and not evil.
12220 ** May you find forgiveness for yourself and forgive others.
12221 ** May you share freely, never taking more than you give.
12223 *************************************************************************
12225 ** This module implements the sqlite3_status() interface and related
12226 ** functionality.
12228 /************** Include vdbeInt.h in the middle of status.c ******************/
12229 /************** Begin file vdbeInt.h *****************************************/
12231 ** 2003 September 6
12233 ** The author disclaims copyright to this source code. In place of
12234 ** a legal notice, here is a blessing:
12236 ** May you do good and not evil.
12237 ** May you find forgiveness for yourself and forgive others.
12238 ** May you share freely, never taking more than you give.
12240 *************************************************************************
12241 ** This is the header file for information that is private to the
12242 ** VDBE. This information used to all be at the top of the single
12243 ** source code file "vdbe.c". When that file became too big (over
12244 ** 6000 lines long) it was split up into several smaller files and
12245 ** this header information was factored out.
12247 #ifndef _VDBEINT_H_
12248 #define _VDBEINT_H_
12251 ** SQL is translated into a sequence of instructions to be
12252 ** executed by a virtual machine. Each instruction is an instance
12253 ** of the following structure.
12255 typedef struct VdbeOp Op;
12258 ** Boolean values
12260 typedef unsigned char Bool;
12263 ** A cursor is a pointer into a single BTree within a database file.
12264 ** The cursor can seek to a BTree entry with a particular key, or
12265 ** loop over all entries of the Btree. You can also insert new BTree
12266 ** entries or retrieve the key or data from the entry that the cursor
12267 ** is currently pointing to.
12269 ** Every cursor that the virtual machine has open is represented by an
12270 ** instance of the following structure.
12272 struct VdbeCursor {
12273 BtCursor *pCursor; /* The cursor structure of the backend */
12274 Btree *pBt; /* Separate file holding temporary table */
12275 KeyInfo *pKeyInfo; /* Info about index keys needed by index cursors */
12276 int iDb; /* Index of cursor database in db->aDb[] (or -1) */
12277 int pseudoTableReg; /* Register holding pseudotable content. */
12278 int nField; /* Number of fields in the header */
12279 Bool zeroed; /* True if zeroed out and ready for reuse */
12280 Bool rowidIsValid; /* True if lastRowid is valid */
12281 Bool atFirst; /* True if pointing to first entry */
12282 Bool useRandomRowid; /* Generate new record numbers semi-randomly */
12283 Bool nullRow; /* True if pointing to a row with no data */
12284 Bool deferredMoveto; /* A call to sqlite3BtreeMoveto() is needed */
12285 Bool isTable; /* True if a table requiring integer keys */
12286 Bool isIndex; /* True if an index containing keys only - no data */
12287 Bool isOrdered; /* True if the underlying table is BTREE_UNORDERED */
12288 sqlite3_vtab_cursor *pVtabCursor; /* The cursor for a virtual table */
12289 const sqlite3_module *pModule; /* Module for cursor pVtabCursor */
12290 i64 seqCount; /* Sequence counter */
12291 i64 movetoTarget; /* Argument to the deferred sqlite3BtreeMoveto() */
12292 i64 lastRowid; /* Last rowid from a Next or NextIdx operation */
12294 /* Result of last sqlite3BtreeMoveto() done by an OP_NotExists or
12295 ** OP_IsUnique opcode on this cursor. */
12296 int seekResult;
12298 /* Cached information about the header for the data record that the
12299 ** cursor is currently pointing to. Only valid if cacheStatus matches
12300 ** Vdbe.cacheCtr. Vdbe.cacheCtr will never take on the value of
12301 ** CACHE_STALE and so setting cacheStatus=CACHE_STALE guarantees that
12302 ** the cache is out of date.
12304 ** aRow might point to (ephemeral) data for the current row, or it might
12305 ** be NULL.
12307 u32 cacheStatus; /* Cache is valid if this matches Vdbe.cacheCtr */
12308 int payloadSize; /* Total number of bytes in the record */
12309 u32 *aType; /* Type values for all entries in the record */
12310 u32 *aOffset; /* Cached offsets to the start of each columns data */
12311 u8 *aRow; /* Data for the current row, if all on one page */
12313 typedef struct VdbeCursor VdbeCursor;
12316 ** When a sub-program is executed (OP_Program), a structure of this type
12317 ** is allocated to store the current value of the program counter, as
12318 ** well as the current memory cell array and various other frame specific
12319 ** values stored in the Vdbe struct. When the sub-program is finished,
12320 ** these values are copied back to the Vdbe from the VdbeFrame structure,
12321 ** restoring the state of the VM to as it was before the sub-program
12322 ** began executing.
12324 ** The memory for a VdbeFrame object is allocated and managed by a memory
12325 ** cell in the parent (calling) frame. When the memory cell is deleted or
12326 ** overwritten, the VdbeFrame object is not freed immediately. Instead, it
12327 ** is linked into the Vdbe.pDelFrame list. The contents of the Vdbe.pDelFrame
12328 ** list is deleted when the VM is reset in VdbeHalt(). The reason for doing
12329 ** this instead of deleting the VdbeFrame immediately is to avoid recursive
12330 ** calls to sqlite3VdbeMemRelease() when the memory cells belonging to the
12331 ** child frame are released.
12333 ** The currently executing frame is stored in Vdbe.pFrame. Vdbe.pFrame is
12334 ** set to NULL if the currently executing frame is the main program.
12336 typedef struct VdbeFrame VdbeFrame;
12337 struct VdbeFrame {
12338 Vdbe *v; /* VM this frame belongs to */
12339 int pc; /* Program Counter in parent (calling) frame */
12340 Op *aOp; /* Program instructions for parent frame */
12341 int nOp; /* Size of aOp array */
12342 Mem *aMem; /* Array of memory cells for parent frame */
12343 int nMem; /* Number of entries in aMem */
12344 VdbeCursor **apCsr; /* Array of Vdbe cursors for parent frame */
12345 u16 nCursor; /* Number of entries in apCsr */
12346 void *token; /* Copy of SubProgram.token */
12347 int nChildMem; /* Number of memory cells for child frame */
12348 int nChildCsr; /* Number of cursors for child frame */
12349 i64 lastRowid; /* Last insert rowid (sqlite3.lastRowid) */
12350 int nChange; /* Statement changes (Vdbe.nChanges) */
12351 VdbeFrame *pParent; /* Parent of this frame, or NULL if parent is main */
12354 #define VdbeFrameMem(p) ((Mem *)&((u8 *)p)[ROUND8(sizeof(VdbeFrame))])
12357 ** A value for VdbeCursor.cacheValid that means the cache is always invalid.
12359 #define CACHE_STALE 0
12362 ** Internally, the vdbe manipulates nearly all SQL values as Mem
12363 ** structures. Each Mem struct may cache multiple representations (string,
12364 ** integer etc.) of the same value.
12366 struct Mem {
12367 sqlite3 *db; /* The associated database connection */
12368 char *z; /* String or BLOB value */
12369 double r; /* Real value */
12370 union {
12371 i64 i; /* Integer value used when MEM_Int is set in flags */
12372 int nZero; /* Used when bit MEM_Zero is set in flags */
12373 FuncDef *pDef; /* Used only when flags==MEM_Agg */
12374 RowSet *pRowSet; /* Used only when flags==MEM_RowSet */
12375 VdbeFrame *pFrame; /* Used when flags==MEM_Frame */
12376 } u;
12377 int n; /* Number of characters in string value, excluding '\0' */
12378 u16 flags; /* Some combination of MEM_Null, MEM_Str, MEM_Dyn, etc. */
12379 u8 type; /* One of SQLITE_NULL, SQLITE_TEXT, SQLITE_INTEGER, etc */
12380 u8 enc; /* SQLITE_UTF8, SQLITE_UTF16BE, SQLITE_UTF16LE */
12381 #ifdef SQLITE_DEBUG
12382 Mem *pScopyFrom; /* This Mem is a shallow copy of pScopyFrom */
12383 void *pFiller; /* So that sizeof(Mem) is a multiple of 8 */
12384 #endif
12385 void (*xDel)(void *); /* If not null, call this function to delete Mem.z */
12386 char *zMalloc; /* Dynamic buffer allocated by sqlite3_malloc() */
12389 /* One or more of the following flags are set to indicate the validOK
12390 ** representations of the value stored in the Mem struct.
12392 ** If the MEM_Null flag is set, then the value is an SQL NULL value.
12393 ** No other flags may be set in this case.
12395 ** If the MEM_Str flag is set then Mem.z points at a string representation.
12396 ** Usually this is encoded in the same unicode encoding as the main
12397 ** database (see below for exceptions). If the MEM_Term flag is also
12398 ** set, then the string is nul terminated. The MEM_Int and MEM_Real
12399 ** flags may coexist with the MEM_Str flag.
12401 #define MEM_Null 0x0001 /* Value is NULL */
12402 #define MEM_Str 0x0002 /* Value is a string */
12403 #define MEM_Int 0x0004 /* Value is an integer */
12404 #define MEM_Real 0x0008 /* Value is a real number */
12405 #define MEM_Blob 0x0010 /* Value is a BLOB */
12406 #define MEM_RowSet 0x0020 /* Value is a RowSet object */
12407 #define MEM_Frame 0x0040 /* Value is a VdbeFrame object */
12408 #define MEM_Invalid 0x0080 /* Value is undefined */
12409 #define MEM_TypeMask 0x00ff /* Mask of type bits */
12411 /* Whenever Mem contains a valid string or blob representation, one of
12412 ** the following flags must be set to determine the memory management
12413 ** policy for Mem.z. The MEM_Term flag tells us whether or not the
12414 ** string is \000 or \u0000 terminated
12416 #define MEM_Term 0x0200 /* String rep is nul terminated */
12417 #define MEM_Dyn 0x0400 /* Need to call sqliteFree() on Mem.z */
12418 #define MEM_Static 0x0800 /* Mem.z points to a static string */
12419 #define MEM_Ephem 0x1000 /* Mem.z points to an ephemeral string */
12420 #define MEM_Agg 0x2000 /* Mem.z points to an agg function context */
12421 #define MEM_Zero 0x4000 /* Mem.i contains count of 0s appended to blob */
12422 #ifdef SQLITE_OMIT_INCRBLOB
12423 #undef MEM_Zero
12424 #define MEM_Zero 0x0000
12425 #endif
12428 ** Clear any existing type flags from a Mem and replace them with f
12430 #define MemSetTypeFlag(p, f) \
12431 ((p)->flags = ((p)->flags&~(MEM_TypeMask|MEM_Zero))|f)
12434 ** Return true if a memory cell is not marked as invalid. This macro
12435 ** is for use inside assert() statements only.
12437 #ifdef SQLITE_DEBUG
12438 #define memIsValid(M) ((M)->flags & MEM_Invalid)==0
12439 #endif
12442 /* A VdbeFunc is just a FuncDef (defined in sqliteInt.h) that contains
12443 ** additional information about auxiliary information bound to arguments
12444 ** of the function. This is used to implement the sqlite3_get_auxdata()
12445 ** and sqlite3_set_auxdata() APIs. The "auxdata" is some auxiliary data
12446 ** that can be associated with a constant argument to a function. This
12447 ** allows functions such as "regexp" to compile their constant regular
12448 ** expression argument once and reused the compiled code for multiple
12449 ** invocations.
12451 struct VdbeFunc {
12452 FuncDef *pFunc; /* The definition of the function */
12453 int nAux; /* Number of entries allocated for apAux[] */
12454 struct AuxData {
12455 void *pAux; /* Aux data for the i-th argument */
12456 void (*xDelete)(void *); /* Destructor for the aux data */
12457 } apAux[1]; /* One slot for each function argument */
12461 ** The "context" argument for a installable function. A pointer to an
12462 ** instance of this structure is the first argument to the routines used
12463 ** implement the SQL functions.
12465 ** There is a typedef for this structure in sqlite.h. So all routines,
12466 ** even the public interface to SQLite, can use a pointer to this structure.
12467 ** But this file is the only place where the internal details of this
12468 ** structure are known.
12470 ** This structure is defined inside of vdbeInt.h because it uses substructures
12471 ** (Mem) which are only defined there.
12473 struct sqlite3_context {
12474 FuncDef *pFunc; /* Pointer to function information. MUST BE FIRST */
12475 VdbeFunc *pVdbeFunc; /* Auxilary data, if created. */
12476 Mem s; /* The return value is stored here */
12477 Mem *pMem; /* Memory cell used to store aggregate context */
12478 int isError; /* Error code returned by the function. */
12479 CollSeq *pColl; /* Collating sequence */
12483 ** An instance of the virtual machine. This structure contains the complete
12484 ** state of the virtual machine.
12486 ** The "sqlite3_stmt" structure pointer that is returned by sqlite3_prepare()
12487 ** is really a pointer to an instance of this structure.
12489 ** The Vdbe.inVtabMethod variable is set to non-zero for the duration of
12490 ** any virtual table method invocations made by the vdbe program. It is
12491 ** set to 2 for xDestroy method calls and 1 for all other methods. This
12492 ** variable is used for two purposes: to allow xDestroy methods to execute
12493 ** "DROP TABLE" statements and to prevent some nasty side effects of
12494 ** malloc failure when SQLite is invoked recursively by a virtual table
12495 ** method function.
12497 struct Vdbe {
12498 sqlite3 *db; /* The database connection that owns this statement */
12499 Op *aOp; /* Space to hold the virtual machine's program */
12500 Mem *aMem; /* The memory locations */
12501 Mem **apArg; /* Arguments to currently executing user function */
12502 Mem *aColName; /* Column names to return */
12503 Mem *pResultSet; /* Pointer to an array of results */
12504 int nMem; /* Number of memory locations currently allocated */
12505 int nOp; /* Number of instructions in the program */
12506 int nOpAlloc; /* Number of slots allocated for aOp[] */
12507 int nLabel; /* Number of labels used */
12508 int nLabelAlloc; /* Number of slots allocated in aLabel[] */
12509 int *aLabel; /* Space to hold the labels */
12510 u16 nResColumn; /* Number of columns in one row of the result set */
12511 u16 nCursor; /* Number of slots in apCsr[] */
12512 u32 magic; /* Magic number for sanity checking */
12513 char *zErrMsg; /* Error message written here */
12514 Vdbe *pPrev,*pNext; /* Linked list of VDBEs with the same Vdbe.db */
12515 VdbeCursor **apCsr; /* One element of this array for each open cursor */
12516 Mem *aVar; /* Values for the OP_Variable opcode. */
12517 char **azVar; /* Name of variables */
12518 ynVar nVar; /* Number of entries in aVar[] */
12519 u32 cacheCtr; /* VdbeCursor row cache generation counter */
12520 int pc; /* The program counter */
12521 int rc; /* Value to return */
12522 u8 errorAction; /* Recovery action to do in case of an error */
12523 u8 okVar; /* True if azVar[] has been initialized */
12524 u8 explain; /* True if EXPLAIN present on SQL command */
12525 u8 changeCntOn; /* True to update the change-counter */
12526 u8 expired; /* True if the VM needs to be recompiled */
12527 u8 runOnlyOnce; /* Automatically expire on reset */
12528 u8 minWriteFileFormat; /* Minimum file format for writable database files */
12529 u8 inVtabMethod; /* See comments above */
12530 u8 usesStmtJournal; /* True if uses a statement journal */
12531 u8 readOnly; /* True for read-only statements */
12532 u8 isPrepareV2; /* True if prepared with prepare_v2() */
12533 int nChange; /* Number of db changes made since last reset */
12534 yDbMask btreeMask; /* Bitmask of db->aDb[] entries referenced */
12535 yDbMask lockMask; /* Subset of btreeMask that requires a lock */
12536 int iStatement; /* Statement number (or 0 if has not opened stmt) */
12537 int aCounter[3]; /* Counters used by sqlite3_stmt_status() */
12538 #ifndef SQLITE_OMIT_TRACE
12539 i64 startTime; /* Time when query started - used for profiling */
12540 #endif
12541 i64 nFkConstraint; /* Number of imm. FK constraints this VM */
12542 i64 nStmtDefCons; /* Number of def. constraints when stmt started */
12543 char *zSql; /* Text of the SQL statement that generated this */
12544 void *pFree; /* Free this when deleting the vdbe */
12545 #ifdef SQLITE_DEBUG
12546 FILE *trace; /* Write an execution trace here, if not NULL */
12547 #endif
12548 VdbeFrame *pFrame; /* Parent frame */
12549 VdbeFrame *pDelFrame; /* List of frame objects to free on VM reset */
12550 int nFrame; /* Number of frames in pFrame list */
12551 u32 expmask; /* Binding to these vars invalidates VM */
12552 SubProgram *pProgram; /* Linked list of all sub-programs used by VM */
12556 ** The following are allowed values for Vdbe.magic
12558 #define VDBE_MAGIC_INIT 0x26bceaa5 /* Building a VDBE program */
12559 #define VDBE_MAGIC_RUN 0xbdf20da3 /* VDBE is ready to execute */
12560 #define VDBE_MAGIC_HALT 0x519c2973 /* VDBE has completed execution */
12561 #define VDBE_MAGIC_DEAD 0xb606c3c8 /* The VDBE has been deallocated */
12564 ** Function prototypes
12566 SQLITE_PRIVATE void sqlite3VdbeFreeCursor(Vdbe *, VdbeCursor*);
12567 void sqliteVdbePopStack(Vdbe*,int);
12568 SQLITE_PRIVATE int sqlite3VdbeCursorMoveto(VdbeCursor*);
12569 #if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE)
12570 SQLITE_PRIVATE void sqlite3VdbePrintOp(FILE*, int, Op*);
12571 #endif
12572 SQLITE_PRIVATE u32 sqlite3VdbeSerialTypeLen(u32);
12573 SQLITE_PRIVATE u32 sqlite3VdbeSerialType(Mem*, int);
12574 SQLITE_PRIVATE u32 sqlite3VdbeSerialPut(unsigned char*, int, Mem*, int);
12575 SQLITE_PRIVATE u32 sqlite3VdbeSerialGet(const unsigned char*, u32, Mem*);
12576 SQLITE_PRIVATE void sqlite3VdbeDeleteAuxData(VdbeFunc*, int);
12578 int sqlite2BtreeKeyCompare(BtCursor *, const void *, int, int, int *);
12579 SQLITE_PRIVATE int sqlite3VdbeIdxKeyCompare(VdbeCursor*,UnpackedRecord*,int*);
12580 SQLITE_PRIVATE int sqlite3VdbeIdxRowid(sqlite3*, BtCursor *, i64 *);
12581 SQLITE_PRIVATE int sqlite3MemCompare(const Mem*, const Mem*, const CollSeq*);
12582 SQLITE_PRIVATE int sqlite3VdbeExec(Vdbe*);
12583 SQLITE_PRIVATE int sqlite3VdbeList(Vdbe*);
12584 SQLITE_PRIVATE int sqlite3VdbeHalt(Vdbe*);
12585 SQLITE_PRIVATE int sqlite3VdbeChangeEncoding(Mem *, int);
12586 SQLITE_PRIVATE int sqlite3VdbeMemTooBig(Mem*);
12587 SQLITE_PRIVATE int sqlite3VdbeMemCopy(Mem*, const Mem*);
12588 SQLITE_PRIVATE void sqlite3VdbeMemShallowCopy(Mem*, const Mem*, int);
12589 SQLITE_PRIVATE void sqlite3VdbeMemMove(Mem*, Mem*);
12590 SQLITE_PRIVATE int sqlite3VdbeMemNulTerminate(Mem*);
12591 SQLITE_PRIVATE int sqlite3VdbeMemSetStr(Mem*, const char*, int, u8, void(*)(void*));
12592 SQLITE_PRIVATE void sqlite3VdbeMemSetInt64(Mem*, i64);
12593 #ifdef SQLITE_OMIT_FLOATING_POINT
12594 # define sqlite3VdbeMemSetDouble sqlite3VdbeMemSetInt64
12595 #else
12596 SQLITE_PRIVATE void sqlite3VdbeMemSetDouble(Mem*, double);
12597 #endif
12598 SQLITE_PRIVATE void sqlite3VdbeMemSetNull(Mem*);
12599 SQLITE_PRIVATE void sqlite3VdbeMemSetZeroBlob(Mem*,int);
12600 SQLITE_PRIVATE void sqlite3VdbeMemSetRowSet(Mem*);
12601 SQLITE_PRIVATE int sqlite3VdbeMemMakeWriteable(Mem*);
12602 SQLITE_PRIVATE int sqlite3VdbeMemStringify(Mem*, int);
12603 SQLITE_PRIVATE i64 sqlite3VdbeIntValue(Mem*);
12604 SQLITE_PRIVATE int sqlite3VdbeMemIntegerify(Mem*);
12605 SQLITE_PRIVATE double sqlite3VdbeRealValue(Mem*);
12606 SQLITE_PRIVATE void sqlite3VdbeIntegerAffinity(Mem*);
12607 SQLITE_PRIVATE int sqlite3VdbeMemRealify(Mem*);
12608 SQLITE_PRIVATE int sqlite3VdbeMemNumerify(Mem*);
12609 SQLITE_PRIVATE int sqlite3VdbeMemFromBtree(BtCursor*,int,int,int,Mem*);
12610 SQLITE_PRIVATE void sqlite3VdbeMemRelease(Mem *p);
12611 SQLITE_PRIVATE void sqlite3VdbeMemReleaseExternal(Mem *p);
12612 SQLITE_PRIVATE int sqlite3VdbeMemFinalize(Mem*, FuncDef*);
12613 SQLITE_PRIVATE const char *sqlite3OpcodeName(int);
12614 SQLITE_PRIVATE int sqlite3VdbeMemGrow(Mem *pMem, int n, int preserve);
12615 SQLITE_PRIVATE int sqlite3VdbeCloseStatement(Vdbe *, int);
12616 SQLITE_PRIVATE void sqlite3VdbeFrameDelete(VdbeFrame*);
12617 SQLITE_PRIVATE int sqlite3VdbeFrameRestore(VdbeFrame *);
12618 SQLITE_PRIVATE void sqlite3VdbeMemStoreType(Mem *pMem);
12620 #if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE>0
12621 SQLITE_PRIVATE void sqlite3VdbeEnter(Vdbe*);
12622 SQLITE_PRIVATE void sqlite3VdbeLeave(Vdbe*);
12623 #else
12624 # define sqlite3VdbeEnter(X)
12625 # define sqlite3VdbeLeave(X)
12626 #endif
12628 #ifdef SQLITE_DEBUG
12629 SQLITE_PRIVATE void sqlite3VdbeMemPrepareToChange(Vdbe*,Mem*);
12630 #endif
12632 #ifndef SQLITE_OMIT_FOREIGN_KEY
12633 SQLITE_PRIVATE int sqlite3VdbeCheckFk(Vdbe *, int);
12634 #else
12635 # define sqlite3VdbeCheckFk(p,i) 0
12636 #endif
12638 SQLITE_PRIVATE int sqlite3VdbeMemTranslate(Mem*, u8);
12639 #ifdef SQLITE_DEBUG
12640 SQLITE_PRIVATE void sqlite3VdbePrintSql(Vdbe*);
12641 SQLITE_PRIVATE void sqlite3VdbeMemPrettyPrint(Mem *pMem, char *zBuf);
12642 #endif
12643 SQLITE_PRIVATE int sqlite3VdbeMemHandleBom(Mem *pMem);
12645 #ifndef SQLITE_OMIT_INCRBLOB
12646 SQLITE_PRIVATE int sqlite3VdbeMemExpandBlob(Mem *);
12647 #else
12648 #define sqlite3VdbeMemExpandBlob(x) SQLITE_OK
12649 #endif
12651 #endif /* !defined(_VDBEINT_H_) */
12653 /************** End of vdbeInt.h *********************************************/
12654 /************** Continuing where we left off in status.c *********************/
12657 ** Variables in which to record status information.
12659 typedef struct sqlite3StatType sqlite3StatType;
12660 static SQLITE_WSD struct sqlite3StatType {
12661 int nowValue[10]; /* Current value */
12662 int mxValue[10]; /* Maximum value */
12663 } sqlite3Stat = { {0,}, {0,} };
12666 /* The "wsdStat" macro will resolve to the status information
12667 ** state vector. If writable static data is unsupported on the target,
12668 ** we have to locate the state vector at run-time. In the more common
12669 ** case where writable static data is supported, wsdStat can refer directly
12670 ** to the "sqlite3Stat" state vector declared above.
12672 #ifdef SQLITE_OMIT_WSD
12673 # define wsdStatInit sqlite3StatType *x = &GLOBAL(sqlite3StatType,sqlite3Stat)
12674 # define wsdStat x[0]
12675 #else
12676 # define wsdStatInit
12677 # define wsdStat sqlite3Stat
12678 #endif
12681 ** Return the current value of a status parameter.
12683 SQLITE_PRIVATE int sqlite3StatusValue(int op){
12684 wsdStatInit;
12685 assert( op>=0 && op<ArraySize(wsdStat.nowValue) );
12686 return wsdStat.nowValue[op];
12690 ** Add N to the value of a status record. It is assumed that the
12691 ** caller holds appropriate locks.
12693 SQLITE_PRIVATE void sqlite3StatusAdd(int op, int N){
12694 wsdStatInit;
12695 assert( op>=0 && op<ArraySize(wsdStat.nowValue) );
12696 wsdStat.nowValue[op] += N;
12697 if( wsdStat.nowValue[op]>wsdStat.mxValue[op] ){
12698 wsdStat.mxValue[op] = wsdStat.nowValue[op];
12703 ** Set the value of a status to X.
12705 SQLITE_PRIVATE void sqlite3StatusSet(int op, int X){
12706 wsdStatInit;
12707 assert( op>=0 && op<ArraySize(wsdStat.nowValue) );
12708 wsdStat.nowValue[op] = X;
12709 if( wsdStat.nowValue[op]>wsdStat.mxValue[op] ){
12710 wsdStat.mxValue[op] = wsdStat.nowValue[op];
12715 ** Query status information.
12717 ** This implementation assumes that reading or writing an aligned
12718 ** 32-bit integer is an atomic operation. If that assumption is not true,
12719 ** then this routine is not threadsafe.
12721 SQLITE_API int sqlite3_status(int op, int *pCurrent, int *pHighwater, int resetFlag){
12722 wsdStatInit;
12723 if( op<0 || op>=ArraySize(wsdStat.nowValue) ){
12724 return SQLITE_MISUSE_BKPT;
12726 *pCurrent = wsdStat.nowValue[op];
12727 *pHighwater = wsdStat.mxValue[op];
12728 if( resetFlag ){
12729 wsdStat.mxValue[op] = wsdStat.nowValue[op];
12731 return SQLITE_OK;
12735 ** Query status information for a single database connection
12737 SQLITE_API int sqlite3_db_status(
12738 sqlite3 *db, /* The database connection whose status is desired */
12739 int op, /* Status verb */
12740 int *pCurrent, /* Write current value here */
12741 int *pHighwater, /* Write high-water mark here */
12742 int resetFlag /* Reset high-water mark if true */
12744 int rc = SQLITE_OK; /* Return code */
12745 sqlite3_mutex_enter(db->mutex);
12746 switch( op ){
12747 case SQLITE_DBSTATUS_LOOKASIDE_USED: {
12748 *pCurrent = db->lookaside.nOut;
12749 *pHighwater = db->lookaside.mxOut;
12750 if( resetFlag ){
12751 db->lookaside.mxOut = db->lookaside.nOut;
12753 break;
12756 case SQLITE_DBSTATUS_LOOKASIDE_HIT:
12757 case SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE:
12758 case SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL: {
12759 testcase( op==SQLITE_DBSTATUS_LOOKASIDE_HIT );
12760 testcase( op==SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE );
12761 testcase( op==SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL );
12762 assert( (op-SQLITE_DBSTATUS_LOOKASIDE_HIT)>=0 );
12763 assert( (op-SQLITE_DBSTATUS_LOOKASIDE_HIT)<3 );
12764 *pCurrent = 0;
12765 *pHighwater = db->lookaside.anStat[op - SQLITE_DBSTATUS_LOOKASIDE_HIT];
12766 if( resetFlag ){
12767 db->lookaside.anStat[op - SQLITE_DBSTATUS_LOOKASIDE_HIT] = 0;
12769 break;
12773 ** Return an approximation for the amount of memory currently used
12774 ** by all pagers associated with the given database connection. The
12775 ** highwater mark is meaningless and is returned as zero.
12777 case SQLITE_DBSTATUS_CACHE_USED: {
12778 int totalUsed = 0;
12779 int i;
12780 sqlite3BtreeEnterAll(db);
12781 for(i=0; i<db->nDb; i++){
12782 Btree *pBt = db->aDb[i].pBt;
12783 if( pBt ){
12784 Pager *pPager = sqlite3BtreePager(pBt);
12785 totalUsed += sqlite3PagerMemUsed(pPager);
12788 sqlite3BtreeLeaveAll(db);
12789 *pCurrent = totalUsed;
12790 *pHighwater = 0;
12791 break;
12795 ** *pCurrent gets an accurate estimate of the amount of memory used
12796 ** to store the schema for all databases (main, temp, and any ATTACHed
12797 ** databases. *pHighwater is set to zero.
12799 case SQLITE_DBSTATUS_SCHEMA_USED: {
12800 int i; /* Used to iterate through schemas */
12801 int nByte = 0; /* Used to accumulate return value */
12803 sqlite3BtreeEnterAll(db);
12804 db->pnBytesFreed = &nByte;
12805 for(i=0; i<db->nDb; i++){
12806 Schema *pSchema = db->aDb[i].pSchema;
12807 if( ALWAYS(pSchema!=0) ){
12808 HashElem *p;
12810 nByte += sqlite3GlobalConfig.m.xRoundup(sizeof(HashElem)) * (
12811 pSchema->tblHash.count
12812 + pSchema->trigHash.count
12813 + pSchema->idxHash.count
12814 + pSchema->fkeyHash.count
12816 nByte += sqlite3MallocSize(pSchema->tblHash.ht);
12817 nByte += sqlite3MallocSize(pSchema->trigHash.ht);
12818 nByte += sqlite3MallocSize(pSchema->idxHash.ht);
12819 nByte += sqlite3MallocSize(pSchema->fkeyHash.ht);
12821 for(p=sqliteHashFirst(&pSchema->trigHash); p; p=sqliteHashNext(p)){
12822 sqlite3DeleteTrigger(db, (Trigger*)sqliteHashData(p));
12824 for(p=sqliteHashFirst(&pSchema->tblHash); p; p=sqliteHashNext(p)){
12825 sqlite3DeleteTable(db, (Table *)sqliteHashData(p));
12829 db->pnBytesFreed = 0;
12830 sqlite3BtreeLeaveAll(db);
12832 *pHighwater = 0;
12833 *pCurrent = nByte;
12834 break;
12838 ** *pCurrent gets an accurate estimate of the amount of memory used
12839 ** to store all prepared statements.
12840 ** *pHighwater is set to zero.
12842 case SQLITE_DBSTATUS_STMT_USED: {
12843 struct Vdbe *pVdbe; /* Used to iterate through VMs */
12844 int nByte = 0; /* Used to accumulate return value */
12846 db->pnBytesFreed = &nByte;
12847 for(pVdbe=db->pVdbe; pVdbe; pVdbe=pVdbe->pNext){
12848 sqlite3VdbeDeleteObject(db, pVdbe);
12850 db->pnBytesFreed = 0;
12852 *pHighwater = 0;
12853 *pCurrent = nByte;
12855 break;
12858 default: {
12859 rc = SQLITE_ERROR;
12862 sqlite3_mutex_leave(db->mutex);
12863 return rc;
12866 /************** End of status.c **********************************************/
12867 /************** Begin file date.c ********************************************/
12869 ** 2003 October 31
12871 ** The author disclaims copyright to this source code. In place of
12872 ** a legal notice, here is a blessing:
12874 ** May you do good and not evil.
12875 ** May you find forgiveness for yourself and forgive others.
12876 ** May you share freely, never taking more than you give.
12878 *************************************************************************
12879 ** This file contains the C functions that implement date and time
12880 ** functions for SQLite.
12882 ** There is only one exported symbol in this file - the function
12883 ** sqlite3RegisterDateTimeFunctions() found at the bottom of the file.
12884 ** All other code has file scope.
12886 ** SQLite processes all times and dates as Julian Day numbers. The
12887 ** dates and times are stored as the number of days since noon
12888 ** in Greenwich on November 24, 4714 B.C. according to the Gregorian
12889 ** calendar system.
12891 ** 1970-01-01 00:00:00 is JD 2440587.5
12892 ** 2000-01-01 00:00:00 is JD 2451544.5
12894 ** This implemention requires years to be expressed as a 4-digit number
12895 ** which means that only dates between 0000-01-01 and 9999-12-31 can
12896 ** be represented, even though julian day numbers allow a much wider
12897 ** range of dates.
12899 ** The Gregorian calendar system is used for all dates and times,
12900 ** even those that predate the Gregorian calendar. Historians usually
12901 ** use the Julian calendar for dates prior to 1582-10-15 and for some
12902 ** dates afterwards, depending on locale. Beware of this difference.
12904 ** The conversion algorithms are implemented based on descriptions
12905 ** in the following text:
12907 ** Jean Meeus
12908 ** Astronomical Algorithms, 2nd Edition, 1998
12909 ** ISBM 0-943396-61-1
12910 ** Willmann-Bell, Inc
12911 ** Richmond, Virginia (USA)
12913 #include <time.h>
12915 #ifndef SQLITE_OMIT_DATETIME_FUNCS
12918 ** On recent Windows platforms, the localtime_s() function is available
12919 ** as part of the "Secure CRT". It is essentially equivalent to
12920 ** localtime_r() available under most POSIX platforms, except that the
12921 ** order of the parameters is reversed.
12923 ** See http://msdn.microsoft.com/en-us/library/a442x3ye(VS.80).aspx.
12925 ** If the user has not indicated to use localtime_r() or localtime_s()
12926 ** already, check for an MSVC build environment that provides
12927 ** localtime_s().
12929 #if !defined(HAVE_LOCALTIME_R) && !defined(HAVE_LOCALTIME_S) && \
12930 defined(_MSC_VER) && defined(_CRT_INSECURE_DEPRECATE)
12931 #define HAVE_LOCALTIME_S 1
12932 #endif
12935 ** A structure for holding a single date and time.
12937 typedef struct DateTime DateTime;
12938 struct DateTime {
12939 sqlite3_int64 iJD; /* The julian day number times 86400000 */
12940 int Y, M, D; /* Year, month, and day */
12941 int h, m; /* Hour and minutes */
12942 int tz; /* Timezone offset in minutes */
12943 double s; /* Seconds */
12944 char validYMD; /* True (1) if Y,M,D are valid */
12945 char validHMS; /* True (1) if h,m,s are valid */
12946 char validJD; /* True (1) if iJD is valid */
12947 char validTZ; /* True (1) if tz is valid */
12952 ** Convert zDate into one or more integers. Additional arguments
12953 ** come in groups of 5 as follows:
12955 ** N number of digits in the integer
12956 ** min minimum allowed value of the integer
12957 ** max maximum allowed value of the integer
12958 ** nextC first character after the integer
12959 ** pVal where to write the integers value.
12961 ** Conversions continue until one with nextC==0 is encountered.
12962 ** The function returns the number of successful conversions.
12964 static int getDigits(const char *zDate, ...){
12965 va_list ap;
12966 int val;
12967 int N;
12968 int min;
12969 int max;
12970 int nextC;
12971 int *pVal;
12972 int cnt = 0;
12973 va_start(ap, zDate);
12975 N = va_arg(ap, int);
12976 min = va_arg(ap, int);
12977 max = va_arg(ap, int);
12978 nextC = va_arg(ap, int);
12979 pVal = va_arg(ap, int*);
12980 val = 0;
12981 while( N-- ){
12982 if( !sqlite3Isdigit(*zDate) ){
12983 goto end_getDigits;
12985 val = val*10 + *zDate - '0';
12986 zDate++;
12988 if( val<min || val>max || (nextC!=0 && nextC!=*zDate) ){
12989 goto end_getDigits;
12991 *pVal = val;
12992 zDate++;
12993 cnt++;
12994 }while( nextC );
12995 end_getDigits:
12996 va_end(ap);
12997 return cnt;
13001 ** Parse a timezone extension on the end of a date-time.
13002 ** The extension is of the form:
13004 ** (+/-)HH:MM
13006 ** Or the "zulu" notation:
13008 ** Z
13010 ** If the parse is successful, write the number of minutes
13011 ** of change in p->tz and return 0. If a parser error occurs,
13012 ** return non-zero.
13014 ** A missing specifier is not considered an error.
13016 static int parseTimezone(const char *zDate, DateTime *p){
13017 int sgn = 0;
13018 int nHr, nMn;
13019 int c;
13020 while( sqlite3Isspace(*zDate) ){ zDate++; }
13021 p->tz = 0;
13022 c = *zDate;
13023 if( c=='-' ){
13024 sgn = -1;
13025 }else if( c=='+' ){
13026 sgn = +1;
13027 }else if( c=='Z' || c=='z' ){
13028 zDate++;
13029 goto zulu_time;
13030 }else{
13031 return c!=0;
13033 zDate++;
13034 if( getDigits(zDate, 2, 0, 14, ':', &nHr, 2, 0, 59, 0, &nMn)!=2 ){
13035 return 1;
13037 zDate += 5;
13038 p->tz = sgn*(nMn + nHr*60);
13039 zulu_time:
13040 while( sqlite3Isspace(*zDate) ){ zDate++; }
13041 return *zDate!=0;
13045 ** Parse times of the form HH:MM or HH:MM:SS or HH:MM:SS.FFFF.
13046 ** The HH, MM, and SS must each be exactly 2 digits. The
13047 ** fractional seconds FFFF can be one or more digits.
13049 ** Return 1 if there is a parsing error and 0 on success.
13051 static int parseHhMmSs(const char *zDate, DateTime *p){
13052 int h, m, s;
13053 double ms = 0.0;
13054 if( getDigits(zDate, 2, 0, 24, ':', &h, 2, 0, 59, 0, &m)!=2 ){
13055 return 1;
13057 zDate += 5;
13058 if( *zDate==':' ){
13059 zDate++;
13060 if( getDigits(zDate, 2, 0, 59, 0, &s)!=1 ){
13061 return 1;
13063 zDate += 2;
13064 if( *zDate=='.' && sqlite3Isdigit(zDate[1]) ){
13065 double rScale = 1.0;
13066 zDate++;
13067 while( sqlite3Isdigit(*zDate) ){
13068 ms = ms*10.0 + *zDate - '0';
13069 rScale *= 10.0;
13070 zDate++;
13072 ms /= rScale;
13074 }else{
13075 s = 0;
13077 p->validJD = 0;
13078 p->validHMS = 1;
13079 p->h = h;
13080 p->m = m;
13081 p->s = s + ms;
13082 if( parseTimezone(zDate, p) ) return 1;
13083 p->validTZ = (p->tz!=0)?1:0;
13084 return 0;
13088 ** Convert from YYYY-MM-DD HH:MM:SS to julian day. We always assume
13089 ** that the YYYY-MM-DD is according to the Gregorian calendar.
13091 ** Reference: Meeus page 61
13093 static void computeJD(DateTime *p){
13094 int Y, M, D, A, B, X1, X2;
13096 if( p->validJD ) return;
13097 if( p->validYMD ){
13098 Y = p->Y;
13099 M = p->M;
13100 D = p->D;
13101 }else{
13102 Y = 2000; /* If no YMD specified, assume 2000-Jan-01 */
13103 M = 1;
13104 D = 1;
13106 if( M<=2 ){
13107 Y--;
13108 M += 12;
13110 A = Y/100;
13111 B = 2 - A + (A/4);
13112 X1 = 36525*(Y+4716)/100;
13113 X2 = 306001*(M+1)/10000;
13114 p->iJD = (sqlite3_int64)((X1 + X2 + D + B - 1524.5 ) * 86400000);
13115 p->validJD = 1;
13116 if( p->validHMS ){
13117 p->iJD += p->h*3600000 + p->m*60000 + (sqlite3_int64)(p->s*1000);
13118 if( p->validTZ ){
13119 p->iJD -= p->tz*60000;
13120 p->validYMD = 0;
13121 p->validHMS = 0;
13122 p->validTZ = 0;
13128 ** Parse dates of the form
13130 ** YYYY-MM-DD HH:MM:SS.FFF
13131 ** YYYY-MM-DD HH:MM:SS
13132 ** YYYY-MM-DD HH:MM
13133 ** YYYY-MM-DD
13135 ** Write the result into the DateTime structure and return 0
13136 ** on success and 1 if the input string is not a well-formed
13137 ** date.
13139 static int parseYyyyMmDd(const char *zDate, DateTime *p){
13140 int Y, M, D, neg;
13142 if( zDate[0]=='-' ){
13143 zDate++;
13144 neg = 1;
13145 }else{
13146 neg = 0;
13148 if( getDigits(zDate,4,0,9999,'-',&Y,2,1,12,'-',&M,2,1,31,0,&D)!=3 ){
13149 return 1;
13151 zDate += 10;
13152 while( sqlite3Isspace(*zDate) || 'T'==*(u8*)zDate ){ zDate++; }
13153 if( parseHhMmSs(zDate, p)==0 ){
13154 /* We got the time */
13155 }else if( *zDate==0 ){
13156 p->validHMS = 0;
13157 }else{
13158 return 1;
13160 p->validJD = 0;
13161 p->validYMD = 1;
13162 p->Y = neg ? -Y : Y;
13163 p->M = M;
13164 p->D = D;
13165 if( p->validTZ ){
13166 computeJD(p);
13168 return 0;
13172 ** Set the time to the current time reported by the VFS
13174 static void setDateTimeToCurrent(sqlite3_context *context, DateTime *p){
13175 sqlite3 *db = sqlite3_context_db_handle(context);
13176 sqlite3OsCurrentTimeInt64(db->pVfs, &p->iJD);
13177 p->validJD = 1;
13181 ** Attempt to parse the given string into a Julian Day Number. Return
13182 ** the number of errors.
13184 ** The following are acceptable forms for the input string:
13186 ** YYYY-MM-DD HH:MM:SS.FFF +/-HH:MM
13187 ** DDDD.DD
13188 ** now
13190 ** In the first form, the +/-HH:MM is always optional. The fractional
13191 ** seconds extension (the ".FFF") is optional. The seconds portion
13192 ** (":SS.FFF") is option. The year and date can be omitted as long
13193 ** as there is a time string. The time string can be omitted as long
13194 ** as there is a year and date.
13196 static int parseDateOrTime(
13197 sqlite3_context *context,
13198 const char *zDate,
13199 DateTime *p
13201 double r;
13202 if( parseYyyyMmDd(zDate,p)==0 ){
13203 return 0;
13204 }else if( parseHhMmSs(zDate, p)==0 ){
13205 return 0;
13206 }else if( sqlite3StrICmp(zDate,"now")==0){
13207 setDateTimeToCurrent(context, p);
13208 return 0;
13209 }else if( sqlite3AtoF(zDate, &r, sqlite3Strlen30(zDate), SQLITE_UTF8) ){
13210 p->iJD = (sqlite3_int64)(r*86400000.0 + 0.5);
13211 p->validJD = 1;
13212 return 0;
13214 return 1;
13218 ** Compute the Year, Month, and Day from the julian day number.
13220 static void computeYMD(DateTime *p){
13221 int Z, A, B, C, D, E, X1;
13222 if( p->validYMD ) return;
13223 if( !p->validJD ){
13224 p->Y = 2000;
13225 p->M = 1;
13226 p->D = 1;
13227 }else{
13228 Z = (int)((p->iJD + 43200000)/86400000);
13229 A = (int)((Z - 1867216.25)/36524.25);
13230 A = Z + 1 + A - (A/4);
13231 B = A + 1524;
13232 C = (int)((B - 122.1)/365.25);
13233 D = (36525*C)/100;
13234 E = (int)((B-D)/30.6001);
13235 X1 = (int)(30.6001*E);
13236 p->D = B - D - X1;
13237 p->M = E<14 ? E-1 : E-13;
13238 p->Y = p->M>2 ? C - 4716 : C - 4715;
13240 p->validYMD = 1;
13244 ** Compute the Hour, Minute, and Seconds from the julian day number.
13246 static void computeHMS(DateTime *p){
13247 int s;
13248 if( p->validHMS ) return;
13249 computeJD(p);
13250 s = (int)((p->iJD + 43200000) % 86400000);
13251 p->s = s/1000.0;
13252 s = (int)p->s;
13253 p->s -= s;
13254 p->h = s/3600;
13255 s -= p->h*3600;
13256 p->m = s/60;
13257 p->s += s - p->m*60;
13258 p->validHMS = 1;
13262 ** Compute both YMD and HMS
13264 static void computeYMD_HMS(DateTime *p){
13265 computeYMD(p);
13266 computeHMS(p);
13270 ** Clear the YMD and HMS and the TZ
13272 static void clearYMD_HMS_TZ(DateTime *p){
13273 p->validYMD = 0;
13274 p->validHMS = 0;
13275 p->validTZ = 0;
13278 #ifndef SQLITE_OMIT_LOCALTIME
13280 ** Compute the difference (in milliseconds)
13281 ** between localtime and UTC (a.k.a. GMT)
13282 ** for the time value p where p is in UTC.
13284 static sqlite3_int64 localtimeOffset(DateTime *p){
13285 DateTime x, y;
13286 time_t t;
13287 x = *p;
13288 computeYMD_HMS(&x);
13289 if( x.Y<1971 || x.Y>=2038 ){
13290 x.Y = 2000;
13291 x.M = 1;
13292 x.D = 1;
13293 x.h = 0;
13294 x.m = 0;
13295 x.s = 0.0;
13296 } else {
13297 int s = (int)(x.s + 0.5);
13298 x.s = s;
13300 x.tz = 0;
13301 x.validJD = 0;
13302 computeJD(&x);
13303 t = (time_t)(x.iJD/1000 - 21086676*(i64)10000);
13304 #ifdef HAVE_LOCALTIME_R
13306 struct tm sLocal;
13307 localtime_r(&t, &sLocal);
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 #elif defined(HAVE_LOCALTIME_S) && HAVE_LOCALTIME_S
13317 struct tm sLocal;
13318 localtime_s(&sLocal, &t);
13319 y.Y = sLocal.tm_year + 1900;
13320 y.M = sLocal.tm_mon + 1;
13321 y.D = sLocal.tm_mday;
13322 y.h = sLocal.tm_hour;
13323 y.m = sLocal.tm_min;
13324 y.s = sLocal.tm_sec;
13326 #else
13328 struct tm *pTm;
13329 sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
13330 pTm = localtime(&t);
13331 y.Y = pTm->tm_year + 1900;
13332 y.M = pTm->tm_mon + 1;
13333 y.D = pTm->tm_mday;
13334 y.h = pTm->tm_hour;
13335 y.m = pTm->tm_min;
13336 y.s = pTm->tm_sec;
13337 sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
13339 #endif
13340 y.validYMD = 1;
13341 y.validHMS = 1;
13342 y.validJD = 0;
13343 y.validTZ = 0;
13344 computeJD(&y);
13345 return y.iJD - x.iJD;
13347 #endif /* SQLITE_OMIT_LOCALTIME */
13350 ** Process a modifier to a date-time stamp. The modifiers are
13351 ** as follows:
13353 ** NNN days
13354 ** NNN hours
13355 ** NNN minutes
13356 ** NNN.NNNN seconds
13357 ** NNN months
13358 ** NNN years
13359 ** start of month
13360 ** start of year
13361 ** start of week
13362 ** start of day
13363 ** weekday N
13364 ** unixepoch
13365 ** localtime
13366 ** utc
13368 ** Return 0 on success and 1 if there is any kind of error.
13370 static int parseModifier(const char *zMod, DateTime *p){
13371 int rc = 1;
13372 int n;
13373 double r;
13374 char *z, zBuf[30];
13375 z = zBuf;
13376 for(n=0; n<ArraySize(zBuf)-1 && zMod[n]; n++){
13377 z[n] = (char)sqlite3UpperToLower[(u8)zMod[n]];
13379 z[n] = 0;
13380 switch( z[0] ){
13381 #ifndef SQLITE_OMIT_LOCALTIME
13382 case 'l': {
13383 /* localtime
13385 ** Assuming the current time value is UTC (a.k.a. GMT), shift it to
13386 ** show local time.
13388 if( strcmp(z, "localtime")==0 ){
13389 computeJD(p);
13390 p->iJD += localtimeOffset(p);
13391 clearYMD_HMS_TZ(p);
13392 rc = 0;
13394 break;
13396 #endif
13397 case 'u': {
13399 ** unixepoch
13401 ** Treat the current value of p->iJD as the number of
13402 ** seconds since 1970. Convert to a real julian day number.
13404 if( strcmp(z, "unixepoch")==0 && p->validJD ){
13405 p->iJD = (p->iJD + 43200)/86400 + 21086676*(i64)10000000;
13406 clearYMD_HMS_TZ(p);
13407 rc = 0;
13409 #ifndef SQLITE_OMIT_LOCALTIME
13410 else if( strcmp(z, "utc")==0 ){
13411 sqlite3_int64 c1;
13412 computeJD(p);
13413 c1 = localtimeOffset(p);
13414 p->iJD -= c1;
13415 clearYMD_HMS_TZ(p);
13416 p->iJD += c1 - localtimeOffset(p);
13417 rc = 0;
13419 #endif
13420 break;
13422 case 'w': {
13424 ** weekday N
13426 ** Move the date to the same time on the next occurrence of
13427 ** weekday N where 0==Sunday, 1==Monday, and so forth. If the
13428 ** date is already on the appropriate weekday, this is a no-op.
13430 if( strncmp(z, "weekday ", 8)==0
13431 && sqlite3AtoF(&z[8], &r, sqlite3Strlen30(&z[8]), SQLITE_UTF8)
13432 && (n=(int)r)==r && n>=0 && r<7 ){
13433 sqlite3_int64 Z;
13434 computeYMD_HMS(p);
13435 p->validTZ = 0;
13436 p->validJD = 0;
13437 computeJD(p);
13438 Z = ((p->iJD + 129600000)/86400000) % 7;
13439 if( Z>n ) Z -= 7;
13440 p->iJD += (n - Z)*86400000;
13441 clearYMD_HMS_TZ(p);
13442 rc = 0;
13444 break;
13446 case 's': {
13448 ** start of TTTTT
13450 ** Move the date backwards to the beginning of the current day,
13451 ** or month or year.
13453 if( strncmp(z, "start of ", 9)!=0 ) break;
13454 z += 9;
13455 computeYMD(p);
13456 p->validHMS = 1;
13457 p->h = p->m = 0;
13458 p->s = 0.0;
13459 p->validTZ = 0;
13460 p->validJD = 0;
13461 if( strcmp(z,"month")==0 ){
13462 p->D = 1;
13463 rc = 0;
13464 }else if( strcmp(z,"year")==0 ){
13465 computeYMD(p);
13466 p->M = 1;
13467 p->D = 1;
13468 rc = 0;
13469 }else if( strcmp(z,"day")==0 ){
13470 rc = 0;
13472 break;
13474 case '+':
13475 case '-':
13476 case '0':
13477 case '1':
13478 case '2':
13479 case '3':
13480 case '4':
13481 case '5':
13482 case '6':
13483 case '7':
13484 case '8':
13485 case '9': {
13486 double rRounder;
13487 for(n=1; z[n] && z[n]!=':' && !sqlite3Isspace(z[n]); n++){}
13488 if( !sqlite3AtoF(z, &r, n, SQLITE_UTF8) ){
13489 rc = 1;
13490 break;
13492 if( z[n]==':' ){
13493 /* A modifier of the form (+|-)HH:MM:SS.FFF adds (or subtracts) the
13494 ** specified number of hours, minutes, seconds, and fractional seconds
13495 ** to the time. The ".FFF" may be omitted. The ":SS.FFF" may be
13496 ** omitted.
13498 const char *z2 = z;
13499 DateTime tx;
13500 sqlite3_int64 day;
13501 if( !sqlite3Isdigit(*z2) ) z2++;
13502 memset(&tx, 0, sizeof(tx));
13503 if( parseHhMmSs(z2, &tx) ) break;
13504 computeJD(&tx);
13505 tx.iJD -= 43200000;
13506 day = tx.iJD/86400000;
13507 tx.iJD -= day*86400000;
13508 if( z[0]=='-' ) tx.iJD = -tx.iJD;
13509 computeJD(p);
13510 clearYMD_HMS_TZ(p);
13511 p->iJD += tx.iJD;
13512 rc = 0;
13513 break;
13515 z += n;
13516 while( sqlite3Isspace(*z) ) z++;
13517 n = sqlite3Strlen30(z);
13518 if( n>10 || n<3 ) break;
13519 if( z[n-1]=='s' ){ z[n-1] = 0; n--; }
13520 computeJD(p);
13521 rc = 0;
13522 rRounder = r<0 ? -0.5 : +0.5;
13523 if( n==3 && strcmp(z,"day")==0 ){
13524 p->iJD += (sqlite3_int64)(r*86400000.0 + rRounder);
13525 }else if( n==4 && strcmp(z,"hour")==0 ){
13526 p->iJD += (sqlite3_int64)(r*(86400000.0/24.0) + rRounder);
13527 }else if( n==6 && strcmp(z,"minute")==0 ){
13528 p->iJD += (sqlite3_int64)(r*(86400000.0/(24.0*60.0)) + rRounder);
13529 }else if( n==6 && strcmp(z,"second")==0 ){
13530 p->iJD += (sqlite3_int64)(r*(86400000.0/(24.0*60.0*60.0)) + rRounder);
13531 }else if( n==5 && strcmp(z,"month")==0 ){
13532 int x, y;
13533 computeYMD_HMS(p);
13534 p->M += (int)r;
13535 x = p->M>0 ? (p->M-1)/12 : (p->M-12)/12;
13536 p->Y += x;
13537 p->M -= x*12;
13538 p->validJD = 0;
13539 computeJD(p);
13540 y = (int)r;
13541 if( y!=r ){
13542 p->iJD += (sqlite3_int64)((r - y)*30.0*86400000.0 + rRounder);
13544 }else if( n==4 && strcmp(z,"year")==0 ){
13545 int y = (int)r;
13546 computeYMD_HMS(p);
13547 p->Y += y;
13548 p->validJD = 0;
13549 computeJD(p);
13550 if( y!=r ){
13551 p->iJD += (sqlite3_int64)((r - y)*365.0*86400000.0 + rRounder);
13553 }else{
13554 rc = 1;
13556 clearYMD_HMS_TZ(p);
13557 break;
13559 default: {
13560 break;
13563 return rc;
13567 ** Process time function arguments. argv[0] is a date-time stamp.
13568 ** argv[1] and following are modifiers. Parse them all and write
13569 ** the resulting time into the DateTime structure p. Return 0
13570 ** on success and 1 if there are any errors.
13572 ** If there are zero parameters (if even argv[0] is undefined)
13573 ** then assume a default value of "now" for argv[0].
13575 static int isDate(
13576 sqlite3_context *context,
13577 int argc,
13578 sqlite3_value **argv,
13579 DateTime *p
13581 int i;
13582 const unsigned char *z;
13583 int eType;
13584 memset(p, 0, sizeof(*p));
13585 if( argc==0 ){
13586 setDateTimeToCurrent(context, p);
13587 }else if( (eType = sqlite3_value_type(argv[0]))==SQLITE_FLOAT
13588 || eType==SQLITE_INTEGER ){
13589 p->iJD = (sqlite3_int64)(sqlite3_value_double(argv[0])*86400000.0 + 0.5);
13590 p->validJD = 1;
13591 }else{
13592 z = sqlite3_value_text(argv[0]);
13593 if( !z || parseDateOrTime(context, (char*)z, p) ){
13594 return 1;
13597 for(i=1; i<argc; i++){
13598 if( (z = sqlite3_value_text(argv[i]))==0 || parseModifier((char*)z, p) ){
13599 return 1;
13602 return 0;
13607 ** The following routines implement the various date and time functions
13608 ** of SQLite.
13612 ** julianday( TIMESTRING, MOD, MOD, ...)
13614 ** Return the julian day number of the date specified in the arguments
13616 static void juliandayFunc(
13617 sqlite3_context *context,
13618 int argc,
13619 sqlite3_value **argv
13621 DateTime x;
13622 if( isDate(context, argc, argv, &x)==0 ){
13623 computeJD(&x);
13624 sqlite3_result_double(context, x.iJD/86400000.0);
13629 ** datetime( TIMESTRING, MOD, MOD, ...)
13631 ** Return YYYY-MM-DD HH:MM:SS
13633 static void datetimeFunc(
13634 sqlite3_context *context,
13635 int argc,
13636 sqlite3_value **argv
13638 DateTime x;
13639 if( isDate(context, argc, argv, &x)==0 ){
13640 char zBuf[100];
13641 computeYMD_HMS(&x);
13642 sqlite3_snprintf(sizeof(zBuf), zBuf, "%04d-%02d-%02d %02d:%02d:%02d",
13643 x.Y, x.M, x.D, x.h, x.m, (int)(x.s));
13644 sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
13649 ** time( TIMESTRING, MOD, MOD, ...)
13651 ** Return HH:MM:SS
13653 static void timeFunc(
13654 sqlite3_context *context,
13655 int argc,
13656 sqlite3_value **argv
13658 DateTime x;
13659 if( isDate(context, argc, argv, &x)==0 ){
13660 char zBuf[100];
13661 computeHMS(&x);
13662 sqlite3_snprintf(sizeof(zBuf), zBuf, "%02d:%02d:%02d", x.h, x.m, (int)x.s);
13663 sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
13668 ** date( TIMESTRING, MOD, MOD, ...)
13670 ** Return YYYY-MM-DD
13672 static void dateFunc(
13673 sqlite3_context *context,
13674 int argc,
13675 sqlite3_value **argv
13677 DateTime x;
13678 if( isDate(context, argc, argv, &x)==0 ){
13679 char zBuf[100];
13680 computeYMD(&x);
13681 sqlite3_snprintf(sizeof(zBuf), zBuf, "%04d-%02d-%02d", x.Y, x.M, x.D);
13682 sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
13687 ** strftime( FORMAT, TIMESTRING, MOD, MOD, ...)
13689 ** Return a string described by FORMAT. Conversions as follows:
13691 ** %d day of month
13692 ** %f ** fractional seconds SS.SSS
13693 ** %H hour 00-24
13694 ** %j day of year 000-366
13695 ** %J ** Julian day number
13696 ** %m month 01-12
13697 ** %M minute 00-59
13698 ** %s seconds since 1970-01-01
13699 ** %S seconds 00-59
13700 ** %w day of week 0-6 sunday==0
13701 ** %W week of year 00-53
13702 ** %Y year 0000-9999
13703 ** %% %
13705 static void strftimeFunc(
13706 sqlite3_context *context,
13707 int argc,
13708 sqlite3_value **argv
13710 DateTime x;
13711 u64 n;
13712 size_t i,j;
13713 char *z;
13714 sqlite3 *db;
13715 const char *zFmt = (const char*)sqlite3_value_text(argv[0]);
13716 char zBuf[100];
13717 if( zFmt==0 || isDate(context, argc-1, argv+1, &x) ) return;
13718 db = sqlite3_context_db_handle(context);
13719 for(i=0, n=1; zFmt[i]; i++, n++){
13720 if( zFmt[i]=='%' ){
13721 switch( zFmt[i+1] ){
13722 case 'd':
13723 case 'H':
13724 case 'm':
13725 case 'M':
13726 case 'S':
13727 case 'W':
13728 n++;
13729 /* fall thru */
13730 case 'w':
13731 case '%':
13732 break;
13733 case 'f':
13734 n += 8;
13735 break;
13736 case 'j':
13737 n += 3;
13738 break;
13739 case 'Y':
13740 n += 8;
13741 break;
13742 case 's':
13743 case 'J':
13744 n += 50;
13745 break;
13746 default:
13747 return; /* ERROR. return a NULL */
13749 i++;
13752 testcase( n==sizeof(zBuf)-1 );
13753 testcase( n==sizeof(zBuf) );
13754 testcase( n==(u64)db->aLimit[SQLITE_LIMIT_LENGTH]+1 );
13755 testcase( n==(u64)db->aLimit[SQLITE_LIMIT_LENGTH] );
13756 if( n<sizeof(zBuf) ){
13757 z = zBuf;
13758 }else if( n>(u64)db->aLimit[SQLITE_LIMIT_LENGTH] ){
13759 sqlite3_result_error_toobig(context);
13760 return;
13761 }else{
13762 z = sqlite3DbMallocRaw(db, (int)n);
13763 if( z==0 ){
13764 sqlite3_result_error_nomem(context);
13765 return;
13768 computeJD(&x);
13769 computeYMD_HMS(&x);
13770 for(i=j=0; zFmt[i]; i++){
13771 if( zFmt[i]!='%' ){
13772 z[j++] = zFmt[i];
13773 }else{
13774 i++;
13775 switch( zFmt[i] ){
13776 case 'd': sqlite3_snprintf(3, &z[j],"%02d",x.D); j+=2; break;
13777 case 'f': {
13778 double s = x.s;
13779 if( s>59.999 ) s = 59.999;
13780 sqlite3_snprintf(7, &z[j],"%06.3f", s);
13781 j += sqlite3Strlen30(&z[j]);
13782 break;
13784 case 'H': sqlite3_snprintf(3, &z[j],"%02d",x.h); j+=2; break;
13785 case 'W': /* Fall thru */
13786 case 'j': {
13787 int nDay; /* Number of days since 1st day of year */
13788 DateTime y = x;
13789 y.validJD = 0;
13790 y.M = 1;
13791 y.D = 1;
13792 computeJD(&y);
13793 nDay = (int)((x.iJD-y.iJD+43200000)/86400000);
13794 if( zFmt[i]=='W' ){
13795 int wd; /* 0=Monday, 1=Tuesday, ... 6=Sunday */
13796 wd = (int)(((x.iJD+43200000)/86400000)%7);
13797 sqlite3_snprintf(3, &z[j],"%02d",(nDay+7-wd)/7);
13798 j += 2;
13799 }else{
13800 sqlite3_snprintf(4, &z[j],"%03d",nDay+1);
13801 j += 3;
13803 break;
13805 case 'J': {
13806 sqlite3_snprintf(20, &z[j],"%.16g",x.iJD/86400000.0);
13807 j+=sqlite3Strlen30(&z[j]);
13808 break;
13810 case 'm': sqlite3_snprintf(3, &z[j],"%02d",x.M); j+=2; break;
13811 case 'M': sqlite3_snprintf(3, &z[j],"%02d",x.m); j+=2; break;
13812 case 's': {
13813 sqlite3_snprintf(30,&z[j],"%lld",
13814 (i64)(x.iJD/1000 - 21086676*(i64)10000));
13815 j += sqlite3Strlen30(&z[j]);
13816 break;
13818 case 'S': sqlite3_snprintf(3,&z[j],"%02d",(int)x.s); j+=2; break;
13819 case 'w': {
13820 z[j++] = (char)(((x.iJD+129600000)/86400000) % 7) + '0';
13821 break;
13823 case 'Y': {
13824 sqlite3_snprintf(5,&z[j],"%04d",x.Y); j+=sqlite3Strlen30(&z[j]);
13825 break;
13827 default: z[j++] = '%'; break;
13831 z[j] = 0;
13832 sqlite3_result_text(context, z, -1,
13833 z==zBuf ? SQLITE_TRANSIENT : SQLITE_DYNAMIC);
13837 ** current_time()
13839 ** This function returns the same value as time('now').
13841 static void ctimeFunc(
13842 sqlite3_context *context,
13843 int NotUsed,
13844 sqlite3_value **NotUsed2
13846 UNUSED_PARAMETER2(NotUsed, NotUsed2);
13847 timeFunc(context, 0, 0);
13851 ** current_date()
13853 ** This function returns the same value as date('now').
13855 static void cdateFunc(
13856 sqlite3_context *context,
13857 int NotUsed,
13858 sqlite3_value **NotUsed2
13860 UNUSED_PARAMETER2(NotUsed, NotUsed2);
13861 dateFunc(context, 0, 0);
13865 ** current_timestamp()
13867 ** This function returns the same value as datetime('now').
13869 static void ctimestampFunc(
13870 sqlite3_context *context,
13871 int NotUsed,
13872 sqlite3_value **NotUsed2
13874 UNUSED_PARAMETER2(NotUsed, NotUsed2);
13875 datetimeFunc(context, 0, 0);
13877 #endif /* !defined(SQLITE_OMIT_DATETIME_FUNCS) */
13879 #ifdef SQLITE_OMIT_DATETIME_FUNCS
13881 ** If the library is compiled to omit the full-scale date and time
13882 ** handling (to get a smaller binary), the following minimal version
13883 ** of the functions current_time(), current_date() and current_timestamp()
13884 ** are included instead. This is to support column declarations that
13885 ** include "DEFAULT CURRENT_TIME" etc.
13887 ** This function uses the C-library functions time(), gmtime()
13888 ** and strftime(). The format string to pass to strftime() is supplied
13889 ** as the user-data for the function.
13891 static void currentTimeFunc(
13892 sqlite3_context *context,
13893 int argc,
13894 sqlite3_value **argv
13896 time_t t;
13897 char *zFormat = (char *)sqlite3_user_data(context);
13898 sqlite3 *db;
13899 sqlite3_int64 iT;
13900 char zBuf[20];
13902 UNUSED_PARAMETER(argc);
13903 UNUSED_PARAMETER(argv);
13905 db = sqlite3_context_db_handle(context);
13906 sqlite3OsCurrentTimeInt64(db->pVfs, &iT);
13907 t = iT/1000 - 10000*(sqlite3_int64)21086676;
13908 #ifdef HAVE_GMTIME_R
13910 struct tm sNow;
13911 gmtime_r(&t, &sNow);
13912 strftime(zBuf, 20, zFormat, &sNow);
13914 #else
13916 struct tm *pTm;
13917 sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
13918 pTm = gmtime(&t);
13919 strftime(zBuf, 20, zFormat, pTm);
13920 sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
13922 #endif
13924 sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
13926 #endif
13929 ** This function registered all of the above C functions as SQL
13930 ** functions. This should be the only routine in this file with
13931 ** external linkage.
13933 SQLITE_PRIVATE void sqlite3RegisterDateTimeFunctions(void){
13934 static SQLITE_WSD FuncDef aDateTimeFuncs[] = {
13935 #ifndef SQLITE_OMIT_DATETIME_FUNCS
13936 FUNCTION(julianday, -1, 0, 0, juliandayFunc ),
13937 FUNCTION(date, -1, 0, 0, dateFunc ),
13938 FUNCTION(time, -1, 0, 0, timeFunc ),
13939 FUNCTION(datetime, -1, 0, 0, datetimeFunc ),
13940 FUNCTION(strftime, -1, 0, 0, strftimeFunc ),
13941 FUNCTION(current_time, 0, 0, 0, ctimeFunc ),
13942 FUNCTION(current_timestamp, 0, 0, 0, ctimestampFunc),
13943 FUNCTION(current_date, 0, 0, 0, cdateFunc ),
13944 #else
13945 STR_FUNCTION(current_time, 0, "%H:%M:%S", 0, currentTimeFunc),
13946 STR_FUNCTION(current_date, 0, "%Y-%m-%d", 0, currentTimeFunc),
13947 STR_FUNCTION(current_timestamp, 0, "%Y-%m-%d %H:%M:%S", 0, currentTimeFunc),
13948 #endif
13950 int i;
13951 FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
13952 FuncDef *aFunc = (FuncDef*)&GLOBAL(FuncDef, aDateTimeFuncs);
13954 for(i=0; i<ArraySize(aDateTimeFuncs); i++){
13955 sqlite3FuncDefInsert(pHash, &aFunc[i]);
13959 /************** End of date.c ************************************************/
13960 /************** Begin file os.c **********************************************/
13962 ** 2005 November 29
13964 ** The author disclaims copyright to this source code. In place of
13965 ** a legal notice, here is a blessing:
13967 ** May you do good and not evil.
13968 ** May you find forgiveness for yourself and forgive others.
13969 ** May you share freely, never taking more than you give.
13971 ******************************************************************************
13973 ** This file contains OS interface code that is common to all
13974 ** architectures.
13976 #define _SQLITE_OS_C_ 1
13977 #undef _SQLITE_OS_C_
13980 ** The default SQLite sqlite3_vfs implementations do not allocate
13981 ** memory (actually, os_unix.c allocates a small amount of memory
13982 ** from within OsOpen()), but some third-party implementations may.
13983 ** So we test the effects of a malloc() failing and the sqlite3OsXXX()
13984 ** function returning SQLITE_IOERR_NOMEM using the DO_OS_MALLOC_TEST macro.
13986 ** The following functions are instrumented for malloc() failure
13987 ** testing:
13989 ** sqlite3OsOpen()
13990 ** sqlite3OsRead()
13991 ** sqlite3OsWrite()
13992 ** sqlite3OsSync()
13993 ** sqlite3OsLock()
13996 #if defined(SQLITE_TEST)
13997 SQLITE_API int sqlite3_memdebug_vfs_oom_test = 1;
13998 #define DO_OS_MALLOC_TEST(x) \
13999 if (sqlite3_memdebug_vfs_oom_test && (!x || !sqlite3IsMemJournal(x))) { \
14000 void *pTstAlloc = sqlite3Malloc(10); \
14001 if (!pTstAlloc) return SQLITE_IOERR_NOMEM; \
14002 sqlite3_free(pTstAlloc); \
14004 #else
14005 #define DO_OS_MALLOC_TEST(x)
14006 #endif
14009 ** The following routines are convenience wrappers around methods
14010 ** of the sqlite3_file object. This is mostly just syntactic sugar. All
14011 ** of this would be completely automatic if SQLite were coded using
14012 ** C++ instead of plain old C.
14014 SQLITE_PRIVATE int sqlite3OsClose(sqlite3_file *pId){
14015 int rc = SQLITE_OK;
14016 if( pId->pMethods ){
14017 rc = pId->pMethods->xClose(pId);
14018 pId->pMethods = 0;
14020 return rc;
14022 SQLITE_PRIVATE int sqlite3OsRead(sqlite3_file *id, void *pBuf, int amt, i64 offset){
14023 DO_OS_MALLOC_TEST(id);
14024 return id->pMethods->xRead(id, pBuf, amt, offset);
14026 SQLITE_PRIVATE int sqlite3OsWrite(sqlite3_file *id, const void *pBuf, int amt, i64 offset){
14027 DO_OS_MALLOC_TEST(id);
14028 return id->pMethods->xWrite(id, pBuf, amt, offset);
14030 SQLITE_PRIVATE int sqlite3OsTruncate(sqlite3_file *id, i64 size){
14031 return id->pMethods->xTruncate(id, size);
14033 SQLITE_PRIVATE int sqlite3OsSync(sqlite3_file *id, int flags){
14034 DO_OS_MALLOC_TEST(id);
14035 return id->pMethods->xSync(id, flags);
14037 SQLITE_PRIVATE int sqlite3OsFileSize(sqlite3_file *id, i64 *pSize){
14038 DO_OS_MALLOC_TEST(id);
14039 return id->pMethods->xFileSize(id, pSize);
14041 SQLITE_PRIVATE int sqlite3OsLock(sqlite3_file *id, int lockType){
14042 DO_OS_MALLOC_TEST(id);
14043 return id->pMethods->xLock(id, lockType);
14045 SQLITE_PRIVATE int sqlite3OsUnlock(sqlite3_file *id, int lockType){
14046 return id->pMethods->xUnlock(id, lockType);
14048 SQLITE_PRIVATE int sqlite3OsCheckReservedLock(sqlite3_file *id, int *pResOut){
14049 DO_OS_MALLOC_TEST(id);
14050 return id->pMethods->xCheckReservedLock(id, pResOut);
14052 SQLITE_PRIVATE int sqlite3OsFileControl(sqlite3_file *id, int op, void *pArg){
14053 return id->pMethods->xFileControl(id, op, pArg);
14055 SQLITE_PRIVATE int sqlite3OsSectorSize(sqlite3_file *id){
14056 int (*xSectorSize)(sqlite3_file*) = id->pMethods->xSectorSize;
14057 return (xSectorSize ? xSectorSize(id) : SQLITE_DEFAULT_SECTOR_SIZE);
14059 SQLITE_PRIVATE int sqlite3OsDeviceCharacteristics(sqlite3_file *id){
14060 return id->pMethods->xDeviceCharacteristics(id);
14062 SQLITE_PRIVATE int sqlite3OsShmLock(sqlite3_file *id, int offset, int n, int flags){
14063 return id->pMethods->xShmLock(id, offset, n, flags);
14065 SQLITE_PRIVATE void sqlite3OsShmBarrier(sqlite3_file *id){
14066 id->pMethods->xShmBarrier(id);
14068 SQLITE_PRIVATE int sqlite3OsShmUnmap(sqlite3_file *id, int deleteFlag){
14069 return id->pMethods->xShmUnmap(id, deleteFlag);
14071 SQLITE_PRIVATE int sqlite3OsShmMap(
14072 sqlite3_file *id, /* Database file handle */
14073 int iPage,
14074 int pgsz,
14075 int bExtend, /* True to extend file if necessary */
14076 void volatile **pp /* OUT: Pointer to mapping */
14078 return id->pMethods->xShmMap(id, iPage, pgsz, bExtend, pp);
14082 ** The next group of routines are convenience wrappers around the
14083 ** VFS methods.
14085 SQLITE_PRIVATE int sqlite3OsOpen(
14086 sqlite3_vfs *pVfs,
14087 const char *zPath,
14088 sqlite3_file *pFile,
14089 int flags,
14090 int *pFlagsOut
14092 int rc;
14093 DO_OS_MALLOC_TEST(0);
14094 /* 0x87f3f is a mask of SQLITE_OPEN_ flags that are valid to be passed
14095 ** down into the VFS layer. Some SQLITE_OPEN_ flags (for example,
14096 ** SQLITE_OPEN_FULLMUTEX or SQLITE_OPEN_SHAREDCACHE) are blocked before
14097 ** reaching the VFS. */
14098 rc = pVfs->xOpen(pVfs, zPath, pFile, flags & 0x87f3f, pFlagsOut);
14099 assert( rc==SQLITE_OK || pFile->pMethods==0 );
14100 return rc;
14102 SQLITE_PRIVATE int sqlite3OsDelete(sqlite3_vfs *pVfs, const char *zPath, int dirSync){
14103 return pVfs->xDelete(pVfs, zPath, dirSync);
14105 SQLITE_PRIVATE int sqlite3OsAccess(
14106 sqlite3_vfs *pVfs,
14107 const char *zPath,
14108 int flags,
14109 int *pResOut
14111 DO_OS_MALLOC_TEST(0);
14112 return pVfs->xAccess(pVfs, zPath, flags, pResOut);
14114 SQLITE_PRIVATE int sqlite3OsFullPathname(
14115 sqlite3_vfs *pVfs,
14116 const char *zPath,
14117 int nPathOut,
14118 char *zPathOut
14120 zPathOut[0] = 0;
14121 return pVfs->xFullPathname(pVfs, zPath, nPathOut, zPathOut);
14123 #ifndef SQLITE_OMIT_LOAD_EXTENSION
14124 SQLITE_PRIVATE void *sqlite3OsDlOpen(sqlite3_vfs *pVfs, const char *zPath){
14125 return pVfs->xDlOpen(pVfs, zPath);
14127 SQLITE_PRIVATE void sqlite3OsDlError(sqlite3_vfs *pVfs, int nByte, char *zBufOut){
14128 pVfs->xDlError(pVfs, nByte, zBufOut);
14130 SQLITE_PRIVATE void (*sqlite3OsDlSym(sqlite3_vfs *pVfs, void *pHdle, const char *zSym))(void){
14131 return pVfs->xDlSym(pVfs, pHdle, zSym);
14133 SQLITE_PRIVATE void sqlite3OsDlClose(sqlite3_vfs *pVfs, void *pHandle){
14134 pVfs->xDlClose(pVfs, pHandle);
14136 #endif /* SQLITE_OMIT_LOAD_EXTENSION */
14137 SQLITE_PRIVATE int sqlite3OsRandomness(sqlite3_vfs *pVfs, int nByte, char *zBufOut){
14138 return pVfs->xRandomness(pVfs, nByte, zBufOut);
14140 SQLITE_PRIVATE int sqlite3OsSleep(sqlite3_vfs *pVfs, int nMicro){
14141 return pVfs->xSleep(pVfs, nMicro);
14143 SQLITE_PRIVATE int sqlite3OsCurrentTimeInt64(sqlite3_vfs *pVfs, sqlite3_int64 *pTimeOut){
14144 int rc;
14145 /* IMPLEMENTATION-OF: R-49045-42493 SQLite will use the xCurrentTimeInt64()
14146 ** method to get the current date and time if that method is available
14147 ** (if iVersion is 2 or greater and the function pointer is not NULL) and
14148 ** will fall back to xCurrentTime() if xCurrentTimeInt64() is
14149 ** unavailable.
14151 if( pVfs->iVersion>=2 && pVfs->xCurrentTimeInt64 ){
14152 rc = pVfs->xCurrentTimeInt64(pVfs, pTimeOut);
14153 }else{
14154 double r;
14155 rc = pVfs->xCurrentTime(pVfs, &r);
14156 *pTimeOut = (sqlite3_int64)(r*86400000.0);
14158 return rc;
14161 SQLITE_PRIVATE int sqlite3OsOpenMalloc(
14162 sqlite3_vfs *pVfs,
14163 const char *zFile,
14164 sqlite3_file **ppFile,
14165 int flags,
14166 int *pOutFlags
14168 int rc = SQLITE_NOMEM;
14169 sqlite3_file *pFile;
14170 pFile = (sqlite3_file *)sqlite3Malloc(pVfs->szOsFile);
14171 if( pFile ){
14172 rc = sqlite3OsOpen(pVfs, zFile, pFile, flags, pOutFlags);
14173 if( rc!=SQLITE_OK ){
14174 sqlite3_free(pFile);
14175 }else{
14176 *ppFile = pFile;
14179 return rc;
14181 SQLITE_PRIVATE int sqlite3OsCloseFree(sqlite3_file *pFile){
14182 int rc = SQLITE_OK;
14183 assert( pFile );
14184 rc = sqlite3OsClose(pFile);
14185 sqlite3_free(pFile);
14186 return rc;
14190 ** This function is a wrapper around the OS specific implementation of
14191 ** sqlite3_os_init(). The purpose of the wrapper is to provide the
14192 ** ability to simulate a malloc failure, so that the handling of an
14193 ** error in sqlite3_os_init() by the upper layers can be tested.
14195 SQLITE_PRIVATE int sqlite3OsInit(void){
14196 void *p = sqlite3_malloc(10);
14197 if( p==0 ) return SQLITE_NOMEM;
14198 sqlite3_free(p);
14199 return sqlite3_os_init();
14203 ** The list of all registered VFS implementations.
14205 static sqlite3_vfs * SQLITE_WSD vfsList = 0;
14206 #define vfsList GLOBAL(sqlite3_vfs *, vfsList)
14209 ** Locate a VFS by name. If no name is given, simply return the
14210 ** first VFS on the list.
14212 SQLITE_API sqlite3_vfs *sqlite3_vfs_find(const char *zVfs){
14213 sqlite3_vfs *pVfs = 0;
14214 #if SQLITE_THREADSAFE
14215 sqlite3_mutex *mutex;
14216 #endif
14217 #ifndef SQLITE_OMIT_AUTOINIT
14218 int rc = sqlite3_initialize();
14219 if( rc ) return 0;
14220 #endif
14221 #if SQLITE_THREADSAFE
14222 mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
14223 #endif
14224 sqlite3_mutex_enter(mutex);
14225 for(pVfs = vfsList; pVfs; pVfs=pVfs->pNext){
14226 if( zVfs==0 ) break;
14227 if( strcmp(zVfs, pVfs->zName)==0 ) break;
14229 sqlite3_mutex_leave(mutex);
14230 return pVfs;
14234 ** Unlink a VFS from the linked list
14236 static void vfsUnlink(sqlite3_vfs *pVfs){
14237 assert( sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER)) );
14238 if( pVfs==0 ){
14239 /* No-op */
14240 }else if( vfsList==pVfs ){
14241 vfsList = pVfs->pNext;
14242 }else if( vfsList ){
14243 sqlite3_vfs *p = vfsList;
14244 while( p->pNext && p->pNext!=pVfs ){
14245 p = p->pNext;
14247 if( p->pNext==pVfs ){
14248 p->pNext = pVfs->pNext;
14254 ** Register a VFS with the system. It is harmless to register the same
14255 ** VFS multiple times. The new VFS becomes the default if makeDflt is
14256 ** true.
14258 SQLITE_API int sqlite3_vfs_register(sqlite3_vfs *pVfs, int makeDflt){
14259 sqlite3_mutex *mutex = 0;
14260 #ifndef SQLITE_OMIT_AUTOINIT
14261 int rc = sqlite3_initialize();
14262 if( rc ) return rc;
14263 #endif
14264 mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
14265 sqlite3_mutex_enter(mutex);
14266 vfsUnlink(pVfs);
14267 if( makeDflt || vfsList==0 ){
14268 pVfs->pNext = vfsList;
14269 vfsList = pVfs;
14270 }else{
14271 pVfs->pNext = vfsList->pNext;
14272 vfsList->pNext = pVfs;
14274 assert(vfsList);
14275 sqlite3_mutex_leave(mutex);
14276 return SQLITE_OK;
14280 ** Unregister a VFS so that it is no longer accessible.
14282 SQLITE_API int sqlite3_vfs_unregister(sqlite3_vfs *pVfs){
14283 #if SQLITE_THREADSAFE
14284 sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
14285 #endif
14286 sqlite3_mutex_enter(mutex);
14287 vfsUnlink(pVfs);
14288 sqlite3_mutex_leave(mutex);
14289 return SQLITE_OK;
14292 /************** End of os.c **************************************************/
14293 /************** Begin file fault.c *******************************************/
14295 ** 2008 Jan 22
14297 ** The author disclaims copyright to this source code. In place of
14298 ** a legal notice, here is a blessing:
14300 ** May you do good and not evil.
14301 ** May you find forgiveness for yourself and forgive others.
14302 ** May you share freely, never taking more than you give.
14304 *************************************************************************
14306 ** This file contains code to support the concept of "benign"
14307 ** malloc failures (when the xMalloc() or xRealloc() method of the
14308 ** sqlite3_mem_methods structure fails to allocate a block of memory
14309 ** and returns 0).
14311 ** Most malloc failures are non-benign. After they occur, SQLite
14312 ** abandons the current operation and returns an error code (usually
14313 ** SQLITE_NOMEM) to the user. However, sometimes a fault is not necessarily
14314 ** fatal. For example, if a malloc fails while resizing a hash table, this
14315 ** is completely recoverable simply by not carrying out the resize. The
14316 ** hash table will continue to function normally. So a malloc failure
14317 ** during a hash table resize is a benign fault.
14321 #ifndef SQLITE_OMIT_BUILTIN_TEST
14324 ** Global variables.
14326 typedef struct BenignMallocHooks BenignMallocHooks;
14327 static SQLITE_WSD struct BenignMallocHooks {
14328 void (*xBenignBegin)(void);
14329 void (*xBenignEnd)(void);
14330 } sqlite3Hooks = { 0, 0 };
14332 /* The "wsdHooks" macro will resolve to the appropriate BenignMallocHooks
14333 ** structure. If writable static data is unsupported on the target,
14334 ** we have to locate the state vector at run-time. In the more common
14335 ** case where writable static data is supported, wsdHooks can refer directly
14336 ** to the "sqlite3Hooks" state vector declared above.
14338 #ifdef SQLITE_OMIT_WSD
14339 # define wsdHooksInit \
14340 BenignMallocHooks *x = &GLOBAL(BenignMallocHooks,sqlite3Hooks)
14341 # define wsdHooks x[0]
14342 #else
14343 # define wsdHooksInit
14344 # define wsdHooks sqlite3Hooks
14345 #endif
14349 ** Register hooks to call when sqlite3BeginBenignMalloc() and
14350 ** sqlite3EndBenignMalloc() are called, respectively.
14352 SQLITE_PRIVATE void sqlite3BenignMallocHooks(
14353 void (*xBenignBegin)(void),
14354 void (*xBenignEnd)(void)
14356 wsdHooksInit;
14357 wsdHooks.xBenignBegin = xBenignBegin;
14358 wsdHooks.xBenignEnd = xBenignEnd;
14362 ** This (sqlite3EndBenignMalloc()) is called by SQLite code to indicate that
14363 ** subsequent malloc failures are benign. A call to sqlite3EndBenignMalloc()
14364 ** indicates that subsequent malloc failures are non-benign.
14366 SQLITE_PRIVATE void sqlite3BeginBenignMalloc(void){
14367 wsdHooksInit;
14368 if( wsdHooks.xBenignBegin ){
14369 wsdHooks.xBenignBegin();
14372 SQLITE_PRIVATE void sqlite3EndBenignMalloc(void){
14373 wsdHooksInit;
14374 if( wsdHooks.xBenignEnd ){
14375 wsdHooks.xBenignEnd();
14379 #endif /* #ifndef SQLITE_OMIT_BUILTIN_TEST */
14381 /************** End of fault.c ***********************************************/
14382 /************** Begin file mem0.c ********************************************/
14384 ** 2008 October 28
14386 ** The author disclaims copyright to this source code. In place of
14387 ** a legal notice, here is a blessing:
14389 ** May you do good and not evil.
14390 ** May you find forgiveness for yourself and forgive others.
14391 ** May you share freely, never taking more than you give.
14393 *************************************************************************
14395 ** This file contains a no-op memory allocation drivers for use when
14396 ** SQLITE_ZERO_MALLOC is defined. The allocation drivers implemented
14397 ** here always fail. SQLite will not operate with these drivers. These
14398 ** are merely placeholders. Real drivers must be substituted using
14399 ** sqlite3_config() before SQLite will operate.
14403 ** This version of the memory allocator is the default. It is
14404 ** used when no other memory allocator is specified using compile-time
14405 ** macros.
14407 #ifdef SQLITE_ZERO_MALLOC
14410 ** No-op versions of all memory allocation routines
14412 static void *sqlite3MemMalloc(int nByte){ return 0; }
14413 static void sqlite3MemFree(void *pPrior){ return; }
14414 static void *sqlite3MemRealloc(void *pPrior, int nByte){ return 0; }
14415 static int sqlite3MemSize(void *pPrior){ return 0; }
14416 static int sqlite3MemRoundup(int n){ return n; }
14417 static int sqlite3MemInit(void *NotUsed){ return SQLITE_OK; }
14418 static void sqlite3MemShutdown(void *NotUsed){ return; }
14421 ** This routine is the only routine in this file with external linkage.
14423 ** Populate the low-level memory allocation function pointers in
14424 ** sqlite3GlobalConfig.m with pointers to the routines in this file.
14426 SQLITE_PRIVATE void sqlite3MemSetDefault(void){
14427 static const sqlite3_mem_methods defaultMethods = {
14428 sqlite3MemMalloc,
14429 sqlite3MemFree,
14430 sqlite3MemRealloc,
14431 sqlite3MemSize,
14432 sqlite3MemRoundup,
14433 sqlite3MemInit,
14434 sqlite3MemShutdown,
14437 sqlite3_config(SQLITE_CONFIG_MALLOC, &defaultMethods);
14440 #endif /* SQLITE_ZERO_MALLOC */
14442 /************** End of mem0.c ************************************************/
14443 /************** Begin file mem1.c ********************************************/
14445 ** 2007 August 14
14447 ** The author disclaims copyright to this source code. In place of
14448 ** a legal notice, here is a blessing:
14450 ** May you do good and not evil.
14451 ** May you find forgiveness for yourself and forgive others.
14452 ** May you share freely, never taking more than you give.
14454 *************************************************************************
14456 ** This file contains low-level memory allocation drivers for when
14457 ** SQLite will use the standard C-library malloc/realloc/free interface
14458 ** to obtain the memory it needs.
14460 ** This file contains implementations of the low-level memory allocation
14461 ** routines specified in the sqlite3_mem_methods object.
14465 ** This version of the memory allocator is the default. It is
14466 ** used when no other memory allocator is specified using compile-time
14467 ** macros.
14469 #ifdef SQLITE_SYSTEM_MALLOC
14472 ** Like malloc(), but remember the size of the allocation
14473 ** so that we can find it later using sqlite3MemSize().
14475 ** For this low-level routine, we are guaranteed that nByte>0 because
14476 ** cases of nByte<=0 will be intercepted and dealt with by higher level
14477 ** routines.
14479 static void *sqlite3MemMalloc(int nByte){
14480 sqlite3_int64 *p;
14481 assert( nByte>0 );
14482 nByte = ROUND8(nByte);
14483 p = malloc( nByte+8 );
14484 if( p ){
14485 p[0] = nByte;
14486 p++;
14487 }else{
14488 testcase( sqlite3GlobalConfig.xLog!=0 );
14489 sqlite3_log(SQLITE_NOMEM, "failed to allocate %u bytes of memory", nByte);
14491 return (void *)p;
14495 ** Like free() but works for allocations obtained from sqlite3MemMalloc()
14496 ** or sqlite3MemRealloc().
14498 ** For this low-level routine, we already know that pPrior!=0 since
14499 ** cases where pPrior==0 will have been intecepted and dealt with
14500 ** by higher-level routines.
14502 static void sqlite3MemFree(void *pPrior){
14503 sqlite3_int64 *p = (sqlite3_int64*)pPrior;
14504 assert( pPrior!=0 );
14505 p--;
14506 free(p);
14510 ** Report the allocated size of a prior return from xMalloc()
14511 ** or xRealloc().
14513 static int sqlite3MemSize(void *pPrior){
14514 sqlite3_int64 *p;
14515 if( pPrior==0 ) return 0;
14516 p = (sqlite3_int64*)pPrior;
14517 p--;
14518 return (int)p[0];
14522 ** Like realloc(). Resize an allocation previously obtained from
14523 ** sqlite3MemMalloc().
14525 ** For this low-level interface, we know that pPrior!=0. Cases where
14526 ** pPrior==0 while have been intercepted by higher-level routine and
14527 ** redirected to xMalloc. Similarly, we know that nByte>0 becauses
14528 ** cases where nByte<=0 will have been intercepted by higher-level
14529 ** routines and redirected to xFree.
14531 static void *sqlite3MemRealloc(void *pPrior, int nByte){
14532 sqlite3_int64 *p = (sqlite3_int64*)pPrior;
14533 assert( pPrior!=0 && nByte>0 );
14534 assert( nByte==ROUND8(nByte) ); /* EV: R-46199-30249 */
14535 p--;
14536 p = realloc(p, nByte+8 );
14537 if( p ){
14538 p[0] = nByte;
14539 p++;
14540 }else{
14541 testcase( sqlite3GlobalConfig.xLog!=0 );
14542 sqlite3_log(SQLITE_NOMEM,
14543 "failed memory resize %u to %u bytes",
14544 sqlite3MemSize(pPrior), nByte);
14546 return (void*)p;
14550 ** Round up a request size to the next valid allocation size.
14552 static int sqlite3MemRoundup(int n){
14553 return ROUND8(n);
14557 ** Initialize this module.
14559 static int sqlite3MemInit(void *NotUsed){
14560 UNUSED_PARAMETER(NotUsed);
14561 return SQLITE_OK;
14565 ** Deinitialize this module.
14567 static void sqlite3MemShutdown(void *NotUsed){
14568 UNUSED_PARAMETER(NotUsed);
14569 return;
14573 ** This routine is the only routine in this file with external linkage.
14575 ** Populate the low-level memory allocation function pointers in
14576 ** sqlite3GlobalConfig.m with pointers to the routines in this file.
14578 SQLITE_PRIVATE void sqlite3MemSetDefault(void){
14579 static const sqlite3_mem_methods defaultMethods = {
14580 sqlite3MemMalloc,
14581 sqlite3MemFree,
14582 sqlite3MemRealloc,
14583 sqlite3MemSize,
14584 sqlite3MemRoundup,
14585 sqlite3MemInit,
14586 sqlite3MemShutdown,
14589 sqlite3_config(SQLITE_CONFIG_MALLOC, &defaultMethods);
14592 #endif /* SQLITE_SYSTEM_MALLOC */
14594 /************** End of mem1.c ************************************************/
14595 /************** Begin file mem2.c ********************************************/
14597 ** 2007 August 15
14599 ** The author disclaims copyright to this source code. In place of
14600 ** a legal notice, here is a blessing:
14602 ** May you do good and not evil.
14603 ** May you find forgiveness for yourself and forgive others.
14604 ** May you share freely, never taking more than you give.
14606 *************************************************************************
14608 ** This file contains low-level memory allocation drivers for when
14609 ** SQLite will use the standard C-library malloc/realloc/free interface
14610 ** to obtain the memory it needs while adding lots of additional debugging
14611 ** information to each allocation in order to help detect and fix memory
14612 ** leaks and memory usage errors.
14614 ** This file contains implementations of the low-level memory allocation
14615 ** routines specified in the sqlite3_mem_methods object.
14619 ** This version of the memory allocator is used only if the
14620 ** SQLITE_MEMDEBUG macro is defined
14622 #ifdef SQLITE_MEMDEBUG
14625 ** The backtrace functionality is only available with GLIBC
14627 #ifdef __GLIBC__
14628 extern int backtrace(void**,int);
14629 extern void backtrace_symbols_fd(void*const*,int,int);
14630 #else
14631 # define backtrace(A,B) 1
14632 # define backtrace_symbols_fd(A,B,C)
14633 #endif
14636 ** Each memory allocation looks like this:
14638 ** ------------------------------------------------------------------------
14639 ** | Title | backtrace pointers | MemBlockHdr | allocation | EndGuard |
14640 ** ------------------------------------------------------------------------
14642 ** The application code sees only a pointer to the allocation. We have
14643 ** to back up from the allocation pointer to find the MemBlockHdr. The
14644 ** MemBlockHdr tells us the size of the allocation and the number of
14645 ** backtrace pointers. There is also a guard word at the end of the
14646 ** MemBlockHdr.
14648 struct MemBlockHdr {
14649 i64 iSize; /* Size of this allocation */
14650 struct MemBlockHdr *pNext, *pPrev; /* Linked list of all unfreed memory */
14651 char nBacktrace; /* Number of backtraces on this alloc */
14652 char nBacktraceSlots; /* Available backtrace slots */
14653 u8 nTitle; /* Bytes of title; includes '\0' */
14654 u8 eType; /* Allocation type code */
14655 int iForeGuard; /* Guard word for sanity */
14659 ** Guard words
14661 #define FOREGUARD 0x80F5E153
14662 #define REARGUARD 0xE4676B53
14665 ** Number of malloc size increments to track.
14667 #define NCSIZE 1000
14670 ** All of the static variables used by this module are collected
14671 ** into a single structure named "mem". This is to keep the
14672 ** static variables organized and to reduce namespace pollution
14673 ** when this module is combined with other in the amalgamation.
14675 static struct {
14678 ** Mutex to control access to the memory allocation subsystem.
14680 sqlite3_mutex *mutex;
14683 ** Head and tail of a linked list of all outstanding allocations
14685 struct MemBlockHdr *pFirst;
14686 struct MemBlockHdr *pLast;
14689 ** The number of levels of backtrace to save in new allocations.
14691 int nBacktrace;
14692 void (*xBacktrace)(int, int, void **);
14695 ** Title text to insert in front of each block
14697 int nTitle; /* Bytes of zTitle to save. Includes '\0' and padding */
14698 char zTitle[100]; /* The title text */
14701 ** sqlite3MallocDisallow() increments the following counter.
14702 ** sqlite3MallocAllow() decrements it.
14704 int disallow; /* Do not allow memory allocation */
14707 ** Gather statistics on the sizes of memory allocations.
14708 ** nAlloc[i] is the number of allocation attempts of i*8
14709 ** bytes. i==NCSIZE is the number of allocation attempts for
14710 ** sizes more than NCSIZE*8 bytes.
14712 int nAlloc[NCSIZE]; /* Total number of allocations */
14713 int nCurrent[NCSIZE]; /* Current number of allocations */
14714 int mxCurrent[NCSIZE]; /* Highwater mark for nCurrent */
14716 } mem;
14720 ** Adjust memory usage statistics
14722 static void adjustStats(int iSize, int increment){
14723 int i = ROUND8(iSize)/8;
14724 if( i>NCSIZE-1 ){
14725 i = NCSIZE - 1;
14727 if( increment>0 ){
14728 mem.nAlloc[i]++;
14729 mem.nCurrent[i]++;
14730 if( mem.nCurrent[i]>mem.mxCurrent[i] ){
14731 mem.mxCurrent[i] = mem.nCurrent[i];
14733 }else{
14734 mem.nCurrent[i]--;
14735 assert( mem.nCurrent[i]>=0 );
14740 ** Given an allocation, find the MemBlockHdr for that allocation.
14742 ** This routine checks the guards at either end of the allocation and
14743 ** if they are incorrect it asserts.
14745 static struct MemBlockHdr *sqlite3MemsysGetHeader(void *pAllocation){
14746 struct MemBlockHdr *p;
14747 int *pInt;
14748 u8 *pU8;
14749 int nReserve;
14751 p = (struct MemBlockHdr*)pAllocation;
14752 p--;
14753 assert( p->iForeGuard==(int)FOREGUARD );
14754 nReserve = ROUND8(p->iSize);
14755 pInt = (int*)pAllocation;
14756 pU8 = (u8*)pAllocation;
14757 assert( pInt[nReserve/sizeof(int)]==(int)REARGUARD );
14758 /* This checks any of the "extra" bytes allocated due
14759 ** to rounding up to an 8 byte boundary to ensure
14760 ** they haven't been overwritten.
14762 while( nReserve-- > p->iSize ) assert( pU8[nReserve]==0x65 );
14763 return p;
14767 ** Return the number of bytes currently allocated at address p.
14769 static int sqlite3MemSize(void *p){
14770 struct MemBlockHdr *pHdr;
14771 if( !p ){
14772 return 0;
14774 pHdr = sqlite3MemsysGetHeader(p);
14775 return pHdr->iSize;
14779 ** Initialize the memory allocation subsystem.
14781 static int sqlite3MemInit(void *NotUsed){
14782 UNUSED_PARAMETER(NotUsed);
14783 assert( (sizeof(struct MemBlockHdr)&7) == 0 );
14784 if( !sqlite3GlobalConfig.bMemstat ){
14785 /* If memory status is enabled, then the malloc.c wrapper will already
14786 ** hold the STATIC_MEM mutex when the routines here are invoked. */
14787 mem.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
14789 return SQLITE_OK;
14793 ** Deinitialize the memory allocation subsystem.
14795 static void sqlite3MemShutdown(void *NotUsed){
14796 UNUSED_PARAMETER(NotUsed);
14797 mem.mutex = 0;
14801 ** Round up a request size to the next valid allocation size.
14803 static int sqlite3MemRoundup(int n){
14804 return ROUND8(n);
14808 ** Fill a buffer with pseudo-random bytes. This is used to preset
14809 ** the content of a new memory allocation to unpredictable values and
14810 ** to clear the content of a freed allocation to unpredictable values.
14812 static void randomFill(char *pBuf, int nByte){
14813 unsigned int x, y, r;
14814 x = SQLITE_PTR_TO_INT(pBuf);
14815 y = nByte | 1;
14816 while( nByte >= 4 ){
14817 x = (x>>1) ^ (-(x&1) & 0xd0000001);
14818 y = y*1103515245 + 12345;
14819 r = x ^ y;
14820 *(int*)pBuf = r;
14821 pBuf += 4;
14822 nByte -= 4;
14824 while( nByte-- > 0 ){
14825 x = (x>>1) ^ (-(x&1) & 0xd0000001);
14826 y = y*1103515245 + 12345;
14827 r = x ^ y;
14828 *(pBuf++) = r & 0xff;
14833 ** Allocate nByte bytes of memory.
14835 static void *sqlite3MemMalloc(int nByte){
14836 struct MemBlockHdr *pHdr;
14837 void **pBt;
14838 char *z;
14839 int *pInt;
14840 void *p = 0;
14841 int totalSize;
14842 int nReserve;
14843 sqlite3_mutex_enter(mem.mutex);
14844 assert( mem.disallow==0 );
14845 nReserve = ROUND8(nByte);
14846 totalSize = nReserve + sizeof(*pHdr) + sizeof(int) +
14847 mem.nBacktrace*sizeof(void*) + mem.nTitle;
14848 p = malloc(totalSize);
14849 if( p ){
14850 z = p;
14851 pBt = (void**)&z[mem.nTitle];
14852 pHdr = (struct MemBlockHdr*)&pBt[mem.nBacktrace];
14853 pHdr->pNext = 0;
14854 pHdr->pPrev = mem.pLast;
14855 if( mem.pLast ){
14856 mem.pLast->pNext = pHdr;
14857 }else{
14858 mem.pFirst = pHdr;
14860 mem.pLast = pHdr;
14861 pHdr->iForeGuard = FOREGUARD;
14862 pHdr->eType = MEMTYPE_HEAP;
14863 pHdr->nBacktraceSlots = mem.nBacktrace;
14864 pHdr->nTitle = mem.nTitle;
14865 if( mem.nBacktrace ){
14866 void *aAddr[40];
14867 pHdr->nBacktrace = backtrace(aAddr, mem.nBacktrace+1)-1;
14868 memcpy(pBt, &aAddr[1], pHdr->nBacktrace*sizeof(void*));
14869 assert(pBt[0]);
14870 if( mem.xBacktrace ){
14871 mem.xBacktrace(nByte, pHdr->nBacktrace-1, &aAddr[1]);
14873 }else{
14874 pHdr->nBacktrace = 0;
14876 if( mem.nTitle ){
14877 memcpy(z, mem.zTitle, mem.nTitle);
14879 pHdr->iSize = nByte;
14880 adjustStats(nByte, +1);
14881 pInt = (int*)&pHdr[1];
14882 pInt[nReserve/sizeof(int)] = REARGUARD;
14883 randomFill((char*)pInt, nByte);
14884 memset(((char*)pInt)+nByte, 0x65, nReserve-nByte);
14885 p = (void*)pInt;
14887 sqlite3_mutex_leave(mem.mutex);
14888 return p;
14892 ** Free memory.
14894 static void sqlite3MemFree(void *pPrior){
14895 struct MemBlockHdr *pHdr;
14896 void **pBt;
14897 char *z;
14898 assert( sqlite3GlobalConfig.bMemstat || sqlite3GlobalConfig.bCoreMutex==0
14899 || mem.mutex!=0 );
14900 pHdr = sqlite3MemsysGetHeader(pPrior);
14901 pBt = (void**)pHdr;
14902 pBt -= pHdr->nBacktraceSlots;
14903 sqlite3_mutex_enter(mem.mutex);
14904 if( pHdr->pPrev ){
14905 assert( pHdr->pPrev->pNext==pHdr );
14906 pHdr->pPrev->pNext = pHdr->pNext;
14907 }else{
14908 assert( mem.pFirst==pHdr );
14909 mem.pFirst = pHdr->pNext;
14911 if( pHdr->pNext ){
14912 assert( pHdr->pNext->pPrev==pHdr );
14913 pHdr->pNext->pPrev = pHdr->pPrev;
14914 }else{
14915 assert( mem.pLast==pHdr );
14916 mem.pLast = pHdr->pPrev;
14918 z = (char*)pBt;
14919 z -= pHdr->nTitle;
14920 adjustStats(pHdr->iSize, -1);
14921 randomFill(z, sizeof(void*)*pHdr->nBacktraceSlots + sizeof(*pHdr) +
14922 pHdr->iSize + sizeof(int) + pHdr->nTitle);
14923 free(z);
14924 sqlite3_mutex_leave(mem.mutex);
14928 ** Change the size of an existing memory allocation.
14930 ** For this debugging implementation, we *always* make a copy of the
14931 ** allocation into a new place in memory. In this way, if the
14932 ** higher level code is using pointer to the old allocation, it is
14933 ** much more likely to break and we are much more liking to find
14934 ** the error.
14936 static void *sqlite3MemRealloc(void *pPrior, int nByte){
14937 struct MemBlockHdr *pOldHdr;
14938 void *pNew;
14939 assert( mem.disallow==0 );
14940 assert( (nByte & 7)==0 ); /* EV: R-46199-30249 */
14941 pOldHdr = sqlite3MemsysGetHeader(pPrior);
14942 pNew = sqlite3MemMalloc(nByte);
14943 if( pNew ){
14944 memcpy(pNew, pPrior, nByte<pOldHdr->iSize ? nByte : pOldHdr->iSize);
14945 if( nByte>pOldHdr->iSize ){
14946 randomFill(&((char*)pNew)[pOldHdr->iSize], nByte - pOldHdr->iSize);
14948 sqlite3MemFree(pPrior);
14950 return pNew;
14954 ** Populate the low-level memory allocation function pointers in
14955 ** sqlite3GlobalConfig.m with pointers to the routines in this file.
14957 SQLITE_PRIVATE void sqlite3MemSetDefault(void){
14958 static const sqlite3_mem_methods defaultMethods = {
14959 sqlite3MemMalloc,
14960 sqlite3MemFree,
14961 sqlite3MemRealloc,
14962 sqlite3MemSize,
14963 sqlite3MemRoundup,
14964 sqlite3MemInit,
14965 sqlite3MemShutdown,
14968 sqlite3_config(SQLITE_CONFIG_MALLOC, &defaultMethods);
14972 ** Set the "type" of an allocation.
14974 SQLITE_PRIVATE void sqlite3MemdebugSetType(void *p, u8 eType){
14975 if( p && sqlite3GlobalConfig.m.xMalloc==sqlite3MemMalloc ){
14976 struct MemBlockHdr *pHdr;
14977 pHdr = sqlite3MemsysGetHeader(p);
14978 assert( pHdr->iForeGuard==FOREGUARD );
14979 pHdr->eType = eType;
14984 ** Return TRUE if the mask of type in eType matches the type of the
14985 ** allocation p. Also return true if p==NULL.
14987 ** This routine is designed for use within an assert() statement, to
14988 ** verify the type of an allocation. For example:
14990 ** assert( sqlite3MemdebugHasType(p, MEMTYPE_DB) );
14992 SQLITE_PRIVATE int sqlite3MemdebugHasType(void *p, u8 eType){
14993 int rc = 1;
14994 if( p && sqlite3GlobalConfig.m.xMalloc==sqlite3MemMalloc ){
14995 struct MemBlockHdr *pHdr;
14996 pHdr = sqlite3MemsysGetHeader(p);
14997 assert( pHdr->iForeGuard==FOREGUARD ); /* Allocation is valid */
14998 if( (pHdr->eType&eType)==0 ){
14999 rc = 0;
15002 return rc;
15006 ** Return TRUE if the mask of type in eType matches no bits of the type of the
15007 ** allocation p. Also return true if p==NULL.
15009 ** This routine is designed for use within an assert() statement, to
15010 ** verify the type of an allocation. For example:
15012 ** assert( sqlite3MemdebugNoType(p, MEMTYPE_DB) );
15014 SQLITE_PRIVATE int sqlite3MemdebugNoType(void *p, u8 eType){
15015 int rc = 1;
15016 if( p && sqlite3GlobalConfig.m.xMalloc==sqlite3MemMalloc ){
15017 struct MemBlockHdr *pHdr;
15018 pHdr = sqlite3MemsysGetHeader(p);
15019 assert( pHdr->iForeGuard==FOREGUARD ); /* Allocation is valid */
15020 if( (pHdr->eType&eType)!=0 ){
15021 rc = 0;
15024 return rc;
15028 ** Set the number of backtrace levels kept for each allocation.
15029 ** A value of zero turns off backtracing. The number is always rounded
15030 ** up to a multiple of 2.
15032 SQLITE_PRIVATE void sqlite3MemdebugBacktrace(int depth){
15033 if( depth<0 ){ depth = 0; }
15034 if( depth>20 ){ depth = 20; }
15035 depth = (depth+1)&0xfe;
15036 mem.nBacktrace = depth;
15039 SQLITE_PRIVATE void sqlite3MemdebugBacktraceCallback(void (*xBacktrace)(int, int, void **)){
15040 mem.xBacktrace = xBacktrace;
15044 ** Set the title string for subsequent allocations.
15046 SQLITE_PRIVATE void sqlite3MemdebugSettitle(const char *zTitle){
15047 unsigned int n = sqlite3Strlen30(zTitle) + 1;
15048 sqlite3_mutex_enter(mem.mutex);
15049 if( n>=sizeof(mem.zTitle) ) n = sizeof(mem.zTitle)-1;
15050 memcpy(mem.zTitle, zTitle, n);
15051 mem.zTitle[n] = 0;
15052 mem.nTitle = ROUND8(n);
15053 sqlite3_mutex_leave(mem.mutex);
15056 SQLITE_PRIVATE void sqlite3MemdebugSync(){
15057 struct MemBlockHdr *pHdr;
15058 for(pHdr=mem.pFirst; pHdr; pHdr=pHdr->pNext){
15059 void **pBt = (void**)pHdr;
15060 pBt -= pHdr->nBacktraceSlots;
15061 mem.xBacktrace(pHdr->iSize, pHdr->nBacktrace-1, &pBt[1]);
15066 ** Open the file indicated and write a log of all unfreed memory
15067 ** allocations into that log.
15069 SQLITE_PRIVATE void sqlite3MemdebugDump(const char *zFilename){
15070 FILE *out;
15071 struct MemBlockHdr *pHdr;
15072 void **pBt;
15073 int i;
15074 out = fopen(zFilename, "w");
15075 if( out==0 ){
15076 fprintf(stderr, "** Unable to output memory debug output log: %s **\n",
15077 zFilename);
15078 return;
15080 for(pHdr=mem.pFirst; pHdr; pHdr=pHdr->pNext){
15081 char *z = (char*)pHdr;
15082 z -= pHdr->nBacktraceSlots*sizeof(void*) + pHdr->nTitle;
15083 fprintf(out, "**** %lld bytes at %p from %s ****\n",
15084 pHdr->iSize, &pHdr[1], pHdr->nTitle ? z : "???");
15085 if( pHdr->nBacktrace ){
15086 fflush(out);
15087 pBt = (void**)pHdr;
15088 pBt -= pHdr->nBacktraceSlots;
15089 backtrace_symbols_fd(pBt, pHdr->nBacktrace, fileno(out));
15090 fprintf(out, "\n");
15093 fprintf(out, "COUNTS:\n");
15094 for(i=0; i<NCSIZE-1; i++){
15095 if( mem.nAlloc[i] ){
15096 fprintf(out, " %5d: %10d %10d %10d\n",
15097 i*8, mem.nAlloc[i], mem.nCurrent[i], mem.mxCurrent[i]);
15100 if( mem.nAlloc[NCSIZE-1] ){
15101 fprintf(out, " %5d: %10d %10d %10d\n",
15102 NCSIZE*8-8, mem.nAlloc[NCSIZE-1],
15103 mem.nCurrent[NCSIZE-1], mem.mxCurrent[NCSIZE-1]);
15105 fclose(out);
15109 ** Return the number of times sqlite3MemMalloc() has been called.
15111 SQLITE_PRIVATE int sqlite3MemdebugMallocCount(){
15112 int i;
15113 int nTotal = 0;
15114 for(i=0; i<NCSIZE; i++){
15115 nTotal += mem.nAlloc[i];
15117 return nTotal;
15121 #endif /* SQLITE_MEMDEBUG */
15123 /************** End of mem2.c ************************************************/
15124 /************** Begin file mem3.c ********************************************/
15126 ** 2007 October 14
15128 ** The author disclaims copyright to this source code. In place of
15129 ** a legal notice, here is a blessing:
15131 ** May you do good and not evil.
15132 ** May you find forgiveness for yourself and forgive others.
15133 ** May you share freely, never taking more than you give.
15135 *************************************************************************
15136 ** This file contains the C functions that implement a memory
15137 ** allocation subsystem for use by SQLite.
15139 ** This version of the memory allocation subsystem omits all
15140 ** use of malloc(). The SQLite user supplies a block of memory
15141 ** before calling sqlite3_initialize() from which allocations
15142 ** are made and returned by the xMalloc() and xRealloc()
15143 ** implementations. Once sqlite3_initialize() has been called,
15144 ** the amount of memory available to SQLite is fixed and cannot
15145 ** be changed.
15147 ** This version of the memory allocation subsystem is included
15148 ** in the build only if SQLITE_ENABLE_MEMSYS3 is defined.
15152 ** This version of the memory allocator is only built into the library
15153 ** SQLITE_ENABLE_MEMSYS3 is defined. Defining this symbol does not
15154 ** mean that the library will use a memory-pool by default, just that
15155 ** it is available. The mempool allocator is activated by calling
15156 ** sqlite3_config().
15158 #ifdef SQLITE_ENABLE_MEMSYS3
15161 ** Maximum size (in Mem3Blocks) of a "small" chunk.
15163 #define MX_SMALL 10
15167 ** Number of freelist hash slots
15169 #define N_HASH 61
15172 ** A memory allocation (also called a "chunk") consists of two or
15173 ** more blocks where each block is 8 bytes. The first 8 bytes are
15174 ** a header that is not returned to the user.
15176 ** A chunk is two or more blocks that is either checked out or
15177 ** free. The first block has format u.hdr. u.hdr.size4x is 4 times the
15178 ** size of the allocation in blocks if the allocation is free.
15179 ** The u.hdr.size4x&1 bit is true if the chunk is checked out and
15180 ** false if the chunk is on the freelist. The u.hdr.size4x&2 bit
15181 ** is true if the previous chunk is checked out and false if the
15182 ** previous chunk is free. The u.hdr.prevSize field is the size of
15183 ** the previous chunk in blocks if the previous chunk is on the
15184 ** freelist. If the previous chunk is checked out, then
15185 ** u.hdr.prevSize can be part of the data for that chunk and should
15186 ** not be read or written.
15188 ** We often identify a chunk by its index in mem3.aPool[]. When
15189 ** this is done, the chunk index refers to the second block of
15190 ** the chunk. In this way, the first chunk has an index of 1.
15191 ** A chunk index of 0 means "no such chunk" and is the equivalent
15192 ** of a NULL pointer.
15194 ** The second block of free chunks is of the form u.list. The
15195 ** two fields form a double-linked list of chunks of related sizes.
15196 ** Pointers to the head of the list are stored in mem3.aiSmall[]
15197 ** for smaller chunks and mem3.aiHash[] for larger chunks.
15199 ** The second block of a chunk is user data if the chunk is checked
15200 ** out. If a chunk is checked out, the user data may extend into
15201 ** the u.hdr.prevSize value of the following chunk.
15203 typedef struct Mem3Block Mem3Block;
15204 struct Mem3Block {
15205 union {
15206 struct {
15207 u32 prevSize; /* Size of previous chunk in Mem3Block elements */
15208 u32 size4x; /* 4x the size of current chunk in Mem3Block elements */
15209 } hdr;
15210 struct {
15211 u32 next; /* Index in mem3.aPool[] of next free chunk */
15212 u32 prev; /* Index in mem3.aPool[] of previous free chunk */
15213 } list;
15214 } u;
15218 ** All of the static variables used by this module are collected
15219 ** into a single structure named "mem3". This is to keep the
15220 ** static variables organized and to reduce namespace pollution
15221 ** when this module is combined with other in the amalgamation.
15223 static SQLITE_WSD struct Mem3Global {
15225 ** Memory available for allocation. nPool is the size of the array
15226 ** (in Mem3Blocks) pointed to by aPool less 2.
15228 u32 nPool;
15229 Mem3Block *aPool;
15232 ** True if we are evaluating an out-of-memory callback.
15234 int alarmBusy;
15237 ** Mutex to control access to the memory allocation subsystem.
15239 sqlite3_mutex *mutex;
15242 ** The minimum amount of free space that we have seen.
15244 u32 mnMaster;
15247 ** iMaster is the index of the master chunk. Most new allocations
15248 ** occur off of this chunk. szMaster is the size (in Mem3Blocks)
15249 ** of the current master. iMaster is 0 if there is not master chunk.
15250 ** The master chunk is not in either the aiHash[] or aiSmall[].
15252 u32 iMaster;
15253 u32 szMaster;
15256 ** Array of lists of free blocks according to the block size
15257 ** for smaller chunks, or a hash on the block size for larger
15258 ** chunks.
15260 u32 aiSmall[MX_SMALL-1]; /* For sizes 2 through MX_SMALL, inclusive */
15261 u32 aiHash[N_HASH]; /* For sizes MX_SMALL+1 and larger */
15262 } mem3 = { 97535575 };
15264 #define mem3 GLOBAL(struct Mem3Global, mem3)
15267 ** Unlink the chunk at mem3.aPool[i] from list it is currently
15268 ** on. *pRoot is the list that i is a member of.
15270 static void memsys3UnlinkFromList(u32 i, u32 *pRoot){
15271 u32 next = mem3.aPool[i].u.list.next;
15272 u32 prev = mem3.aPool[i].u.list.prev;
15273 assert( sqlite3_mutex_held(mem3.mutex) );
15274 if( prev==0 ){
15275 *pRoot = next;
15276 }else{
15277 mem3.aPool[prev].u.list.next = next;
15279 if( next ){
15280 mem3.aPool[next].u.list.prev = prev;
15282 mem3.aPool[i].u.list.next = 0;
15283 mem3.aPool[i].u.list.prev = 0;
15287 ** Unlink the chunk at index i from
15288 ** whatever list is currently a member of.
15290 static void memsys3Unlink(u32 i){
15291 u32 size, hash;
15292 assert( sqlite3_mutex_held(mem3.mutex) );
15293 assert( (mem3.aPool[i-1].u.hdr.size4x & 1)==0 );
15294 assert( i>=1 );
15295 size = mem3.aPool[i-1].u.hdr.size4x/4;
15296 assert( size==mem3.aPool[i+size-1].u.hdr.prevSize );
15297 assert( size>=2 );
15298 if( size <= MX_SMALL ){
15299 memsys3UnlinkFromList(i, &mem3.aiSmall[size-2]);
15300 }else{
15301 hash = size % N_HASH;
15302 memsys3UnlinkFromList(i, &mem3.aiHash[hash]);
15307 ** Link the chunk at mem3.aPool[i] so that is on the list rooted
15308 ** at *pRoot.
15310 static void memsys3LinkIntoList(u32 i, u32 *pRoot){
15311 assert( sqlite3_mutex_held(mem3.mutex) );
15312 mem3.aPool[i].u.list.next = *pRoot;
15313 mem3.aPool[i].u.list.prev = 0;
15314 if( *pRoot ){
15315 mem3.aPool[*pRoot].u.list.prev = i;
15317 *pRoot = i;
15321 ** Link the chunk at index i into either the appropriate
15322 ** small chunk list, or into the large chunk hash table.
15324 static void memsys3Link(u32 i){
15325 u32 size, hash;
15326 assert( sqlite3_mutex_held(mem3.mutex) );
15327 assert( i>=1 );
15328 assert( (mem3.aPool[i-1].u.hdr.size4x & 1)==0 );
15329 size = mem3.aPool[i-1].u.hdr.size4x/4;
15330 assert( size==mem3.aPool[i+size-1].u.hdr.prevSize );
15331 assert( size>=2 );
15332 if( size <= MX_SMALL ){
15333 memsys3LinkIntoList(i, &mem3.aiSmall[size-2]);
15334 }else{
15335 hash = size % N_HASH;
15336 memsys3LinkIntoList(i, &mem3.aiHash[hash]);
15341 ** If the STATIC_MEM mutex is not already held, obtain it now. The mutex
15342 ** will already be held (obtained by code in malloc.c) if
15343 ** sqlite3GlobalConfig.bMemStat is true.
15345 static void memsys3Enter(void){
15346 if( sqlite3GlobalConfig.bMemstat==0 && mem3.mutex==0 ){
15347 mem3.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
15349 sqlite3_mutex_enter(mem3.mutex);
15351 static void memsys3Leave(void){
15352 sqlite3_mutex_leave(mem3.mutex);
15356 ** Called when we are unable to satisfy an allocation of nBytes.
15358 static void memsys3OutOfMemory(int nByte){
15359 if( !mem3.alarmBusy ){
15360 mem3.alarmBusy = 1;
15361 assert( sqlite3_mutex_held(mem3.mutex) );
15362 sqlite3_mutex_leave(mem3.mutex);
15363 sqlite3_release_memory(nByte);
15364 sqlite3_mutex_enter(mem3.mutex);
15365 mem3.alarmBusy = 0;
15371 ** Chunk i is a free chunk that has been unlinked. Adjust its
15372 ** size parameters for check-out and return a pointer to the
15373 ** user portion of the chunk.
15375 static void *memsys3Checkout(u32 i, u32 nBlock){
15376 u32 x;
15377 assert( sqlite3_mutex_held(mem3.mutex) );
15378 assert( i>=1 );
15379 assert( mem3.aPool[i-1].u.hdr.size4x/4==nBlock );
15380 assert( mem3.aPool[i+nBlock-1].u.hdr.prevSize==nBlock );
15381 x = mem3.aPool[i-1].u.hdr.size4x;
15382 mem3.aPool[i-1].u.hdr.size4x = nBlock*4 | 1 | (x&2);
15383 mem3.aPool[i+nBlock-1].u.hdr.prevSize = nBlock;
15384 mem3.aPool[i+nBlock-1].u.hdr.size4x |= 2;
15385 return &mem3.aPool[i];
15389 ** Carve a piece off of the end of the mem3.iMaster free chunk.
15390 ** Return a pointer to the new allocation. Or, if the master chunk
15391 ** is not large enough, return 0.
15393 static void *memsys3FromMaster(u32 nBlock){
15394 assert( sqlite3_mutex_held(mem3.mutex) );
15395 assert( mem3.szMaster>=nBlock );
15396 if( nBlock>=mem3.szMaster-1 ){
15397 /* Use the entire master */
15398 void *p = memsys3Checkout(mem3.iMaster, mem3.szMaster);
15399 mem3.iMaster = 0;
15400 mem3.szMaster = 0;
15401 mem3.mnMaster = 0;
15402 return p;
15403 }else{
15404 /* Split the master block. Return the tail. */
15405 u32 newi, x;
15406 newi = mem3.iMaster + mem3.szMaster - nBlock;
15407 assert( newi > mem3.iMaster+1 );
15408 mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.prevSize = nBlock;
15409 mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.size4x |= 2;
15410 mem3.aPool[newi-1].u.hdr.size4x = nBlock*4 + 1;
15411 mem3.szMaster -= nBlock;
15412 mem3.aPool[newi-1].u.hdr.prevSize = mem3.szMaster;
15413 x = mem3.aPool[mem3.iMaster-1].u.hdr.size4x & 2;
15414 mem3.aPool[mem3.iMaster-1].u.hdr.size4x = mem3.szMaster*4 | x;
15415 if( mem3.szMaster < mem3.mnMaster ){
15416 mem3.mnMaster = mem3.szMaster;
15418 return (void*)&mem3.aPool[newi];
15423 ** *pRoot is the head of a list of free chunks of the same size
15424 ** or same size hash. In other words, *pRoot is an entry in either
15425 ** mem3.aiSmall[] or mem3.aiHash[].
15427 ** This routine examines all entries on the given list and tries
15428 ** to coalesce each entries with adjacent free chunks.
15430 ** If it sees a chunk that is larger than mem3.iMaster, it replaces
15431 ** the current mem3.iMaster with the new larger chunk. In order for
15432 ** this mem3.iMaster replacement to work, the master chunk must be
15433 ** linked into the hash tables. That is not the normal state of
15434 ** affairs, of course. The calling routine must link the master
15435 ** chunk before invoking this routine, then must unlink the (possibly
15436 ** changed) master chunk once this routine has finished.
15438 static void memsys3Merge(u32 *pRoot){
15439 u32 iNext, prev, size, i, x;
15441 assert( sqlite3_mutex_held(mem3.mutex) );
15442 for(i=*pRoot; i>0; i=iNext){
15443 iNext = mem3.aPool[i].u.list.next;
15444 size = mem3.aPool[i-1].u.hdr.size4x;
15445 assert( (size&1)==0 );
15446 if( (size&2)==0 ){
15447 memsys3UnlinkFromList(i, pRoot);
15448 assert( i > mem3.aPool[i-1].u.hdr.prevSize );
15449 prev = i - mem3.aPool[i-1].u.hdr.prevSize;
15450 if( prev==iNext ){
15451 iNext = mem3.aPool[prev].u.list.next;
15453 memsys3Unlink(prev);
15454 size = i + size/4 - prev;
15455 x = mem3.aPool[prev-1].u.hdr.size4x & 2;
15456 mem3.aPool[prev-1].u.hdr.size4x = size*4 | x;
15457 mem3.aPool[prev+size-1].u.hdr.prevSize = size;
15458 memsys3Link(prev);
15459 i = prev;
15460 }else{
15461 size /= 4;
15463 if( size>mem3.szMaster ){
15464 mem3.iMaster = i;
15465 mem3.szMaster = size;
15471 ** Return a block of memory of at least nBytes in size.
15472 ** Return NULL if unable.
15474 ** This function assumes that the necessary mutexes, if any, are
15475 ** already held by the caller. Hence "Unsafe".
15477 static void *memsys3MallocUnsafe(int nByte){
15478 u32 i;
15479 u32 nBlock;
15480 u32 toFree;
15482 assert( sqlite3_mutex_held(mem3.mutex) );
15483 assert( sizeof(Mem3Block)==8 );
15484 if( nByte<=12 ){
15485 nBlock = 2;
15486 }else{
15487 nBlock = (nByte + 11)/8;
15489 assert( nBlock>=2 );
15491 /* STEP 1:
15492 ** Look for an entry of the correct size in either the small
15493 ** chunk table or in the large chunk hash table. This is
15494 ** successful most of the time (about 9 times out of 10).
15496 if( nBlock <= MX_SMALL ){
15497 i = mem3.aiSmall[nBlock-2];
15498 if( i>0 ){
15499 memsys3UnlinkFromList(i, &mem3.aiSmall[nBlock-2]);
15500 return memsys3Checkout(i, nBlock);
15502 }else{
15503 int hash = nBlock % N_HASH;
15504 for(i=mem3.aiHash[hash]; i>0; i=mem3.aPool[i].u.list.next){
15505 if( mem3.aPool[i-1].u.hdr.size4x/4==nBlock ){
15506 memsys3UnlinkFromList(i, &mem3.aiHash[hash]);
15507 return memsys3Checkout(i, nBlock);
15512 /* STEP 2:
15513 ** Try to satisfy the allocation by carving a piece off of the end
15514 ** of the master chunk. This step usually works if step 1 fails.
15516 if( mem3.szMaster>=nBlock ){
15517 return memsys3FromMaster(nBlock);
15521 /* STEP 3:
15522 ** Loop through the entire memory pool. Coalesce adjacent free
15523 ** chunks. Recompute the master chunk as the largest free chunk.
15524 ** Then try again to satisfy the allocation by carving a piece off
15525 ** of the end of the master chunk. This step happens very
15526 ** rarely (we hope!)
15528 for(toFree=nBlock*16; toFree<(mem3.nPool*16); toFree *= 2){
15529 memsys3OutOfMemory(toFree);
15530 if( mem3.iMaster ){
15531 memsys3Link(mem3.iMaster);
15532 mem3.iMaster = 0;
15533 mem3.szMaster = 0;
15535 for(i=0; i<N_HASH; i++){
15536 memsys3Merge(&mem3.aiHash[i]);
15538 for(i=0; i<MX_SMALL-1; i++){
15539 memsys3Merge(&mem3.aiSmall[i]);
15541 if( mem3.szMaster ){
15542 memsys3Unlink(mem3.iMaster);
15543 if( mem3.szMaster>=nBlock ){
15544 return memsys3FromMaster(nBlock);
15549 /* If none of the above worked, then we fail. */
15550 return 0;
15554 ** Free an outstanding memory allocation.
15556 ** This function assumes that the necessary mutexes, if any, are
15557 ** already held by the caller. Hence "Unsafe".
15559 void memsys3FreeUnsafe(void *pOld){
15560 Mem3Block *p = (Mem3Block*)pOld;
15561 int i;
15562 u32 size, x;
15563 assert( sqlite3_mutex_held(mem3.mutex) );
15564 assert( p>mem3.aPool && p<&mem3.aPool[mem3.nPool] );
15565 i = p - mem3.aPool;
15566 assert( (mem3.aPool[i-1].u.hdr.size4x&1)==1 );
15567 size = mem3.aPool[i-1].u.hdr.size4x/4;
15568 assert( i+size<=mem3.nPool+1 );
15569 mem3.aPool[i-1].u.hdr.size4x &= ~1;
15570 mem3.aPool[i+size-1].u.hdr.prevSize = size;
15571 mem3.aPool[i+size-1].u.hdr.size4x &= ~2;
15572 memsys3Link(i);
15574 /* Try to expand the master using the newly freed chunk */
15575 if( mem3.iMaster ){
15576 while( (mem3.aPool[mem3.iMaster-1].u.hdr.size4x&2)==0 ){
15577 size = mem3.aPool[mem3.iMaster-1].u.hdr.prevSize;
15578 mem3.iMaster -= size;
15579 mem3.szMaster += size;
15580 memsys3Unlink(mem3.iMaster);
15581 x = mem3.aPool[mem3.iMaster-1].u.hdr.size4x & 2;
15582 mem3.aPool[mem3.iMaster-1].u.hdr.size4x = mem3.szMaster*4 | x;
15583 mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.prevSize = mem3.szMaster;
15585 x = mem3.aPool[mem3.iMaster-1].u.hdr.size4x & 2;
15586 while( (mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.size4x&1)==0 ){
15587 memsys3Unlink(mem3.iMaster+mem3.szMaster);
15588 mem3.szMaster += mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.size4x/4;
15589 mem3.aPool[mem3.iMaster-1].u.hdr.size4x = mem3.szMaster*4 | x;
15590 mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.prevSize = mem3.szMaster;
15596 ** Return the size of an outstanding allocation, in bytes. The
15597 ** size returned omits the 8-byte header overhead. This only
15598 ** works for chunks that are currently checked out.
15600 static int memsys3Size(void *p){
15601 Mem3Block *pBlock;
15602 if( p==0 ) return 0;
15603 pBlock = (Mem3Block*)p;
15604 assert( (pBlock[-1].u.hdr.size4x&1)!=0 );
15605 return (pBlock[-1].u.hdr.size4x&~3)*2 - 4;
15609 ** Round up a request size to the next valid allocation size.
15611 static int memsys3Roundup(int n){
15612 if( n<=12 ){
15613 return 12;
15614 }else{
15615 return ((n+11)&~7) - 4;
15620 ** Allocate nBytes of memory.
15622 static void *memsys3Malloc(int nBytes){
15623 sqlite3_int64 *p;
15624 assert( nBytes>0 ); /* malloc.c filters out 0 byte requests */
15625 memsys3Enter();
15626 p = memsys3MallocUnsafe(nBytes);
15627 memsys3Leave();
15628 return (void*)p;
15632 ** Free memory.
15634 void memsys3Free(void *pPrior){
15635 assert( pPrior );
15636 memsys3Enter();
15637 memsys3FreeUnsafe(pPrior);
15638 memsys3Leave();
15642 ** Change the size of an existing memory allocation
15644 void *memsys3Realloc(void *pPrior, int nBytes){
15645 int nOld;
15646 void *p;
15647 if( pPrior==0 ){
15648 return sqlite3_malloc(nBytes);
15650 if( nBytes<=0 ){
15651 sqlite3_free(pPrior);
15652 return 0;
15654 nOld = memsys3Size(pPrior);
15655 if( nBytes<=nOld && nBytes>=nOld-128 ){
15656 return pPrior;
15658 memsys3Enter();
15659 p = memsys3MallocUnsafe(nBytes);
15660 if( p ){
15661 if( nOld<nBytes ){
15662 memcpy(p, pPrior, nOld);
15663 }else{
15664 memcpy(p, pPrior, nBytes);
15666 memsys3FreeUnsafe(pPrior);
15668 memsys3Leave();
15669 return p;
15673 ** Initialize this module.
15675 static int memsys3Init(void *NotUsed){
15676 UNUSED_PARAMETER(NotUsed);
15677 if( !sqlite3GlobalConfig.pHeap ){
15678 return SQLITE_ERROR;
15681 /* Store a pointer to the memory block in global structure mem3. */
15682 assert( sizeof(Mem3Block)==8 );
15683 mem3.aPool = (Mem3Block *)sqlite3GlobalConfig.pHeap;
15684 mem3.nPool = (sqlite3GlobalConfig.nHeap / sizeof(Mem3Block)) - 2;
15686 /* Initialize the master block. */
15687 mem3.szMaster = mem3.nPool;
15688 mem3.mnMaster = mem3.szMaster;
15689 mem3.iMaster = 1;
15690 mem3.aPool[0].u.hdr.size4x = (mem3.szMaster<<2) + 2;
15691 mem3.aPool[mem3.nPool].u.hdr.prevSize = mem3.nPool;
15692 mem3.aPool[mem3.nPool].u.hdr.size4x = 1;
15694 return SQLITE_OK;
15698 ** Deinitialize this module.
15700 static void memsys3Shutdown(void *NotUsed){
15701 UNUSED_PARAMETER(NotUsed);
15702 mem3.mutex = 0;
15703 return;
15709 ** Open the file indicated and write a log of all unfreed memory
15710 ** allocations into that log.
15712 SQLITE_PRIVATE void sqlite3Memsys3Dump(const char *zFilename){
15713 #ifdef SQLITE_DEBUG
15714 FILE *out;
15715 u32 i, j;
15716 u32 size;
15717 if( zFilename==0 || zFilename[0]==0 ){
15718 out = stdout;
15719 }else{
15720 out = fopen(zFilename, "w");
15721 if( out==0 ){
15722 fprintf(stderr, "** Unable to output memory debug output log: %s **\n",
15723 zFilename);
15724 return;
15727 memsys3Enter();
15728 fprintf(out, "CHUNKS:\n");
15729 for(i=1; i<=mem3.nPool; i+=size/4){
15730 size = mem3.aPool[i-1].u.hdr.size4x;
15731 if( size/4<=1 ){
15732 fprintf(out, "%p size error\n", &mem3.aPool[i]);
15733 assert( 0 );
15734 break;
15736 if( (size&1)==0 && mem3.aPool[i+size/4-1].u.hdr.prevSize!=size/4 ){
15737 fprintf(out, "%p tail size does not match\n", &mem3.aPool[i]);
15738 assert( 0 );
15739 break;
15741 if( ((mem3.aPool[i+size/4-1].u.hdr.size4x&2)>>1)!=(size&1) ){
15742 fprintf(out, "%p tail checkout bit is incorrect\n", &mem3.aPool[i]);
15743 assert( 0 );
15744 break;
15746 if( size&1 ){
15747 fprintf(out, "%p %6d bytes checked out\n", &mem3.aPool[i], (size/4)*8-8);
15748 }else{
15749 fprintf(out, "%p %6d bytes free%s\n", &mem3.aPool[i], (size/4)*8-8,
15750 i==mem3.iMaster ? " **master**" : "");
15753 for(i=0; i<MX_SMALL-1; i++){
15754 if( mem3.aiSmall[i]==0 ) continue;
15755 fprintf(out, "small(%2d):", i);
15756 for(j = mem3.aiSmall[i]; j>0; j=mem3.aPool[j].u.list.next){
15757 fprintf(out, " %p(%d)", &mem3.aPool[j],
15758 (mem3.aPool[j-1].u.hdr.size4x/4)*8-8);
15760 fprintf(out, "\n");
15762 for(i=0; i<N_HASH; i++){
15763 if( mem3.aiHash[i]==0 ) continue;
15764 fprintf(out, "hash(%2d):", i);
15765 for(j = mem3.aiHash[i]; j>0; j=mem3.aPool[j].u.list.next){
15766 fprintf(out, " %p(%d)", &mem3.aPool[j],
15767 (mem3.aPool[j-1].u.hdr.size4x/4)*8-8);
15769 fprintf(out, "\n");
15771 fprintf(out, "master=%d\n", mem3.iMaster);
15772 fprintf(out, "nowUsed=%d\n", mem3.nPool*8 - mem3.szMaster*8);
15773 fprintf(out, "mxUsed=%d\n", mem3.nPool*8 - mem3.mnMaster*8);
15774 sqlite3_mutex_leave(mem3.mutex);
15775 if( out==stdout ){
15776 fflush(stdout);
15777 }else{
15778 fclose(out);
15780 #else
15781 UNUSED_PARAMETER(zFilename);
15782 #endif
15786 ** This routine is the only routine in this file with external
15787 ** linkage.
15789 ** Populate the low-level memory allocation function pointers in
15790 ** sqlite3GlobalConfig.m with pointers to the routines in this file. The
15791 ** arguments specify the block of memory to manage.
15793 ** This routine is only called by sqlite3_config(), and therefore
15794 ** is not required to be threadsafe (it is not).
15796 SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys3(void){
15797 static const sqlite3_mem_methods mempoolMethods = {
15798 memsys3Malloc,
15799 memsys3Free,
15800 memsys3Realloc,
15801 memsys3Size,
15802 memsys3Roundup,
15803 memsys3Init,
15804 memsys3Shutdown,
15807 return &mempoolMethods;
15810 #endif /* SQLITE_ENABLE_MEMSYS3 */
15812 /************** End of mem3.c ************************************************/
15813 /************** Begin file mem5.c ********************************************/
15815 ** 2007 October 14
15817 ** The author disclaims copyright to this source code. In place of
15818 ** a legal notice, here is a blessing:
15820 ** May you do good and not evil.
15821 ** May you find forgiveness for yourself and forgive others.
15822 ** May you share freely, never taking more than you give.
15824 *************************************************************************
15825 ** This file contains the C functions that implement a memory
15826 ** allocation subsystem for use by SQLite.
15828 ** This version of the memory allocation subsystem omits all
15829 ** use of malloc(). The application gives SQLite a block of memory
15830 ** before calling sqlite3_initialize() from which allocations
15831 ** are made and returned by the xMalloc() and xRealloc()
15832 ** implementations. Once sqlite3_initialize() has been called,
15833 ** the amount of memory available to SQLite is fixed and cannot
15834 ** be changed.
15836 ** This version of the memory allocation subsystem is included
15837 ** in the build only if SQLITE_ENABLE_MEMSYS5 is defined.
15839 ** This memory allocator uses the following algorithm:
15841 ** 1. All memory allocations sizes are rounded up to a power of 2.
15843 ** 2. If two adjacent free blocks are the halves of a larger block,
15844 ** then the two blocks are coalesed into the single larger block.
15846 ** 3. New memory is allocated from the first available free block.
15848 ** This algorithm is described in: J. M. Robson. "Bounds for Some Functions
15849 ** Concerning Dynamic Storage Allocation". Journal of the Association for
15850 ** Computing Machinery, Volume 21, Number 8, July 1974, pages 491-499.
15852 ** Let n be the size of the largest allocation divided by the minimum
15853 ** allocation size (after rounding all sizes up to a power of 2.) Let M
15854 ** be the maximum amount of memory ever outstanding at one time. Let
15855 ** N be the total amount of memory available for allocation. Robson
15856 ** proved that this memory allocator will never breakdown due to
15857 ** fragmentation as long as the following constraint holds:
15859 ** N >= M*(1 + log2(n)/2) - n + 1
15861 ** The sqlite3_status() logic tracks the maximum values of n and M so
15862 ** that an application can, at any time, verify this constraint.
15866 ** This version of the memory allocator is used only when
15867 ** SQLITE_ENABLE_MEMSYS5 is defined.
15869 #ifdef SQLITE_ENABLE_MEMSYS5
15872 ** A minimum allocation is an instance of the following structure.
15873 ** Larger allocations are an array of these structures where the
15874 ** size of the array is a power of 2.
15876 ** The size of this object must be a power of two. That fact is
15877 ** verified in memsys5Init().
15879 typedef struct Mem5Link Mem5Link;
15880 struct Mem5Link {
15881 int next; /* Index of next free chunk */
15882 int prev; /* Index of previous free chunk */
15886 ** Maximum size of any allocation is ((1<<LOGMAX)*mem5.szAtom). Since
15887 ** mem5.szAtom is always at least 8 and 32-bit integers are used,
15888 ** it is not actually possible to reach this limit.
15890 #define LOGMAX 30
15893 ** Masks used for mem5.aCtrl[] elements.
15895 #define CTRL_LOGSIZE 0x1f /* Log2 Size of this block */
15896 #define CTRL_FREE 0x20 /* True if not checked out */
15899 ** All of the static variables used by this module are collected
15900 ** into a single structure named "mem5". This is to keep the
15901 ** static variables organized and to reduce namespace pollution
15902 ** when this module is combined with other in the amalgamation.
15904 static SQLITE_WSD struct Mem5Global {
15906 ** Memory available for allocation
15908 int szAtom; /* Smallest possible allocation in bytes */
15909 int nBlock; /* Number of szAtom sized blocks in zPool */
15910 u8 *zPool; /* Memory available to be allocated */
15913 ** Mutex to control access to the memory allocation subsystem.
15915 sqlite3_mutex *mutex;
15918 ** Performance statistics
15920 u64 nAlloc; /* Total number of calls to malloc */
15921 u64 totalAlloc; /* Total of all malloc calls - includes internal frag */
15922 u64 totalExcess; /* Total internal fragmentation */
15923 u32 currentOut; /* Current checkout, including internal fragmentation */
15924 u32 currentCount; /* Current number of distinct checkouts */
15925 u32 maxOut; /* Maximum instantaneous currentOut */
15926 u32 maxCount; /* Maximum instantaneous currentCount */
15927 u32 maxRequest; /* Largest allocation (exclusive of internal frag) */
15930 ** Lists of free blocks. aiFreelist[0] is a list of free blocks of
15931 ** size mem5.szAtom. aiFreelist[1] holds blocks of size szAtom*2.
15932 ** and so forth.
15934 int aiFreelist[LOGMAX+1];
15937 ** Space for tracking which blocks are checked out and the size
15938 ** of each block. One byte per block.
15940 u8 *aCtrl;
15942 } mem5;
15945 ** Access the static variable through a macro for SQLITE_OMIT_WSD
15947 #define mem5 GLOBAL(struct Mem5Global, mem5)
15950 ** Assuming mem5.zPool is divided up into an array of Mem5Link
15951 ** structures, return a pointer to the idx-th such lik.
15953 #define MEM5LINK(idx) ((Mem5Link *)(&mem5.zPool[(idx)*mem5.szAtom]))
15956 ** Unlink the chunk at mem5.aPool[i] from list it is currently
15957 ** on. It should be found on mem5.aiFreelist[iLogsize].
15959 static void memsys5Unlink(int i, int iLogsize){
15960 int next, prev;
15961 assert( i>=0 && i<mem5.nBlock );
15962 assert( iLogsize>=0 && iLogsize<=LOGMAX );
15963 assert( (mem5.aCtrl[i] & CTRL_LOGSIZE)==iLogsize );
15965 next = MEM5LINK(i)->next;
15966 prev = MEM5LINK(i)->prev;
15967 if( prev<0 ){
15968 mem5.aiFreelist[iLogsize] = next;
15969 }else{
15970 MEM5LINK(prev)->next = next;
15972 if( next>=0 ){
15973 MEM5LINK(next)->prev = prev;
15978 ** Link the chunk at mem5.aPool[i] so that is on the iLogsize
15979 ** free list.
15981 static void memsys5Link(int i, int iLogsize){
15982 int x;
15983 assert( sqlite3_mutex_held(mem5.mutex) );
15984 assert( i>=0 && i<mem5.nBlock );
15985 assert( iLogsize>=0 && iLogsize<=LOGMAX );
15986 assert( (mem5.aCtrl[i] & CTRL_LOGSIZE)==iLogsize );
15988 x = MEM5LINK(i)->next = mem5.aiFreelist[iLogsize];
15989 MEM5LINK(i)->prev = -1;
15990 if( x>=0 ){
15991 assert( x<mem5.nBlock );
15992 MEM5LINK(x)->prev = i;
15994 mem5.aiFreelist[iLogsize] = i;
15998 ** If the STATIC_MEM mutex is not already held, obtain it now. The mutex
15999 ** will already be held (obtained by code in malloc.c) if
16000 ** sqlite3GlobalConfig.bMemStat is true.
16002 static void memsys5Enter(void){
16003 sqlite3_mutex_enter(mem5.mutex);
16005 static void memsys5Leave(void){
16006 sqlite3_mutex_leave(mem5.mutex);
16010 ** Return the size of an outstanding allocation, in bytes. The
16011 ** size returned omits the 8-byte header overhead. This only
16012 ** works for chunks that are currently checked out.
16014 static int memsys5Size(void *p){
16015 int iSize = 0;
16016 if( p ){
16017 int i = ((u8 *)p-mem5.zPool)/mem5.szAtom;
16018 assert( i>=0 && i<mem5.nBlock );
16019 iSize = mem5.szAtom * (1 << (mem5.aCtrl[i]&CTRL_LOGSIZE));
16021 return iSize;
16025 ** Find the first entry on the freelist iLogsize. Unlink that
16026 ** entry and return its index.
16028 static int memsys5UnlinkFirst(int iLogsize){
16029 int i;
16030 int iFirst;
16032 assert( iLogsize>=0 && iLogsize<=LOGMAX );
16033 i = iFirst = mem5.aiFreelist[iLogsize];
16034 assert( iFirst>=0 );
16035 while( i>0 ){
16036 if( i<iFirst ) iFirst = i;
16037 i = MEM5LINK(i)->next;
16039 memsys5Unlink(iFirst, iLogsize);
16040 return iFirst;
16044 ** Return a block of memory of at least nBytes in size.
16045 ** Return NULL if unable. Return NULL if nBytes==0.
16047 ** The caller guarantees that nByte positive.
16049 ** The caller has obtained a mutex prior to invoking this
16050 ** routine so there is never any chance that two or more
16051 ** threads can be in this routine at the same time.
16053 static void *memsys5MallocUnsafe(int nByte){
16054 int i; /* Index of a mem5.aPool[] slot */
16055 int iBin; /* Index into mem5.aiFreelist[] */
16056 int iFullSz; /* Size of allocation rounded up to power of 2 */
16057 int iLogsize; /* Log2 of iFullSz/POW2_MIN */
16059 /* nByte must be a positive */
16060 assert( nByte>0 );
16062 /* Keep track of the maximum allocation request. Even unfulfilled
16063 ** requests are counted */
16064 if( (u32)nByte>mem5.maxRequest ){
16065 mem5.maxRequest = nByte;
16068 /* Abort if the requested allocation size is larger than the largest
16069 ** power of two that we can represent using 32-bit signed integers.
16071 if( nByte > 0x40000000 ){
16072 return 0;
16075 /* Round nByte up to the next valid power of two */
16076 for(iFullSz=mem5.szAtom, iLogsize=0; iFullSz<nByte; iFullSz *= 2, iLogsize++){}
16078 /* Make sure mem5.aiFreelist[iLogsize] contains at least one free
16079 ** block. If not, then split a block of the next larger power of
16080 ** two in order to create a new free block of size iLogsize.
16082 for(iBin=iLogsize; mem5.aiFreelist[iBin]<0 && iBin<=LOGMAX; iBin++){}
16083 if( iBin>LOGMAX ){
16084 testcase( sqlite3GlobalConfig.xLog!=0 );
16085 sqlite3_log(SQLITE_NOMEM, "failed to allocate %u bytes", nByte);
16086 return 0;
16088 i = memsys5UnlinkFirst(iBin);
16089 while( iBin>iLogsize ){
16090 int newSize;
16092 iBin--;
16093 newSize = 1 << iBin;
16094 mem5.aCtrl[i+newSize] = CTRL_FREE | iBin;
16095 memsys5Link(i+newSize, iBin);
16097 mem5.aCtrl[i] = iLogsize;
16099 /* Update allocator performance statistics. */
16100 mem5.nAlloc++;
16101 mem5.totalAlloc += iFullSz;
16102 mem5.totalExcess += iFullSz - nByte;
16103 mem5.currentCount++;
16104 mem5.currentOut += iFullSz;
16105 if( mem5.maxCount<mem5.currentCount ) mem5.maxCount = mem5.currentCount;
16106 if( mem5.maxOut<mem5.currentOut ) mem5.maxOut = mem5.currentOut;
16108 /* Return a pointer to the allocated memory. */
16109 return (void*)&mem5.zPool[i*mem5.szAtom];
16113 ** Free an outstanding memory allocation.
16115 static void memsys5FreeUnsafe(void *pOld){
16116 u32 size, iLogsize;
16117 int iBlock;
16119 /* Set iBlock to the index of the block pointed to by pOld in
16120 ** the array of mem5.szAtom byte blocks pointed to by mem5.zPool.
16122 iBlock = ((u8 *)pOld-mem5.zPool)/mem5.szAtom;
16124 /* Check that the pointer pOld points to a valid, non-free block. */
16125 assert( iBlock>=0 && iBlock<mem5.nBlock );
16126 assert( ((u8 *)pOld-mem5.zPool)%mem5.szAtom==0 );
16127 assert( (mem5.aCtrl[iBlock] & CTRL_FREE)==0 );
16129 iLogsize = mem5.aCtrl[iBlock] & CTRL_LOGSIZE;
16130 size = 1<<iLogsize;
16131 assert( iBlock+size-1<(u32)mem5.nBlock );
16133 mem5.aCtrl[iBlock] |= CTRL_FREE;
16134 mem5.aCtrl[iBlock+size-1] |= CTRL_FREE;
16135 assert( mem5.currentCount>0 );
16136 assert( mem5.currentOut>=(size*mem5.szAtom) );
16137 mem5.currentCount--;
16138 mem5.currentOut -= size*mem5.szAtom;
16139 assert( mem5.currentOut>0 || mem5.currentCount==0 );
16140 assert( mem5.currentCount>0 || mem5.currentOut==0 );
16142 mem5.aCtrl[iBlock] = CTRL_FREE | iLogsize;
16143 while( ALWAYS(iLogsize<LOGMAX) ){
16144 int iBuddy;
16145 if( (iBlock>>iLogsize) & 1 ){
16146 iBuddy = iBlock - size;
16147 }else{
16148 iBuddy = iBlock + size;
16150 assert( iBuddy>=0 );
16151 if( (iBuddy+(1<<iLogsize))>mem5.nBlock ) break;
16152 if( mem5.aCtrl[iBuddy]!=(CTRL_FREE | iLogsize) ) break;
16153 memsys5Unlink(iBuddy, iLogsize);
16154 iLogsize++;
16155 if( iBuddy<iBlock ){
16156 mem5.aCtrl[iBuddy] = CTRL_FREE | iLogsize;
16157 mem5.aCtrl[iBlock] = 0;
16158 iBlock = iBuddy;
16159 }else{
16160 mem5.aCtrl[iBlock] = CTRL_FREE | iLogsize;
16161 mem5.aCtrl[iBuddy] = 0;
16163 size *= 2;
16165 memsys5Link(iBlock, iLogsize);
16169 ** Allocate nBytes of memory
16171 static void *memsys5Malloc(int nBytes){
16172 sqlite3_int64 *p = 0;
16173 if( nBytes>0 ){
16174 memsys5Enter();
16175 p = memsys5MallocUnsafe(nBytes);
16176 memsys5Leave();
16178 return (void*)p;
16182 ** Free memory.
16184 ** The outer layer memory allocator prevents this routine from
16185 ** being called with pPrior==0.
16187 static void memsys5Free(void *pPrior){
16188 assert( pPrior!=0 );
16189 memsys5Enter();
16190 memsys5FreeUnsafe(pPrior);
16191 memsys5Leave();
16195 ** Change the size of an existing memory allocation.
16197 ** The outer layer memory allocator prevents this routine from
16198 ** being called with pPrior==0.
16200 ** nBytes is always a value obtained from a prior call to
16201 ** memsys5Round(). Hence nBytes is always a non-negative power
16202 ** of two. If nBytes==0 that means that an oversize allocation
16203 ** (an allocation larger than 0x40000000) was requested and this
16204 ** routine should return 0 without freeing pPrior.
16206 static void *memsys5Realloc(void *pPrior, int nBytes){
16207 int nOld;
16208 void *p;
16209 assert( pPrior!=0 );
16210 assert( (nBytes&(nBytes-1))==0 ); /* EV: R-46199-30249 */
16211 assert( nBytes>=0 );
16212 if( nBytes==0 ){
16213 return 0;
16215 nOld = memsys5Size(pPrior);
16216 if( nBytes<=nOld ){
16217 return pPrior;
16219 memsys5Enter();
16220 p = memsys5MallocUnsafe(nBytes);
16221 if( p ){
16222 memcpy(p, pPrior, nOld);
16223 memsys5FreeUnsafe(pPrior);
16225 memsys5Leave();
16226 return p;
16230 ** Round up a request size to the next valid allocation size. If
16231 ** the allocation is too large to be handled by this allocation system,
16232 ** return 0.
16234 ** All allocations must be a power of two and must be expressed by a
16235 ** 32-bit signed integer. Hence the largest allocation is 0x40000000
16236 ** or 1073741824 bytes.
16238 static int memsys5Roundup(int n){
16239 int iFullSz;
16240 if( n > 0x40000000 ) return 0;
16241 for(iFullSz=mem5.szAtom; iFullSz<n; iFullSz *= 2);
16242 return iFullSz;
16246 ** Return the ceiling of the logarithm base 2 of iValue.
16248 ** Examples: memsys5Log(1) -> 0
16249 ** memsys5Log(2) -> 1
16250 ** memsys5Log(4) -> 2
16251 ** memsys5Log(5) -> 3
16252 ** memsys5Log(8) -> 3
16253 ** memsys5Log(9) -> 4
16255 static int memsys5Log(int iValue){
16256 int iLog;
16257 for(iLog=0; (iLog<(int)((sizeof(int)*8)-1)) && (1<<iLog)<iValue; iLog++);
16258 return iLog;
16262 ** Initialize the memory allocator.
16264 ** This routine is not threadsafe. The caller must be holding a mutex
16265 ** to prevent multiple threads from entering at the same time.
16267 static int memsys5Init(void *NotUsed){
16268 int ii; /* Loop counter */
16269 int nByte; /* Number of bytes of memory available to this allocator */
16270 u8 *zByte; /* Memory usable by this allocator */
16271 int nMinLog; /* Log base 2 of minimum allocation size in bytes */
16272 int iOffset; /* An offset into mem5.aCtrl[] */
16274 UNUSED_PARAMETER(NotUsed);
16276 /* For the purposes of this routine, disable the mutex */
16277 mem5.mutex = 0;
16279 /* The size of a Mem5Link object must be a power of two. Verify that
16280 ** this is case.
16282 assert( (sizeof(Mem5Link)&(sizeof(Mem5Link)-1))==0 );
16284 nByte = sqlite3GlobalConfig.nHeap;
16285 zByte = (u8*)sqlite3GlobalConfig.pHeap;
16286 assert( zByte!=0 ); /* sqlite3_config() does not allow otherwise */
16288 /* boundaries on sqlite3GlobalConfig.mnReq are enforced in sqlite3_config() */
16289 nMinLog = memsys5Log(sqlite3GlobalConfig.mnReq);
16290 mem5.szAtom = (1<<nMinLog);
16291 while( (int)sizeof(Mem5Link)>mem5.szAtom ){
16292 mem5.szAtom = mem5.szAtom << 1;
16295 mem5.nBlock = (nByte / (mem5.szAtom+sizeof(u8)));
16296 mem5.zPool = zByte;
16297 mem5.aCtrl = (u8 *)&mem5.zPool[mem5.nBlock*mem5.szAtom];
16299 for(ii=0; ii<=LOGMAX; ii++){
16300 mem5.aiFreelist[ii] = -1;
16303 iOffset = 0;
16304 for(ii=LOGMAX; ii>=0; ii--){
16305 int nAlloc = (1<<ii);
16306 if( (iOffset+nAlloc)<=mem5.nBlock ){
16307 mem5.aCtrl[iOffset] = ii | CTRL_FREE;
16308 memsys5Link(iOffset, ii);
16309 iOffset += nAlloc;
16311 assert((iOffset+nAlloc)>mem5.nBlock);
16314 /* If a mutex is required for normal operation, allocate one */
16315 if( sqlite3GlobalConfig.bMemstat==0 ){
16316 mem5.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
16319 return SQLITE_OK;
16323 ** Deinitialize this module.
16325 static void memsys5Shutdown(void *NotUsed){
16326 UNUSED_PARAMETER(NotUsed);
16327 mem5.mutex = 0;
16328 return;
16331 #ifdef SQLITE_TEST
16333 ** Open the file indicated and write a log of all unfreed memory
16334 ** allocations into that log.
16336 SQLITE_PRIVATE void sqlite3Memsys5Dump(const char *zFilename){
16337 FILE *out;
16338 int i, j, n;
16339 int nMinLog;
16341 if( zFilename==0 || zFilename[0]==0 ){
16342 out = stdout;
16343 }else{
16344 out = fopen(zFilename, "w");
16345 if( out==0 ){
16346 fprintf(stderr, "** Unable to output memory debug output log: %s **\n",
16347 zFilename);
16348 return;
16351 memsys5Enter();
16352 nMinLog = memsys5Log(mem5.szAtom);
16353 for(i=0; i<=LOGMAX && i+nMinLog<32; i++){
16354 for(n=0, j=mem5.aiFreelist[i]; j>=0; j = MEM5LINK(j)->next, n++){}
16355 fprintf(out, "freelist items of size %d: %d\n", mem5.szAtom << i, n);
16357 fprintf(out, "mem5.nAlloc = %llu\n", mem5.nAlloc);
16358 fprintf(out, "mem5.totalAlloc = %llu\n", mem5.totalAlloc);
16359 fprintf(out, "mem5.totalExcess = %llu\n", mem5.totalExcess);
16360 fprintf(out, "mem5.currentOut = %u\n", mem5.currentOut);
16361 fprintf(out, "mem5.currentCount = %u\n", mem5.currentCount);
16362 fprintf(out, "mem5.maxOut = %u\n", mem5.maxOut);
16363 fprintf(out, "mem5.maxCount = %u\n", mem5.maxCount);
16364 fprintf(out, "mem5.maxRequest = %u\n", mem5.maxRequest);
16365 memsys5Leave();
16366 if( out==stdout ){
16367 fflush(stdout);
16368 }else{
16369 fclose(out);
16372 #endif
16375 ** This routine is the only routine in this file with external
16376 ** linkage. It returns a pointer to a static sqlite3_mem_methods
16377 ** struct populated with the memsys5 methods.
16379 SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys5(void){
16380 static const sqlite3_mem_methods memsys5Methods = {
16381 memsys5Malloc,
16382 memsys5Free,
16383 memsys5Realloc,
16384 memsys5Size,
16385 memsys5Roundup,
16386 memsys5Init,
16387 memsys5Shutdown,
16390 return &memsys5Methods;
16393 #endif /* SQLITE_ENABLE_MEMSYS5 */
16395 /************** End of mem5.c ************************************************/
16396 /************** Begin file mutex.c *******************************************/
16398 ** 2007 August 14
16400 ** The author disclaims copyright to this source code. In place of
16401 ** a legal notice, here is a blessing:
16403 ** May you do good and not evil.
16404 ** May you find forgiveness for yourself and forgive others.
16405 ** May you share freely, never taking more than you give.
16407 *************************************************************************
16408 ** This file contains the C functions that implement mutexes.
16410 ** This file contains code that is common across all mutex implementations.
16413 #if defined(SQLITE_DEBUG) && !defined(SQLITE_MUTEX_OMIT)
16415 ** For debugging purposes, record when the mutex subsystem is initialized
16416 ** and uninitialized so that we can assert() if there is an attempt to
16417 ** allocate a mutex while the system is uninitialized.
16419 static SQLITE_WSD int mutexIsInit = 0;
16420 #endif /* SQLITE_DEBUG */
16423 #ifndef SQLITE_MUTEX_OMIT
16425 ** Initialize the mutex system.
16427 SQLITE_PRIVATE int sqlite3MutexInit(void){
16428 int rc = SQLITE_OK;
16429 if( !sqlite3GlobalConfig.mutex.xMutexAlloc ){
16430 /* If the xMutexAlloc method has not been set, then the user did not
16431 ** install a mutex implementation via sqlite3_config() prior to
16432 ** sqlite3_initialize() being called. This block copies pointers to
16433 ** the default implementation into the sqlite3GlobalConfig structure.
16435 sqlite3_mutex_methods const *pFrom;
16436 sqlite3_mutex_methods *pTo = &sqlite3GlobalConfig.mutex;
16438 if( sqlite3GlobalConfig.bCoreMutex ){
16439 pFrom = sqlite3DefaultMutex();
16440 }else{
16441 pFrom = sqlite3NoopMutex();
16443 memcpy(pTo, pFrom, offsetof(sqlite3_mutex_methods, xMutexAlloc));
16444 memcpy(&pTo->xMutexFree, &pFrom->xMutexFree,
16445 sizeof(*pTo) - offsetof(sqlite3_mutex_methods, xMutexFree));
16446 pTo->xMutexAlloc = pFrom->xMutexAlloc;
16448 rc = sqlite3GlobalConfig.mutex.xMutexInit();
16450 #ifdef SQLITE_DEBUG
16451 GLOBAL(int, mutexIsInit) = 1;
16452 #endif
16454 return rc;
16458 ** Shutdown the mutex system. This call frees resources allocated by
16459 ** sqlite3MutexInit().
16461 SQLITE_PRIVATE int sqlite3MutexEnd(void){
16462 int rc = SQLITE_OK;
16463 if( sqlite3GlobalConfig.mutex.xMutexEnd ){
16464 rc = sqlite3GlobalConfig.mutex.xMutexEnd();
16467 #ifdef SQLITE_DEBUG
16468 GLOBAL(int, mutexIsInit) = 0;
16469 #endif
16471 return rc;
16475 ** Retrieve a pointer to a static mutex or allocate a new dynamic one.
16477 SQLITE_API sqlite3_mutex *sqlite3_mutex_alloc(int id){
16478 #ifndef SQLITE_OMIT_AUTOINIT
16479 if( sqlite3_initialize() ) return 0;
16480 #endif
16481 return sqlite3GlobalConfig.mutex.xMutexAlloc(id);
16484 SQLITE_PRIVATE sqlite3_mutex *sqlite3MutexAlloc(int id){
16485 if( !sqlite3GlobalConfig.bCoreMutex ){
16486 return 0;
16488 assert( GLOBAL(int, mutexIsInit) );
16489 return sqlite3GlobalConfig.mutex.xMutexAlloc(id);
16493 ** Free a dynamic mutex.
16495 SQLITE_API void sqlite3_mutex_free(sqlite3_mutex *p){
16496 if( p ){
16497 sqlite3GlobalConfig.mutex.xMutexFree(p);
16502 ** Obtain the mutex p. If some other thread already has the mutex, block
16503 ** until it can be obtained.
16505 SQLITE_API void sqlite3_mutex_enter(sqlite3_mutex *p){
16506 if( p ){
16507 sqlite3GlobalConfig.mutex.xMutexEnter(p);
16512 ** Obtain the mutex p. If successful, return SQLITE_OK. Otherwise, if another
16513 ** thread holds the mutex and it cannot be obtained, return SQLITE_BUSY.
16515 SQLITE_API int sqlite3_mutex_try(sqlite3_mutex *p){
16516 int rc = SQLITE_OK;
16517 if( p ){
16518 return sqlite3GlobalConfig.mutex.xMutexTry(p);
16520 return rc;
16524 ** The sqlite3_mutex_leave() routine exits a mutex that was previously
16525 ** entered by the same thread. The behavior is undefined if the mutex
16526 ** is not currently entered. If a NULL pointer is passed as an argument
16527 ** this function is a no-op.
16529 SQLITE_API void sqlite3_mutex_leave(sqlite3_mutex *p){
16530 if( p ){
16531 sqlite3GlobalConfig.mutex.xMutexLeave(p);
16535 #ifndef NDEBUG
16537 ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
16538 ** intended for use inside assert() statements.
16540 SQLITE_API int sqlite3_mutex_held(sqlite3_mutex *p){
16541 return p==0 || sqlite3GlobalConfig.mutex.xMutexHeld(p);
16543 SQLITE_API int sqlite3_mutex_notheld(sqlite3_mutex *p){
16544 return p==0 || sqlite3GlobalConfig.mutex.xMutexNotheld(p);
16546 #endif
16548 #endif /* SQLITE_MUTEX_OMIT */
16550 /************** End of mutex.c ***********************************************/
16551 /************** Begin file mutex_noop.c **************************************/
16553 ** 2008 October 07
16555 ** The author disclaims copyright to this source code. In place of
16556 ** a legal notice, here is a blessing:
16558 ** May you do good and not evil.
16559 ** May you find forgiveness for yourself and forgive others.
16560 ** May you share freely, never taking more than you give.
16562 *************************************************************************
16563 ** This file contains the C functions that implement mutexes.
16565 ** This implementation in this file does not provide any mutual
16566 ** exclusion and is thus suitable for use only in applications
16567 ** that use SQLite in a single thread. The routines defined
16568 ** here are place-holders. Applications can substitute working
16569 ** mutex routines at start-time using the
16571 ** sqlite3_config(SQLITE_CONFIG_MUTEX,...)
16573 ** interface.
16575 ** If compiled with SQLITE_DEBUG, then additional logic is inserted
16576 ** that does error checking on mutexes to make sure they are being
16577 ** called correctly.
16580 #ifndef SQLITE_MUTEX_OMIT
16582 #ifndef SQLITE_DEBUG
16584 ** Stub routines for all mutex methods.
16586 ** This routines provide no mutual exclusion or error checking.
16588 static int noopMutexInit(void){ return SQLITE_OK; }
16589 static int noopMutexEnd(void){ return SQLITE_OK; }
16590 static sqlite3_mutex *noopMutexAlloc(int id){
16591 UNUSED_PARAMETER(id);
16592 return (sqlite3_mutex*)8;
16594 static void noopMutexFree(sqlite3_mutex *p){ UNUSED_PARAMETER(p); return; }
16595 static void noopMutexEnter(sqlite3_mutex *p){ UNUSED_PARAMETER(p); return; }
16596 static int noopMutexTry(sqlite3_mutex *p){
16597 UNUSED_PARAMETER(p);
16598 return SQLITE_OK;
16600 static void noopMutexLeave(sqlite3_mutex *p){ UNUSED_PARAMETER(p); return; }
16602 SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3NoopMutex(void){
16603 static const sqlite3_mutex_methods sMutex = {
16604 noopMutexInit,
16605 noopMutexEnd,
16606 noopMutexAlloc,
16607 noopMutexFree,
16608 noopMutexEnter,
16609 noopMutexTry,
16610 noopMutexLeave,
16616 return &sMutex;
16618 #endif /* !SQLITE_DEBUG */
16620 #ifdef SQLITE_DEBUG
16622 ** In this implementation, error checking is provided for testing
16623 ** and debugging purposes. The mutexes still do not provide any
16624 ** mutual exclusion.
16628 ** The mutex object
16630 typedef struct sqlite3_debug_mutex {
16631 int id; /* The mutex type */
16632 int cnt; /* Number of entries without a matching leave */
16633 } sqlite3_debug_mutex;
16636 ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
16637 ** intended for use inside assert() statements.
16639 static int debugMutexHeld(sqlite3_mutex *pX){
16640 sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
16641 return p==0 || p->cnt>0;
16643 static int debugMutexNotheld(sqlite3_mutex *pX){
16644 sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
16645 return p==0 || p->cnt==0;
16649 ** Initialize and deinitialize the mutex subsystem.
16651 static int debugMutexInit(void){ return SQLITE_OK; }
16652 static int debugMutexEnd(void){ return SQLITE_OK; }
16655 ** The sqlite3_mutex_alloc() routine allocates a new
16656 ** mutex and returns a pointer to it. If it returns NULL
16657 ** that means that a mutex could not be allocated.
16659 static sqlite3_mutex *debugMutexAlloc(int id){
16660 static sqlite3_debug_mutex aStatic[6];
16661 sqlite3_debug_mutex *pNew = 0;
16662 switch( id ){
16663 case SQLITE_MUTEX_FAST:
16664 case SQLITE_MUTEX_RECURSIVE: {
16665 pNew = sqlite3Malloc(sizeof(*pNew));
16666 if( pNew ){
16667 pNew->id = id;
16668 pNew->cnt = 0;
16670 break;
16672 default: {
16673 assert( id-2 >= 0 );
16674 assert( id-2 < (int)(sizeof(aStatic)/sizeof(aStatic[0])) );
16675 pNew = &aStatic[id-2];
16676 pNew->id = id;
16677 break;
16680 return (sqlite3_mutex*)pNew;
16684 ** This routine deallocates a previously allocated mutex.
16686 static void debugMutexFree(sqlite3_mutex *pX){
16687 sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
16688 assert( p->cnt==0 );
16689 assert( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE );
16690 sqlite3_free(p);
16694 ** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
16695 ** to enter a mutex. If another thread is already within the mutex,
16696 ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
16697 ** SQLITE_BUSY. The sqlite3_mutex_try() interface returns SQLITE_OK
16698 ** upon successful entry. Mutexes created using SQLITE_MUTEX_RECURSIVE can
16699 ** be entered multiple times by the same thread. In such cases the,
16700 ** mutex must be exited an equal number of times before another thread
16701 ** can enter. If the same thread tries to enter any other kind of mutex
16702 ** more than once, the behavior is undefined.
16704 static void debugMutexEnter(sqlite3_mutex *pX){
16705 sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
16706 assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(pX) );
16707 p->cnt++;
16709 static int debugMutexTry(sqlite3_mutex *pX){
16710 sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
16711 assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(pX) );
16712 p->cnt++;
16713 return SQLITE_OK;
16717 ** The sqlite3_mutex_leave() routine exits a mutex that was
16718 ** previously entered by the same thread. The behavior
16719 ** is undefined if the mutex is not currently entered or
16720 ** is not currently allocated. SQLite will never do either.
16722 static void debugMutexLeave(sqlite3_mutex *pX){
16723 sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
16724 assert( debugMutexHeld(pX) );
16725 p->cnt--;
16726 assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(pX) );
16729 SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3NoopMutex(void){
16730 static const sqlite3_mutex_methods sMutex = {
16731 debugMutexInit,
16732 debugMutexEnd,
16733 debugMutexAlloc,
16734 debugMutexFree,
16735 debugMutexEnter,
16736 debugMutexTry,
16737 debugMutexLeave,
16739 debugMutexHeld,
16740 debugMutexNotheld
16743 return &sMutex;
16745 #endif /* SQLITE_DEBUG */
16748 ** If compiled with SQLITE_MUTEX_NOOP, then the no-op mutex implementation
16749 ** is used regardless of the run-time threadsafety setting.
16751 #ifdef SQLITE_MUTEX_NOOP
16752 SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void){
16753 return sqlite3NoopMutex();
16755 #endif /* SQLITE_MUTEX_NOOP */
16756 #endif /* SQLITE_MUTEX_OMIT */
16758 /************** End of mutex_noop.c ******************************************/
16759 /************** Begin file mutex_os2.c ***************************************/
16761 ** 2007 August 28
16763 ** The author disclaims copyright to this source code. In place of
16764 ** a legal notice, here is a blessing:
16766 ** May you do good and not evil.
16767 ** May you find forgiveness for yourself and forgive others.
16768 ** May you share freely, never taking more than you give.
16770 *************************************************************************
16771 ** This file contains the C functions that implement mutexes for OS/2
16775 ** The code in this file is only used if SQLITE_MUTEX_OS2 is defined.
16776 ** See the mutex.h file for details.
16778 #ifdef SQLITE_MUTEX_OS2
16780 /********************** OS/2 Mutex Implementation **********************
16782 ** This implementation of mutexes is built using the OS/2 API.
16786 ** The mutex object
16787 ** Each recursive mutex is an instance of the following structure.
16789 struct sqlite3_mutex {
16790 HMTX mutex; /* Mutex controlling the lock */
16791 int id; /* Mutex type */
16792 #ifdef SQLITE_DEBUG
16793 int trace; /* True to trace changes */
16794 #endif
16797 #ifdef SQLITE_DEBUG
16798 #define SQLITE3_MUTEX_INITIALIZER { 0, 0, 0 }
16799 #else
16800 #define SQLITE3_MUTEX_INITIALIZER { 0, 0 }
16801 #endif
16804 ** Initialize and deinitialize the mutex subsystem.
16806 static int os2MutexInit(void){ return SQLITE_OK; }
16807 static int os2MutexEnd(void){ return SQLITE_OK; }
16810 ** The sqlite3_mutex_alloc() routine allocates a new
16811 ** mutex and returns a pointer to it. If it returns NULL
16812 ** that means that a mutex could not be allocated.
16813 ** SQLite will unwind its stack and return an error. The argument
16814 ** to sqlite3_mutex_alloc() is one of these integer constants:
16816 ** <ul>
16817 ** <li> SQLITE_MUTEX_FAST
16818 ** <li> SQLITE_MUTEX_RECURSIVE
16819 ** <li> SQLITE_MUTEX_STATIC_MASTER
16820 ** <li> SQLITE_MUTEX_STATIC_MEM
16821 ** <li> SQLITE_MUTEX_STATIC_MEM2
16822 ** <li> SQLITE_MUTEX_STATIC_PRNG
16823 ** <li> SQLITE_MUTEX_STATIC_LRU
16824 ** <li> SQLITE_MUTEX_STATIC_LRU2
16825 ** </ul>
16827 ** The first two constants cause sqlite3_mutex_alloc() to create
16828 ** a new mutex. The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
16829 ** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
16830 ** The mutex implementation does not need to make a distinction
16831 ** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
16832 ** not want to. But SQLite will only request a recursive mutex in
16833 ** cases where it really needs one. If a faster non-recursive mutex
16834 ** implementation is available on the host platform, the mutex subsystem
16835 ** might return such a mutex in response to SQLITE_MUTEX_FAST.
16837 ** The other allowed parameters to sqlite3_mutex_alloc() each return
16838 ** a pointer to a static preexisting mutex. Six static mutexes are
16839 ** used by the current version of SQLite. Future versions of SQLite
16840 ** may add additional static mutexes. Static mutexes are for internal
16841 ** use by SQLite only. Applications that use SQLite mutexes should
16842 ** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
16843 ** SQLITE_MUTEX_RECURSIVE.
16845 ** Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
16846 ** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
16847 ** returns a different mutex on every call. But for the static
16848 ** mutex types, the same mutex is returned on every call that has
16849 ** the same type number.
16851 static sqlite3_mutex *os2MutexAlloc(int iType){
16852 sqlite3_mutex *p = NULL;
16853 switch( iType ){
16854 case SQLITE_MUTEX_FAST:
16855 case SQLITE_MUTEX_RECURSIVE: {
16856 p = sqlite3MallocZero( sizeof(*p) );
16857 if( p ){
16858 p->id = iType;
16859 if( DosCreateMutexSem( 0, &p->mutex, 0, FALSE ) != NO_ERROR ){
16860 sqlite3_free( p );
16861 p = NULL;
16864 break;
16866 default: {
16867 static volatile int isInit = 0;
16868 static sqlite3_mutex staticMutexes[6] = {
16869 SQLITE3_MUTEX_INITIALIZER,
16870 SQLITE3_MUTEX_INITIALIZER,
16871 SQLITE3_MUTEX_INITIALIZER,
16872 SQLITE3_MUTEX_INITIALIZER,
16873 SQLITE3_MUTEX_INITIALIZER,
16874 SQLITE3_MUTEX_INITIALIZER,
16876 if ( !isInit ){
16877 APIRET rc;
16878 PTIB ptib;
16879 PPIB ppib;
16880 HMTX mutex;
16881 char name[32];
16882 DosGetInfoBlocks( &ptib, &ppib );
16883 sqlite3_snprintf( sizeof(name), name, "\\SEM32\\SQLITE%04x",
16884 ppib->pib_ulpid );
16885 while( !isInit ){
16886 mutex = 0;
16887 rc = DosCreateMutexSem( name, &mutex, 0, FALSE);
16888 if( rc == NO_ERROR ){
16889 unsigned int i;
16890 if( !isInit ){
16891 for( i = 0; i < sizeof(staticMutexes)/sizeof(staticMutexes[0]); i++ ){
16892 DosCreateMutexSem( 0, &staticMutexes[i].mutex, 0, FALSE );
16894 isInit = 1;
16896 DosCloseMutexSem( mutex );
16897 }else if( rc == ERROR_DUPLICATE_NAME ){
16898 DosSleep( 1 );
16899 }else{
16900 return p;
16904 assert( iType-2 >= 0 );
16905 assert( iType-2 < sizeof(staticMutexes)/sizeof(staticMutexes[0]) );
16906 p = &staticMutexes[iType-2];
16907 p->id = iType;
16908 break;
16911 return p;
16916 ** This routine deallocates a previously allocated mutex.
16917 ** SQLite is careful to deallocate every mutex that it allocates.
16919 static void os2MutexFree(sqlite3_mutex *p){
16920 #ifdef SQLITE_DEBUG
16921 TID tid;
16922 PID pid;
16923 ULONG ulCount;
16924 DosQueryMutexSem(p->mutex, &pid, &tid, &ulCount);
16925 assert( ulCount==0 );
16926 assert( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE );
16927 #endif
16928 DosCloseMutexSem( p->mutex );
16929 sqlite3_free( p );
16932 #ifdef SQLITE_DEBUG
16934 ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
16935 ** intended for use inside assert() statements.
16937 static int os2MutexHeld(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 || ( ulCount>1 && p->id!=SQLITE_MUTEX_RECURSIVE ) )
16944 return 0;
16945 DosGetInfoBlocks(&ptib, NULL);
16946 return tid==ptib->tib_ptib2->tib2_ultid;
16948 static int os2MutexNotheld(sqlite3_mutex *p){
16949 TID tid;
16950 PID pid;
16951 ULONG ulCount;
16952 PTIB ptib;
16953 DosQueryMutexSem(p->mutex, &pid, &tid, &ulCount);
16954 if( ulCount==0 )
16955 return 1;
16956 DosGetInfoBlocks(&ptib, NULL);
16957 return tid!=ptib->tib_ptib2->tib2_ultid;
16959 static void os2MutexTrace(sqlite3_mutex *p, char *pAction){
16960 TID tid;
16961 PID pid;
16962 ULONG ulCount;
16963 DosQueryMutexSem(p->mutex, &pid, &tid, &ulCount);
16964 printf("%s mutex %p (%d) with nRef=%ld\n", pAction, (void*)p, p->trace, ulCount);
16966 #endif
16969 ** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
16970 ** to enter a mutex. If another thread is already within the mutex,
16971 ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
16972 ** SQLITE_BUSY. The sqlite3_mutex_try() interface returns SQLITE_OK
16973 ** upon successful entry. Mutexes created using SQLITE_MUTEX_RECURSIVE can
16974 ** be entered multiple times by the same thread. In such cases the,
16975 ** mutex must be exited an equal number of times before another thread
16976 ** can enter. If the same thread tries to enter any other kind of mutex
16977 ** more than once, the behavior is undefined.
16979 static void os2MutexEnter(sqlite3_mutex *p){
16980 assert( p->id==SQLITE_MUTEX_RECURSIVE || os2MutexNotheld(p) );
16981 DosRequestMutexSem(p->mutex, SEM_INDEFINITE_WAIT);
16982 #ifdef SQLITE_DEBUG
16983 if( p->trace ) os2MutexTrace(p, "enter");
16984 #endif
16986 static int os2MutexTry(sqlite3_mutex *p){
16987 int rc = SQLITE_BUSY;
16988 assert( p->id==SQLITE_MUTEX_RECURSIVE || os2MutexNotheld(p) );
16989 if( DosRequestMutexSem(p->mutex, SEM_IMMEDIATE_RETURN) == NO_ERROR ) {
16990 rc = SQLITE_OK;
16991 #ifdef SQLITE_DEBUG
16992 if( p->trace ) os2MutexTrace(p, "try");
16993 #endif
16995 return rc;
16999 ** The sqlite3_mutex_leave() routine exits a mutex that was
17000 ** previously entered by the same thread. The behavior
17001 ** is undefined if the mutex is not currently entered or
17002 ** is not currently allocated. SQLite will never do either.
17004 static void os2MutexLeave(sqlite3_mutex *p){
17005 assert( os2MutexHeld(p) );
17006 DosReleaseMutexSem(p->mutex);
17007 #ifdef SQLITE_DEBUG
17008 if( p->trace ) os2MutexTrace(p, "leave");
17009 #endif
17012 SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void){
17013 static const sqlite3_mutex_methods sMutex = {
17014 os2MutexInit,
17015 os2MutexEnd,
17016 os2MutexAlloc,
17017 os2MutexFree,
17018 os2MutexEnter,
17019 os2MutexTry,
17020 os2MutexLeave,
17021 #ifdef SQLITE_DEBUG
17022 os2MutexHeld,
17023 os2MutexNotheld
17024 #else
17027 #endif
17030 return &sMutex;
17032 #endif /* SQLITE_MUTEX_OS2 */
17034 /************** End of mutex_os2.c *******************************************/
17035 /************** Begin file mutex_unix.c **************************************/
17037 ** 2007 August 28
17039 ** The author disclaims copyright to this source code. In place of
17040 ** a legal notice, here is a blessing:
17042 ** May you do good and not evil.
17043 ** May you find forgiveness for yourself and forgive others.
17044 ** May you share freely, never taking more than you give.
17046 *************************************************************************
17047 ** This file contains the C functions that implement mutexes for pthreads
17051 ** The code in this file is only used if we are compiling threadsafe
17052 ** under unix with pthreads.
17054 ** Note that this implementation requires a version of pthreads that
17055 ** supports recursive mutexes.
17057 #ifdef SQLITE_MUTEX_PTHREADS
17059 #include <pthread.h>
17062 ** The sqlite3_mutex.id, sqlite3_mutex.nRef, and sqlite3_mutex.owner fields
17063 ** are necessary under two condidtions: (1) Debug builds and (2) using
17064 ** home-grown mutexes. Encapsulate these conditions into a single #define.
17066 #if defined(SQLITE_DEBUG) || defined(SQLITE_HOMEGROWN_RECURSIVE_MUTEX)
17067 # define SQLITE_MUTEX_NREF 1
17068 #else
17069 # define SQLITE_MUTEX_NREF 0
17070 #endif
17073 ** Each recursive mutex is an instance of the following structure.
17075 struct sqlite3_mutex {
17076 pthread_mutex_t mutex; /* Mutex controlling the lock */
17077 #if SQLITE_MUTEX_NREF
17078 int id; /* Mutex type */
17079 volatile int nRef; /* Number of entrances */
17080 volatile pthread_t owner; /* Thread that is within this mutex */
17081 int trace; /* True to trace changes */
17082 #endif
17084 #if SQLITE_MUTEX_NREF
17085 #define SQLITE3_MUTEX_INITIALIZER { PTHREAD_MUTEX_INITIALIZER, 0, 0, (pthread_t)0, 0 }
17086 #else
17087 #define SQLITE3_MUTEX_INITIALIZER { PTHREAD_MUTEX_INITIALIZER }
17088 #endif
17091 ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
17092 ** intended for use only inside assert() statements. On some platforms,
17093 ** there might be race conditions that can cause these routines to
17094 ** deliver incorrect results. In particular, if pthread_equal() is
17095 ** not an atomic operation, then these routines might delivery
17096 ** incorrect results. On most platforms, pthread_equal() is a
17097 ** comparison of two integers and is therefore atomic. But we are
17098 ** told that HPUX is not such a platform. If so, then these routines
17099 ** will not always work correctly on HPUX.
17101 ** On those platforms where pthread_equal() is not atomic, SQLite
17102 ** should be compiled without -DSQLITE_DEBUG and with -DNDEBUG to
17103 ** make sure no assert() statements are evaluated and hence these
17104 ** routines are never called.
17106 #if !defined(NDEBUG) || defined(SQLITE_DEBUG)
17107 static int pthreadMutexHeld(sqlite3_mutex *p){
17108 return (p->nRef!=0 && pthread_equal(p->owner, pthread_self()));
17110 static int pthreadMutexNotheld(sqlite3_mutex *p){
17111 return p->nRef==0 || pthread_equal(p->owner, pthread_self())==0;
17113 #endif
17116 ** Initialize and deinitialize the mutex subsystem.
17118 static int pthreadMutexInit(void){ return SQLITE_OK; }
17119 static int pthreadMutexEnd(void){ return SQLITE_OK; }
17122 ** The sqlite3_mutex_alloc() routine allocates a new
17123 ** mutex and returns a pointer to it. If it returns NULL
17124 ** that means that a mutex could not be allocated. SQLite
17125 ** will unwind its stack and return an error. The argument
17126 ** to sqlite3_mutex_alloc() is one of these integer constants:
17128 ** <ul>
17129 ** <li> SQLITE_MUTEX_FAST
17130 ** <li> SQLITE_MUTEX_RECURSIVE
17131 ** <li> SQLITE_MUTEX_STATIC_MASTER
17132 ** <li> SQLITE_MUTEX_STATIC_MEM
17133 ** <li> SQLITE_MUTEX_STATIC_MEM2
17134 ** <li> SQLITE_MUTEX_STATIC_PRNG
17135 ** <li> SQLITE_MUTEX_STATIC_LRU
17136 ** <li> SQLITE_MUTEX_STATIC_PMEM
17137 ** </ul>
17139 ** The first two constants cause sqlite3_mutex_alloc() to create
17140 ** a new mutex. The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
17141 ** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
17142 ** The mutex implementation does not need to make a distinction
17143 ** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
17144 ** not want to. But SQLite will only request a recursive mutex in
17145 ** cases where it really needs one. If a faster non-recursive mutex
17146 ** implementation is available on the host platform, the mutex subsystem
17147 ** might return such a mutex in response to SQLITE_MUTEX_FAST.
17149 ** The other allowed parameters to sqlite3_mutex_alloc() each return
17150 ** a pointer to a static preexisting mutex. Six static mutexes are
17151 ** used by the current version of SQLite. Future versions of SQLite
17152 ** may add additional static mutexes. Static mutexes are for internal
17153 ** use by SQLite only. Applications that use SQLite mutexes should
17154 ** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
17155 ** SQLITE_MUTEX_RECURSIVE.
17157 ** Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
17158 ** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
17159 ** returns a different mutex on every call. But for the static
17160 ** mutex types, the same mutex is returned on every call that has
17161 ** the same type number.
17163 static sqlite3_mutex *pthreadMutexAlloc(int iType){
17164 static sqlite3_mutex staticMutexes[] = {
17165 SQLITE3_MUTEX_INITIALIZER,
17166 SQLITE3_MUTEX_INITIALIZER,
17167 SQLITE3_MUTEX_INITIALIZER,
17168 SQLITE3_MUTEX_INITIALIZER,
17169 SQLITE3_MUTEX_INITIALIZER,
17170 SQLITE3_MUTEX_INITIALIZER
17172 sqlite3_mutex *p;
17173 switch( iType ){
17174 case SQLITE_MUTEX_RECURSIVE: {
17175 p = sqlite3MallocZero( sizeof(*p) );
17176 if( p ){
17177 #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
17178 /* If recursive mutexes are not available, we will have to
17179 ** build our own. See below. */
17180 pthread_mutex_init(&p->mutex, 0);
17181 #else
17182 /* Use a recursive mutex if it is available */
17183 pthread_mutexattr_t recursiveAttr;
17184 pthread_mutexattr_init(&recursiveAttr);
17185 pthread_mutexattr_settype(&recursiveAttr, PTHREAD_MUTEX_RECURSIVE);
17186 pthread_mutex_init(&p->mutex, &recursiveAttr);
17187 pthread_mutexattr_destroy(&recursiveAttr);
17188 #endif
17189 #if SQLITE_MUTEX_NREF
17190 p->id = iType;
17191 #endif
17193 break;
17195 case SQLITE_MUTEX_FAST: {
17196 p = sqlite3MallocZero( sizeof(*p) );
17197 if( p ){
17198 #if SQLITE_MUTEX_NREF
17199 p->id = iType;
17200 #endif
17201 pthread_mutex_init(&p->mutex, 0);
17203 break;
17205 default: {
17206 assert( iType-2 >= 0 );
17207 assert( iType-2 < ArraySize(staticMutexes) );
17208 p = &staticMutexes[iType-2];
17209 #if SQLITE_MUTEX_NREF
17210 p->id = iType;
17211 #endif
17212 break;
17215 return p;
17220 ** This routine deallocates a previously
17221 ** allocated mutex. SQLite is careful to deallocate every
17222 ** mutex that it allocates.
17224 static void pthreadMutexFree(sqlite3_mutex *p){
17225 assert( p->nRef==0 );
17226 assert( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE );
17227 pthread_mutex_destroy(&p->mutex);
17228 sqlite3_free(p);
17232 ** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
17233 ** to enter a mutex. If another thread is already within the mutex,
17234 ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
17235 ** SQLITE_BUSY. The sqlite3_mutex_try() interface returns SQLITE_OK
17236 ** upon successful entry. Mutexes created using SQLITE_MUTEX_RECURSIVE can
17237 ** be entered multiple times by the same thread. In such cases the,
17238 ** mutex must be exited an equal number of times before another thread
17239 ** can enter. If the same thread tries to enter any other kind of mutex
17240 ** more than once, the behavior is undefined.
17242 static void pthreadMutexEnter(sqlite3_mutex *p){
17243 assert( p->id==SQLITE_MUTEX_RECURSIVE || pthreadMutexNotheld(p) );
17245 #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
17246 /* If recursive mutexes are not available, then we have to grow
17247 ** our own. This implementation assumes that pthread_equal()
17248 ** is atomic - that it cannot be deceived into thinking self
17249 ** and p->owner are equal if p->owner changes between two values
17250 ** that are not equal to self while the comparison is taking place.
17251 ** This implementation also assumes a coherent cache - that
17252 ** separate processes cannot read different values from the same
17253 ** address at the same time. If either of these two conditions
17254 ** are not met, then the mutexes will fail and problems will result.
17257 pthread_t self = pthread_self();
17258 if( p->nRef>0 && pthread_equal(p->owner, self) ){
17259 p->nRef++;
17260 }else{
17261 pthread_mutex_lock(&p->mutex);
17262 assert( p->nRef==0 );
17263 p->owner = self;
17264 p->nRef = 1;
17267 #else
17268 /* Use the built-in recursive mutexes if they are available.
17270 pthread_mutex_lock(&p->mutex);
17271 #if SQLITE_MUTEX_NREF
17272 assert( p->nRef>0 || p->owner==0 );
17273 p->owner = pthread_self();
17274 p->nRef++;
17275 #endif
17276 #endif
17278 #ifdef SQLITE_DEBUG
17279 if( p->trace ){
17280 printf("enter mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
17282 #endif
17284 static int pthreadMutexTry(sqlite3_mutex *p){
17285 int rc;
17286 assert( p->id==SQLITE_MUTEX_RECURSIVE || pthreadMutexNotheld(p) );
17288 #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
17289 /* If recursive mutexes are not available, then we have to grow
17290 ** our own. This implementation assumes that pthread_equal()
17291 ** is atomic - that it cannot be deceived into thinking self
17292 ** and p->owner are equal if p->owner changes between two values
17293 ** that are not equal to self while the comparison is taking place.
17294 ** This implementation also assumes a coherent cache - that
17295 ** separate processes cannot read different values from the same
17296 ** address at the same time. If either of these two conditions
17297 ** are not met, then the mutexes will fail and problems will result.
17300 pthread_t self = pthread_self();
17301 if( p->nRef>0 && pthread_equal(p->owner, self) ){
17302 p->nRef++;
17303 rc = SQLITE_OK;
17304 }else if( pthread_mutex_trylock(&p->mutex)==0 ){
17305 assert( p->nRef==0 );
17306 p->owner = self;
17307 p->nRef = 1;
17308 rc = SQLITE_OK;
17309 }else{
17310 rc = SQLITE_BUSY;
17313 #else
17314 /* Use the built-in recursive mutexes if they are available.
17316 if( pthread_mutex_trylock(&p->mutex)==0 ){
17317 #if SQLITE_MUTEX_NREF
17318 p->owner = pthread_self();
17319 p->nRef++;
17320 #endif
17321 rc = SQLITE_OK;
17322 }else{
17323 rc = SQLITE_BUSY;
17325 #endif
17327 #ifdef SQLITE_DEBUG
17328 if( rc==SQLITE_OK && p->trace ){
17329 printf("enter mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
17331 #endif
17332 return rc;
17336 ** The sqlite3_mutex_leave() routine exits a mutex that was
17337 ** previously entered by the same thread. The behavior
17338 ** is undefined if the mutex is not currently entered or
17339 ** is not currently allocated. SQLite will never do either.
17341 static void pthreadMutexLeave(sqlite3_mutex *p){
17342 assert( pthreadMutexHeld(p) );
17343 #if SQLITE_MUTEX_NREF
17344 p->nRef--;
17345 if( p->nRef==0 ) p->owner = 0;
17346 #endif
17347 assert( p->nRef==0 || p->id==SQLITE_MUTEX_RECURSIVE );
17349 #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
17350 if( p->nRef==0 ){
17351 pthread_mutex_unlock(&p->mutex);
17353 #else
17354 pthread_mutex_unlock(&p->mutex);
17355 #endif
17357 #ifdef SQLITE_DEBUG
17358 if( p->trace ){
17359 printf("leave mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
17361 #endif
17364 SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void){
17365 static const sqlite3_mutex_methods sMutex = {
17366 pthreadMutexInit,
17367 pthreadMutexEnd,
17368 pthreadMutexAlloc,
17369 pthreadMutexFree,
17370 pthreadMutexEnter,
17371 pthreadMutexTry,
17372 pthreadMutexLeave,
17373 #ifdef SQLITE_DEBUG
17374 pthreadMutexHeld,
17375 pthreadMutexNotheld
17376 #else
17379 #endif
17382 return &sMutex;
17385 #endif /* SQLITE_MUTEX_PTHREAD */
17387 /************** End of mutex_unix.c ******************************************/
17388 /************** Begin file mutex_w32.c ***************************************/
17390 ** 2007 August 14
17392 ** The author disclaims copyright to this source code. In place of
17393 ** a legal notice, here is a blessing:
17395 ** May you do good and not evil.
17396 ** May you find forgiveness for yourself and forgive others.
17397 ** May you share freely, never taking more than you give.
17399 *************************************************************************
17400 ** This file contains the C functions that implement mutexes for win32
17404 ** The code in this file is only used if we are compiling multithreaded
17405 ** on a win32 system.
17407 #ifdef SQLITE_MUTEX_W32
17410 ** Each recursive mutex is an instance of the following structure.
17412 struct sqlite3_mutex {
17413 CRITICAL_SECTION mutex; /* Mutex controlling the lock */
17414 int id; /* Mutex type */
17415 #ifdef SQLITE_DEBUG
17416 volatile int nRef; /* Number of enterances */
17417 volatile DWORD owner; /* Thread holding this mutex */
17418 int trace; /* True to trace changes */
17419 #endif
17421 #define SQLITE_W32_MUTEX_INITIALIZER { 0 }
17422 #ifdef SQLITE_DEBUG
17423 #define SQLITE3_MUTEX_INITIALIZER { SQLITE_W32_MUTEX_INITIALIZER, 0, 0L, (DWORD)0, 0 }
17424 #else
17425 #define SQLITE3_MUTEX_INITIALIZER { SQLITE_W32_MUTEX_INITIALIZER, 0 }
17426 #endif
17429 ** Return true (non-zero) if we are running under WinNT, Win2K, WinXP,
17430 ** or WinCE. Return false (zero) for Win95, Win98, or WinME.
17432 ** Here is an interesting observation: Win95, Win98, and WinME lack
17433 ** the LockFileEx() API. But we can still statically link against that
17434 ** API as long as we don't call it win running Win95/98/ME. A call to
17435 ** this routine is used to determine if the host is Win95/98/ME or
17436 ** WinNT/2K/XP so that we will know whether or not we can safely call
17437 ** the LockFileEx() API.
17439 ** mutexIsNT() is only used for the TryEnterCriticalSection() API call,
17440 ** which is only available if your application was compiled with
17441 ** _WIN32_WINNT defined to a value >= 0x0400. Currently, the only
17442 ** call to TryEnterCriticalSection() is #ifdef'ed out, so #ifdef
17443 ** this out as well.
17445 #if 0
17446 #if SQLITE_OS_WINCE
17447 # define mutexIsNT() (1)
17448 #else
17449 static int mutexIsNT(void){
17450 static int osType = 0;
17451 if( osType==0 ){
17452 OSVERSIONINFO sInfo;
17453 sInfo.dwOSVersionInfoSize = sizeof(sInfo);
17454 GetVersionEx(&sInfo);
17455 osType = sInfo.dwPlatformId==VER_PLATFORM_WIN32_NT ? 2 : 1;
17457 return osType==2;
17459 #endif /* SQLITE_OS_WINCE */
17460 #endif
17462 #ifdef SQLITE_DEBUG
17464 ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
17465 ** intended for use only inside assert() statements.
17467 static int winMutexHeld(sqlite3_mutex *p){
17468 return p->nRef!=0 && p->owner==GetCurrentThreadId();
17470 static int winMutexNotheld2(sqlite3_mutex *p, DWORD tid){
17471 return p->nRef==0 || p->owner!=tid;
17473 static int winMutexNotheld(sqlite3_mutex *p){
17474 DWORD tid = GetCurrentThreadId();
17475 return winMutexNotheld2(p, tid);
17477 #endif
17481 ** Initialize and deinitialize the mutex subsystem.
17483 static sqlite3_mutex winMutex_staticMutexes[6] = {
17484 SQLITE3_MUTEX_INITIALIZER,
17485 SQLITE3_MUTEX_INITIALIZER,
17486 SQLITE3_MUTEX_INITIALIZER,
17487 SQLITE3_MUTEX_INITIALIZER,
17488 SQLITE3_MUTEX_INITIALIZER,
17489 SQLITE3_MUTEX_INITIALIZER
17491 static int winMutex_isInit = 0;
17492 /* As winMutexInit() and winMutexEnd() are called as part
17493 ** of the sqlite3_initialize and sqlite3_shutdown()
17494 ** processing, the "interlocked" magic is probably not
17495 ** strictly necessary.
17497 static long winMutex_lock = 0;
17499 static int winMutexInit(void){
17500 /* The first to increment to 1 does actual initialization */
17501 if( InterlockedCompareExchange(&winMutex_lock, 1, 0)==0 ){
17502 int i;
17503 for(i=0; i<ArraySize(winMutex_staticMutexes); i++){
17504 InitializeCriticalSection(&winMutex_staticMutexes[i].mutex);
17506 winMutex_isInit = 1;
17507 }else{
17508 /* Someone else is in the process of initing the static mutexes */
17509 while( !winMutex_isInit ){
17510 Sleep(1);
17513 return SQLITE_OK;
17516 static int winMutexEnd(void){
17517 /* The first to decrement to 0 does actual shutdown
17518 ** (which should be the last to shutdown.) */
17519 if( InterlockedCompareExchange(&winMutex_lock, 0, 1)==1 ){
17520 if( winMutex_isInit==1 ){
17521 int i;
17522 for(i=0; i<ArraySize(winMutex_staticMutexes); i++){
17523 DeleteCriticalSection(&winMutex_staticMutexes[i].mutex);
17525 winMutex_isInit = 0;
17528 return SQLITE_OK;
17532 ** The sqlite3_mutex_alloc() routine allocates a new
17533 ** mutex and returns a pointer to it. If it returns NULL
17534 ** that means that a mutex could not be allocated. SQLite
17535 ** will unwind its stack and return an error. The argument
17536 ** to sqlite3_mutex_alloc() is one of these integer constants:
17538 ** <ul>
17539 ** <li> SQLITE_MUTEX_FAST
17540 ** <li> SQLITE_MUTEX_RECURSIVE
17541 ** <li> SQLITE_MUTEX_STATIC_MASTER
17542 ** <li> SQLITE_MUTEX_STATIC_MEM
17543 ** <li> SQLITE_MUTEX_STATIC_MEM2
17544 ** <li> SQLITE_MUTEX_STATIC_PRNG
17545 ** <li> SQLITE_MUTEX_STATIC_LRU
17546 ** <li> SQLITE_MUTEX_STATIC_PMEM
17547 ** </ul>
17549 ** The first two constants cause sqlite3_mutex_alloc() to create
17550 ** a new mutex. The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
17551 ** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
17552 ** The mutex implementation does not need to make a distinction
17553 ** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
17554 ** not want to. But SQLite will only request a recursive mutex in
17555 ** cases where it really needs one. If a faster non-recursive mutex
17556 ** implementation is available on the host platform, the mutex subsystem
17557 ** might return such a mutex in response to SQLITE_MUTEX_FAST.
17559 ** The other allowed parameters to sqlite3_mutex_alloc() each return
17560 ** a pointer to a static preexisting mutex. Six static mutexes are
17561 ** used by the current version of SQLite. Future versions of SQLite
17562 ** may add additional static mutexes. Static mutexes are for internal
17563 ** use by SQLite only. Applications that use SQLite mutexes should
17564 ** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
17565 ** SQLITE_MUTEX_RECURSIVE.
17567 ** Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
17568 ** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
17569 ** returns a different mutex on every call. But for the static
17570 ** mutex types, the same mutex is returned on every call that has
17571 ** the same type number.
17573 static sqlite3_mutex *winMutexAlloc(int iType){
17574 sqlite3_mutex *p;
17576 switch( iType ){
17577 case SQLITE_MUTEX_FAST:
17578 case SQLITE_MUTEX_RECURSIVE: {
17579 p = sqlite3MallocZero( sizeof(*p) );
17580 if( p ){
17581 #ifdef SQLITE_DEBUG
17582 p->id = iType;
17583 #endif
17584 InitializeCriticalSection(&p->mutex);
17586 break;
17588 default: {
17589 assert( winMutex_isInit==1 );
17590 assert( iType-2 >= 0 );
17591 assert( iType-2 < ArraySize(winMutex_staticMutexes) );
17592 p = &winMutex_staticMutexes[iType-2];
17593 #ifdef SQLITE_DEBUG
17594 p->id = iType;
17595 #endif
17596 break;
17599 return p;
17604 ** This routine deallocates a previously
17605 ** allocated mutex. SQLite is careful to deallocate every
17606 ** mutex that it allocates.
17608 static void winMutexFree(sqlite3_mutex *p){
17609 assert( p );
17610 assert( p->nRef==0 && p->owner==0 );
17611 assert( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE );
17612 DeleteCriticalSection(&p->mutex);
17613 sqlite3_free(p);
17617 ** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
17618 ** to enter a mutex. If another thread is already within the mutex,
17619 ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
17620 ** SQLITE_BUSY. The sqlite3_mutex_try() interface returns SQLITE_OK
17621 ** upon successful entry. Mutexes created using SQLITE_MUTEX_RECURSIVE can
17622 ** be entered multiple times by the same thread. In such cases the,
17623 ** mutex must be exited an equal number of times before another thread
17624 ** can enter. If the same thread tries to enter any other kind of mutex
17625 ** more than once, the behavior is undefined.
17627 static void winMutexEnter(sqlite3_mutex *p){
17628 #ifdef SQLITE_DEBUG
17629 DWORD tid = GetCurrentThreadId();
17630 assert( p->id==SQLITE_MUTEX_RECURSIVE || winMutexNotheld2(p, tid) );
17631 #endif
17632 EnterCriticalSection(&p->mutex);
17633 #ifdef SQLITE_DEBUG
17634 assert( p->nRef>0 || p->owner==0 );
17635 p->owner = tid;
17636 p->nRef++;
17637 if( p->trace ){
17638 printf("enter mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
17640 #endif
17642 static int winMutexTry(sqlite3_mutex *p){
17643 #ifndef NDEBUG
17644 DWORD tid = GetCurrentThreadId();
17645 #endif
17646 int rc = SQLITE_BUSY;
17647 assert( p->id==SQLITE_MUTEX_RECURSIVE || winMutexNotheld2(p, tid) );
17649 ** The sqlite3_mutex_try() routine is very rarely used, and when it
17650 ** is used it is merely an optimization. So it is OK for it to always
17651 ** fail.
17653 ** The TryEnterCriticalSection() interface is only available on WinNT.
17654 ** And some windows compilers complain if you try to use it without
17655 ** first doing some #defines that prevent SQLite from building on Win98.
17656 ** For that reason, we will omit this optimization for now. See
17657 ** ticket #2685.
17659 #if 0
17660 if( mutexIsNT() && TryEnterCriticalSection(&p->mutex) ){
17661 p->owner = tid;
17662 p->nRef++;
17663 rc = SQLITE_OK;
17665 #else
17666 UNUSED_PARAMETER(p);
17667 #endif
17668 #ifdef SQLITE_DEBUG
17669 if( rc==SQLITE_OK && p->trace ){
17670 printf("try mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
17672 #endif
17673 return rc;
17677 ** The sqlite3_mutex_leave() routine exits a mutex that was
17678 ** previously entered by the same thread. The behavior
17679 ** is undefined if the mutex is not currently entered or
17680 ** is not currently allocated. SQLite will never do either.
17682 static void winMutexLeave(sqlite3_mutex *p){
17683 #ifndef NDEBUG
17684 DWORD tid = GetCurrentThreadId();
17685 assert( p->nRef>0 );
17686 assert( p->owner==tid );
17687 p->nRef--;
17688 if( p->nRef==0 ) p->owner = 0;
17689 assert( p->nRef==0 || p->id==SQLITE_MUTEX_RECURSIVE );
17690 #endif
17691 LeaveCriticalSection(&p->mutex);
17692 #ifdef SQLITE_DEBUG
17693 if( p->trace ){
17694 printf("leave mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
17696 #endif
17699 SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void){
17700 static const sqlite3_mutex_methods sMutex = {
17701 winMutexInit,
17702 winMutexEnd,
17703 winMutexAlloc,
17704 winMutexFree,
17705 winMutexEnter,
17706 winMutexTry,
17707 winMutexLeave,
17708 #ifdef SQLITE_DEBUG
17709 winMutexHeld,
17710 winMutexNotheld
17711 #else
17714 #endif
17717 return &sMutex;
17719 #endif /* SQLITE_MUTEX_W32 */
17721 /************** End of mutex_w32.c *******************************************/
17722 /************** Begin file malloc.c ******************************************/
17724 ** 2001 September 15
17726 ** The author disclaims copyright to this source code. In place of
17727 ** a legal notice, here is a blessing:
17729 ** May you do good and not evil.
17730 ** May you find forgiveness for yourself and forgive others.
17731 ** May you share freely, never taking more than you give.
17733 *************************************************************************
17735 ** Memory allocation functions used throughout sqlite.
17739 ** Attempt to release up to n bytes of non-essential memory currently
17740 ** held by SQLite. An example of non-essential memory is memory used to
17741 ** cache database pages that are not currently in use.
17743 SQLITE_API int sqlite3_release_memory(int n){
17744 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
17745 return sqlite3PcacheReleaseMemory(n);
17746 #else
17747 /* IMPLEMENTATION-OF: R-34391-24921 The sqlite3_release_memory() routine
17748 ** is a no-op returning zero if SQLite is not compiled with
17749 ** SQLITE_ENABLE_MEMORY_MANAGEMENT. */
17750 UNUSED_PARAMETER(n);
17751 return 0;
17752 #endif
17756 ** An instance of the following object records the location of
17757 ** each unused scratch buffer.
17759 typedef struct ScratchFreeslot {
17760 struct ScratchFreeslot *pNext; /* Next unused scratch buffer */
17761 } ScratchFreeslot;
17764 ** State information local to the memory allocation subsystem.
17766 static SQLITE_WSD struct Mem0Global {
17767 sqlite3_mutex *mutex; /* Mutex to serialize access */
17770 ** The alarm callback and its arguments. The mem0.mutex lock will
17771 ** be held while the callback is running. Recursive calls into
17772 ** the memory subsystem are allowed, but no new callbacks will be
17773 ** issued.
17775 sqlite3_int64 alarmThreshold;
17776 void (*alarmCallback)(void*, sqlite3_int64,int);
17777 void *alarmArg;
17780 ** Pointers to the end of sqlite3GlobalConfig.pScratch memory
17781 ** (so that a range test can be used to determine if an allocation
17782 ** being freed came from pScratch) and a pointer to the list of
17783 ** unused scratch allocations.
17785 void *pScratchEnd;
17786 ScratchFreeslot *pScratchFree;
17787 u32 nScratchFree;
17790 ** True if heap is nearly "full" where "full" is defined by the
17791 ** sqlite3_soft_heap_limit() setting.
17793 int nearlyFull;
17794 } mem0 = { 0, 0, 0, 0, 0, 0, 0, 0 };
17796 #define mem0 GLOBAL(struct Mem0Global, mem0)
17799 ** This routine runs when the memory allocator sees that the
17800 ** total memory allocation is about to exceed the soft heap
17801 ** limit.
17803 static void softHeapLimitEnforcer(
17804 void *NotUsed,
17805 sqlite3_int64 NotUsed2,
17806 int allocSize
17808 UNUSED_PARAMETER2(NotUsed, NotUsed2);
17809 sqlite3_release_memory(allocSize);
17813 ** Change the alarm callback
17815 static int sqlite3MemoryAlarm(
17816 void(*xCallback)(void *pArg, sqlite3_int64 used,int N),
17817 void *pArg,
17818 sqlite3_int64 iThreshold
17820 int nUsed;
17821 sqlite3_mutex_enter(mem0.mutex);
17822 mem0.alarmCallback = xCallback;
17823 mem0.alarmArg = pArg;
17824 mem0.alarmThreshold = iThreshold;
17825 nUsed = sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED);
17826 mem0.nearlyFull = (iThreshold>0 && iThreshold<=nUsed);
17827 sqlite3_mutex_leave(mem0.mutex);
17828 return SQLITE_OK;
17831 #ifndef SQLITE_OMIT_DEPRECATED
17833 ** Deprecated external interface. Internal/core SQLite code
17834 ** should call sqlite3MemoryAlarm.
17836 SQLITE_API int sqlite3_memory_alarm(
17837 void(*xCallback)(void *pArg, sqlite3_int64 used,int N),
17838 void *pArg,
17839 sqlite3_int64 iThreshold
17841 return sqlite3MemoryAlarm(xCallback, pArg, iThreshold);
17843 #endif
17846 ** Set the soft heap-size limit for the library. Passing a zero or
17847 ** negative value indicates no limit.
17849 SQLITE_API sqlite3_int64 sqlite3_soft_heap_limit64(sqlite3_int64 n){
17850 sqlite3_int64 priorLimit;
17851 sqlite3_int64 excess;
17852 #ifndef SQLITE_OMIT_AUTOINIT
17853 sqlite3_initialize();
17854 #endif
17855 sqlite3_mutex_enter(mem0.mutex);
17856 priorLimit = mem0.alarmThreshold;
17857 sqlite3_mutex_leave(mem0.mutex);
17858 if( n<0 ) return priorLimit;
17859 if( n>0 ){
17860 sqlite3MemoryAlarm(softHeapLimitEnforcer, 0, n);
17861 }else{
17862 sqlite3MemoryAlarm(0, 0, 0);
17864 excess = sqlite3_memory_used() - n;
17865 if( excess>0 ) sqlite3_release_memory((int)(excess & 0x7fffffff));
17866 return priorLimit;
17868 SQLITE_API void sqlite3_soft_heap_limit(int n){
17869 if( n<0 ) n = 0;
17870 sqlite3_soft_heap_limit64(n);
17874 ** Initialize the memory allocation subsystem.
17876 SQLITE_PRIVATE int sqlite3MallocInit(void){
17877 if( sqlite3GlobalConfig.m.xMalloc==0 ){
17878 sqlite3MemSetDefault();
17880 memset(&mem0, 0, sizeof(mem0));
17881 if( sqlite3GlobalConfig.bCoreMutex ){
17882 mem0.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
17884 if( sqlite3GlobalConfig.pScratch && sqlite3GlobalConfig.szScratch>=100
17885 && sqlite3GlobalConfig.nScratch>0 ){
17886 int i, n, sz;
17887 ScratchFreeslot *pSlot;
17888 sz = ROUNDDOWN8(sqlite3GlobalConfig.szScratch);
17889 sqlite3GlobalConfig.szScratch = sz;
17890 pSlot = (ScratchFreeslot*)sqlite3GlobalConfig.pScratch;
17891 n = sqlite3GlobalConfig.nScratch;
17892 mem0.pScratchFree = pSlot;
17893 mem0.nScratchFree = n;
17894 for(i=0; i<n-1; i++){
17895 pSlot->pNext = (ScratchFreeslot*)(sz+(char*)pSlot);
17896 pSlot = pSlot->pNext;
17898 pSlot->pNext = 0;
17899 mem0.pScratchEnd = (void*)&pSlot[1];
17900 }else{
17901 mem0.pScratchEnd = 0;
17902 sqlite3GlobalConfig.pScratch = 0;
17903 sqlite3GlobalConfig.szScratch = 0;
17904 sqlite3GlobalConfig.nScratch = 0;
17906 if( sqlite3GlobalConfig.pPage==0 || sqlite3GlobalConfig.szPage<512
17907 || sqlite3GlobalConfig.nPage<1 ){
17908 sqlite3GlobalConfig.pPage = 0;
17909 sqlite3GlobalConfig.szPage = 0;
17910 sqlite3GlobalConfig.nPage = 0;
17912 return sqlite3GlobalConfig.m.xInit(sqlite3GlobalConfig.m.pAppData);
17916 ** Return true if the heap is currently under memory pressure - in other
17917 ** words if the amount of heap used is close to the limit set by
17918 ** sqlite3_soft_heap_limit().
17920 SQLITE_PRIVATE int sqlite3HeapNearlyFull(void){
17921 return mem0.nearlyFull;
17925 ** Deinitialize the memory allocation subsystem.
17927 SQLITE_PRIVATE void sqlite3MallocEnd(void){
17928 if( sqlite3GlobalConfig.m.xShutdown ){
17929 sqlite3GlobalConfig.m.xShutdown(sqlite3GlobalConfig.m.pAppData);
17931 memset(&mem0, 0, sizeof(mem0));
17935 ** Return the amount of memory currently checked out.
17937 SQLITE_API sqlite3_int64 sqlite3_memory_used(void){
17938 int n, mx;
17939 sqlite3_int64 res;
17940 sqlite3_status(SQLITE_STATUS_MEMORY_USED, &n, &mx, 0);
17941 res = (sqlite3_int64)n; /* Work around bug in Borland C. Ticket #3216 */
17942 return res;
17946 ** Return the maximum amount of memory that has ever been
17947 ** checked out since either the beginning of this process
17948 ** or since the most recent reset.
17950 SQLITE_API sqlite3_int64 sqlite3_memory_highwater(int resetFlag){
17951 int n, mx;
17952 sqlite3_int64 res;
17953 sqlite3_status(SQLITE_STATUS_MEMORY_USED, &n, &mx, resetFlag);
17954 res = (sqlite3_int64)mx; /* Work around bug in Borland C. Ticket #3216 */
17955 return res;
17959 ** Trigger the alarm
17961 static void sqlite3MallocAlarm(int nByte){
17962 void (*xCallback)(void*,sqlite3_int64,int);
17963 sqlite3_int64 nowUsed;
17964 void *pArg;
17965 if( mem0.alarmCallback==0 ) return;
17966 xCallback = mem0.alarmCallback;
17967 nowUsed = sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED);
17968 pArg = mem0.alarmArg;
17969 mem0.alarmCallback = 0;
17970 sqlite3_mutex_leave(mem0.mutex);
17971 xCallback(pArg, nowUsed, nByte);
17972 sqlite3_mutex_enter(mem0.mutex);
17973 mem0.alarmCallback = xCallback;
17974 mem0.alarmArg = pArg;
17978 ** Do a memory allocation with statistics and alarms. Assume the
17979 ** lock is already held.
17981 static int mallocWithAlarm(int n, void **pp){
17982 int nFull;
17983 void *p;
17984 assert( sqlite3_mutex_held(mem0.mutex) );
17985 nFull = sqlite3GlobalConfig.m.xRoundup(n);
17986 sqlite3StatusSet(SQLITE_STATUS_MALLOC_SIZE, n);
17987 if( mem0.alarmCallback!=0 ){
17988 int nUsed = sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED);
17989 if( nUsed+nFull >= mem0.alarmThreshold ){
17990 mem0.nearlyFull = 1;
17991 sqlite3MallocAlarm(nFull);
17992 }else{
17993 mem0.nearlyFull = 0;
17996 p = sqlite3GlobalConfig.m.xMalloc(nFull);
17997 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
17998 if( p==0 && mem0.alarmCallback ){
17999 sqlite3MallocAlarm(nFull);
18000 p = sqlite3GlobalConfig.m.xMalloc(nFull);
18002 #endif
18003 if( p ){
18004 nFull = sqlite3MallocSize(p);
18005 sqlite3StatusAdd(SQLITE_STATUS_MEMORY_USED, nFull);
18006 sqlite3StatusAdd(SQLITE_STATUS_MALLOC_COUNT, 1);
18008 *pp = p;
18009 return nFull;
18013 ** Allocate memory. This routine is like sqlite3_malloc() except that it
18014 ** assumes the memory subsystem has already been initialized.
18016 SQLITE_PRIVATE void *sqlite3Malloc(int n){
18017 void *p;
18018 if( n<=0 /* IMP: R-65312-04917 */
18019 || n>=0x7fffff00
18021 /* A memory allocation of a number of bytes which is near the maximum
18022 ** signed integer value might cause an integer overflow inside of the
18023 ** xMalloc(). Hence we limit the maximum size to 0x7fffff00, giving
18024 ** 255 bytes of overhead. SQLite itself will never use anything near
18025 ** this amount. The only way to reach the limit is with sqlite3_malloc() */
18026 p = 0;
18027 }else if( sqlite3GlobalConfig.bMemstat ){
18028 sqlite3_mutex_enter(mem0.mutex);
18029 mallocWithAlarm(n, &p);
18030 sqlite3_mutex_leave(mem0.mutex);
18031 }else{
18032 p = sqlite3GlobalConfig.m.xMalloc(n);
18034 assert( EIGHT_BYTE_ALIGNMENT(p) ); /* IMP: R-04675-44850 */
18035 return p;
18039 ** This version of the memory allocation is for use by the application.
18040 ** First make sure the memory subsystem is initialized, then do the
18041 ** allocation.
18043 SQLITE_API void *sqlite3_malloc(int n){
18044 #ifndef SQLITE_OMIT_AUTOINIT
18045 if( sqlite3_initialize() ) return 0;
18046 #endif
18047 return sqlite3Malloc(n);
18051 ** Each thread may only have a single outstanding allocation from
18052 ** xScratchMalloc(). We verify this constraint in the single-threaded
18053 ** case by setting scratchAllocOut to 1 when an allocation
18054 ** is outstanding clearing it when the allocation is freed.
18056 #if SQLITE_THREADSAFE==0 && !defined(NDEBUG)
18057 static int scratchAllocOut = 0;
18058 #endif
18062 ** Allocate memory that is to be used and released right away.
18063 ** This routine is similar to alloca() in that it is not intended
18064 ** for situations where the memory might be held long-term. This
18065 ** routine is intended to get memory to old large transient data
18066 ** structures that would not normally fit on the stack of an
18067 ** embedded processor.
18069 SQLITE_PRIVATE void *sqlite3ScratchMalloc(int n){
18070 void *p;
18071 assert( n>0 );
18073 sqlite3_mutex_enter(mem0.mutex);
18074 if( mem0.nScratchFree && sqlite3GlobalConfig.szScratch>=n ){
18075 p = mem0.pScratchFree;
18076 mem0.pScratchFree = mem0.pScratchFree->pNext;
18077 mem0.nScratchFree--;
18078 sqlite3StatusAdd(SQLITE_STATUS_SCRATCH_USED, 1);
18079 sqlite3StatusSet(SQLITE_STATUS_SCRATCH_SIZE, n);
18080 sqlite3_mutex_leave(mem0.mutex);
18081 }else{
18082 if( sqlite3GlobalConfig.bMemstat ){
18083 sqlite3StatusSet(SQLITE_STATUS_SCRATCH_SIZE, n);
18084 n = mallocWithAlarm(n, &p);
18085 if( p ) sqlite3StatusAdd(SQLITE_STATUS_SCRATCH_OVERFLOW, n);
18086 sqlite3_mutex_leave(mem0.mutex);
18087 }else{
18088 sqlite3_mutex_leave(mem0.mutex);
18089 p = sqlite3GlobalConfig.m.xMalloc(n);
18091 sqlite3MemdebugSetType(p, MEMTYPE_SCRATCH);
18093 assert( sqlite3_mutex_notheld(mem0.mutex) );
18096 #if SQLITE_THREADSAFE==0 && !defined(NDEBUG)
18097 /* Verify that no more than two scratch allocations per thread
18098 ** are outstanding at one time. (This is only checked in the
18099 ** single-threaded case since checking in the multi-threaded case
18100 ** would be much more complicated.) */
18101 assert( scratchAllocOut<=1 );
18102 if( p ) scratchAllocOut++;
18103 #endif
18105 return p;
18107 SQLITE_PRIVATE void sqlite3ScratchFree(void *p){
18108 if( p ){
18110 #if SQLITE_THREADSAFE==0 && !defined(NDEBUG)
18111 /* Verify that no more than two scratch allocation per thread
18112 ** is outstanding at one time. (This is only checked in the
18113 ** single-threaded case since checking in the multi-threaded case
18114 ** would be much more complicated.) */
18115 assert( scratchAllocOut>=1 && scratchAllocOut<=2 );
18116 scratchAllocOut--;
18117 #endif
18119 if( p>=sqlite3GlobalConfig.pScratch && p<mem0.pScratchEnd ){
18120 /* Release memory from the SQLITE_CONFIG_SCRATCH allocation */
18121 ScratchFreeslot *pSlot;
18122 pSlot = (ScratchFreeslot*)p;
18123 sqlite3_mutex_enter(mem0.mutex);
18124 pSlot->pNext = mem0.pScratchFree;
18125 mem0.pScratchFree = pSlot;
18126 mem0.nScratchFree++;
18127 assert( mem0.nScratchFree <= (u32)sqlite3GlobalConfig.nScratch );
18128 sqlite3StatusAdd(SQLITE_STATUS_SCRATCH_USED, -1);
18129 sqlite3_mutex_leave(mem0.mutex);
18130 }else{
18131 /* Release memory back to the heap */
18132 assert( sqlite3MemdebugHasType(p, MEMTYPE_SCRATCH) );
18133 assert( sqlite3MemdebugNoType(p, ~MEMTYPE_SCRATCH) );
18134 sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
18135 if( sqlite3GlobalConfig.bMemstat ){
18136 int iSize = sqlite3MallocSize(p);
18137 sqlite3_mutex_enter(mem0.mutex);
18138 sqlite3StatusAdd(SQLITE_STATUS_SCRATCH_OVERFLOW, -iSize);
18139 sqlite3StatusAdd(SQLITE_STATUS_MEMORY_USED, -iSize);
18140 sqlite3StatusAdd(SQLITE_STATUS_MALLOC_COUNT, -1);
18141 sqlite3GlobalConfig.m.xFree(p);
18142 sqlite3_mutex_leave(mem0.mutex);
18143 }else{
18144 sqlite3GlobalConfig.m.xFree(p);
18151 ** TRUE if p is a lookaside memory allocation from db
18153 #ifndef SQLITE_OMIT_LOOKASIDE
18154 static int isLookaside(sqlite3 *db, void *p){
18155 return p && p>=db->lookaside.pStart && p<db->lookaside.pEnd;
18157 #else
18158 #define isLookaside(A,B) 0
18159 #endif
18162 ** Return the size of a memory allocation previously obtained from
18163 ** sqlite3Malloc() or sqlite3_malloc().
18165 SQLITE_PRIVATE int sqlite3MallocSize(void *p){
18166 assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) );
18167 assert( sqlite3MemdebugNoType(p, MEMTYPE_DB) );
18168 return sqlite3GlobalConfig.m.xSize(p);
18170 SQLITE_PRIVATE int sqlite3DbMallocSize(sqlite3 *db, void *p){
18171 assert( db==0 || sqlite3_mutex_held(db->mutex) );
18172 if( db && isLookaside(db, p) ){
18173 return db->lookaside.sz;
18174 }else{
18175 assert( sqlite3MemdebugHasType(p, MEMTYPE_DB) );
18176 assert( sqlite3MemdebugHasType(p, MEMTYPE_LOOKASIDE|MEMTYPE_HEAP) );
18177 assert( db!=0 || sqlite3MemdebugNoType(p, MEMTYPE_LOOKASIDE) );
18178 return sqlite3GlobalConfig.m.xSize(p);
18183 ** Free memory previously obtained from sqlite3Malloc().
18185 SQLITE_API void sqlite3_free(void *p){
18186 if( p==0 ) return; /* IMP: R-49053-54554 */
18187 assert( sqlite3MemdebugNoType(p, MEMTYPE_DB) );
18188 assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) );
18189 if( sqlite3GlobalConfig.bMemstat ){
18190 sqlite3_mutex_enter(mem0.mutex);
18191 sqlite3StatusAdd(SQLITE_STATUS_MEMORY_USED, -sqlite3MallocSize(p));
18192 sqlite3StatusAdd(SQLITE_STATUS_MALLOC_COUNT, -1);
18193 sqlite3GlobalConfig.m.xFree(p);
18194 sqlite3_mutex_leave(mem0.mutex);
18195 }else{
18196 sqlite3GlobalConfig.m.xFree(p);
18201 ** Free memory that might be associated with a particular database
18202 ** connection.
18204 SQLITE_PRIVATE void sqlite3DbFree(sqlite3 *db, void *p){
18205 assert( db==0 || sqlite3_mutex_held(db->mutex) );
18206 if( db ){
18207 if( db->pnBytesFreed ){
18208 *db->pnBytesFreed += sqlite3DbMallocSize(db, p);
18209 return;
18211 if( isLookaside(db, p) ){
18212 LookasideSlot *pBuf = (LookasideSlot*)p;
18213 pBuf->pNext = db->lookaside.pFree;
18214 db->lookaside.pFree = pBuf;
18215 db->lookaside.nOut--;
18216 return;
18219 assert( sqlite3MemdebugHasType(p, MEMTYPE_DB) );
18220 assert( sqlite3MemdebugHasType(p, MEMTYPE_LOOKASIDE|MEMTYPE_HEAP) );
18221 assert( db!=0 || sqlite3MemdebugNoType(p, MEMTYPE_LOOKASIDE) );
18222 sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
18223 sqlite3_free(p);
18227 ** Change the size of an existing memory allocation
18229 SQLITE_PRIVATE void *sqlite3Realloc(void *pOld, int nBytes){
18230 int nOld, nNew;
18231 void *pNew;
18232 if( pOld==0 ){
18233 return sqlite3Malloc(nBytes); /* IMP: R-28354-25769 */
18235 if( nBytes<=0 ){
18236 sqlite3_free(pOld); /* IMP: R-31593-10574 */
18237 return 0;
18239 if( nBytes>=0x7fffff00 ){
18240 /* The 0x7ffff00 limit term is explained in comments on sqlite3Malloc() */
18241 return 0;
18243 nOld = sqlite3MallocSize(pOld);
18244 /* IMPLEMENTATION-OF: R-46199-30249 SQLite guarantees that the second
18245 ** argument to xRealloc is always a value returned by a prior call to
18246 ** xRoundup. */
18247 nNew = sqlite3GlobalConfig.m.xRoundup(nBytes);
18248 if( nOld==nNew ){
18249 pNew = pOld;
18250 }else if( sqlite3GlobalConfig.bMemstat ){
18251 sqlite3_mutex_enter(mem0.mutex);
18252 sqlite3StatusSet(SQLITE_STATUS_MALLOC_SIZE, nBytes);
18253 if( sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED)+nNew-nOld >=
18254 mem0.alarmThreshold ){
18255 sqlite3MallocAlarm(nNew-nOld);
18257 assert( sqlite3MemdebugHasType(pOld, MEMTYPE_HEAP) );
18258 assert( sqlite3MemdebugNoType(pOld, ~MEMTYPE_HEAP) );
18259 pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew);
18260 if( pNew==0 && mem0.alarmCallback ){
18261 sqlite3MallocAlarm(nBytes);
18262 pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew);
18264 if( pNew ){
18265 nNew = sqlite3MallocSize(pNew);
18266 sqlite3StatusAdd(SQLITE_STATUS_MEMORY_USED, nNew-nOld);
18268 sqlite3_mutex_leave(mem0.mutex);
18269 }else{
18270 pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew);
18272 assert( EIGHT_BYTE_ALIGNMENT(pNew) ); /* IMP: R-04675-44850 */
18273 return pNew;
18277 ** The public interface to sqlite3Realloc. Make sure that the memory
18278 ** subsystem is initialized prior to invoking sqliteRealloc.
18280 SQLITE_API void *sqlite3_realloc(void *pOld, int n){
18281 #ifndef SQLITE_OMIT_AUTOINIT
18282 if( sqlite3_initialize() ) return 0;
18283 #endif
18284 return sqlite3Realloc(pOld, n);
18289 ** Allocate and zero memory.
18291 SQLITE_PRIVATE void *sqlite3MallocZero(int n){
18292 void *p = sqlite3Malloc(n);
18293 if( p ){
18294 memset(p, 0, n);
18296 return p;
18300 ** Allocate and zero memory. If the allocation fails, make
18301 ** the mallocFailed flag in the connection pointer.
18303 SQLITE_PRIVATE void *sqlite3DbMallocZero(sqlite3 *db, int n){
18304 void *p = sqlite3DbMallocRaw(db, n);
18305 if( p ){
18306 memset(p, 0, n);
18308 return p;
18312 ** Allocate and zero memory. If the allocation fails, make
18313 ** the mallocFailed flag in the connection pointer.
18315 ** If db!=0 and db->mallocFailed is true (indicating a prior malloc
18316 ** failure on the same database connection) then always return 0.
18317 ** Hence for a particular database connection, once malloc starts
18318 ** failing, it fails consistently until mallocFailed is reset.
18319 ** This is an important assumption. There are many places in the
18320 ** code that do things like this:
18322 ** int *a = (int*)sqlite3DbMallocRaw(db, 100);
18323 ** int *b = (int*)sqlite3DbMallocRaw(db, 200);
18324 ** if( b ) a[10] = 9;
18326 ** In other words, if a subsequent malloc (ex: "b") worked, it is assumed
18327 ** that all prior mallocs (ex: "a") worked too.
18329 SQLITE_PRIVATE void *sqlite3DbMallocRaw(sqlite3 *db, int n){
18330 void *p;
18331 assert( db==0 || sqlite3_mutex_held(db->mutex) );
18332 assert( db==0 || db->pnBytesFreed==0 );
18333 #ifndef SQLITE_OMIT_LOOKASIDE
18334 if( db ){
18335 LookasideSlot *pBuf;
18336 if( db->mallocFailed ){
18337 return 0;
18339 if( db->lookaside.bEnabled ){
18340 if( n>db->lookaside.sz ){
18341 db->lookaside.anStat[1]++;
18342 }else if( (pBuf = db->lookaside.pFree)==0 ){
18343 db->lookaside.anStat[2]++;
18344 }else{
18345 db->lookaside.pFree = pBuf->pNext;
18346 db->lookaside.nOut++;
18347 db->lookaside.anStat[0]++;
18348 if( db->lookaside.nOut>db->lookaside.mxOut ){
18349 db->lookaside.mxOut = db->lookaside.nOut;
18351 return (void*)pBuf;
18355 #else
18356 if( db && db->mallocFailed ){
18357 return 0;
18359 #endif
18360 p = sqlite3Malloc(n);
18361 if( !p && db ){
18362 db->mallocFailed = 1;
18364 sqlite3MemdebugSetType(p, MEMTYPE_DB |
18365 ((db && db->lookaside.bEnabled) ? MEMTYPE_LOOKASIDE : MEMTYPE_HEAP));
18366 return p;
18370 ** Resize the block of memory pointed to by p to n bytes. If the
18371 ** resize fails, set the mallocFailed flag in the connection object.
18373 SQLITE_PRIVATE void *sqlite3DbRealloc(sqlite3 *db, void *p, int n){
18374 void *pNew = 0;
18375 assert( db!=0 );
18376 assert( sqlite3_mutex_held(db->mutex) );
18377 if( db->mallocFailed==0 ){
18378 if( p==0 ){
18379 return sqlite3DbMallocRaw(db, n);
18381 if( isLookaside(db, p) ){
18382 if( n<=db->lookaside.sz ){
18383 return p;
18385 pNew = sqlite3DbMallocRaw(db, n);
18386 if( pNew ){
18387 memcpy(pNew, p, db->lookaside.sz);
18388 sqlite3DbFree(db, p);
18390 }else{
18391 assert( sqlite3MemdebugHasType(p, MEMTYPE_DB) );
18392 assert( sqlite3MemdebugHasType(p, MEMTYPE_LOOKASIDE|MEMTYPE_HEAP) );
18393 sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
18394 pNew = sqlite3_realloc(p, n);
18395 if( !pNew ){
18396 sqlite3MemdebugSetType(p, MEMTYPE_DB|MEMTYPE_HEAP);
18397 db->mallocFailed = 1;
18399 sqlite3MemdebugSetType(pNew, MEMTYPE_DB |
18400 (db->lookaside.bEnabled ? MEMTYPE_LOOKASIDE : MEMTYPE_HEAP));
18403 return pNew;
18407 ** Attempt to reallocate p. If the reallocation fails, then free p
18408 ** and set the mallocFailed flag in the database connection.
18410 SQLITE_PRIVATE void *sqlite3DbReallocOrFree(sqlite3 *db, void *p, int n){
18411 void *pNew;
18412 pNew = sqlite3DbRealloc(db, p, n);
18413 if( !pNew ){
18414 sqlite3DbFree(db, p);
18416 return pNew;
18420 ** Make a copy of a string in memory obtained from sqliteMalloc(). These
18421 ** functions call sqlite3MallocRaw() directly instead of sqliteMalloc(). This
18422 ** is because when memory debugging is turned on, these two functions are
18423 ** called via macros that record the current file and line number in the
18424 ** ThreadData structure.
18426 SQLITE_PRIVATE char *sqlite3DbStrDup(sqlite3 *db, const char *z){
18427 char *zNew;
18428 size_t n;
18429 if( z==0 ){
18430 return 0;
18432 n = sqlite3Strlen30(z) + 1;
18433 assert( (n&0x7fffffff)==n );
18434 zNew = sqlite3DbMallocRaw(db, (int)n);
18435 if( zNew ){
18436 memcpy(zNew, z, n);
18438 return zNew;
18440 SQLITE_PRIVATE char *sqlite3DbStrNDup(sqlite3 *db, const char *z, int n){
18441 char *zNew;
18442 if( z==0 ){
18443 return 0;
18445 assert( (n&0x7fffffff)==n );
18446 zNew = sqlite3DbMallocRaw(db, n+1);
18447 if( zNew ){
18448 memcpy(zNew, z, n);
18449 zNew[n] = 0;
18451 return zNew;
18455 ** Create a string from the zFromat argument and the va_list that follows.
18456 ** Store the string in memory obtained from sqliteMalloc() and make *pz
18457 ** point to that string.
18459 SQLITE_PRIVATE void sqlite3SetString(char **pz, sqlite3 *db, const char *zFormat, ...){
18460 va_list ap;
18461 char *z;
18463 va_start(ap, zFormat);
18464 z = sqlite3VMPrintf(db, zFormat, ap);
18465 va_end(ap);
18466 sqlite3DbFree(db, *pz);
18467 *pz = z;
18472 ** This function must be called before exiting any API function (i.e.
18473 ** returning control to the user) that has called sqlite3_malloc or
18474 ** sqlite3_realloc.
18476 ** The returned value is normally a copy of the second argument to this
18477 ** function. However, if a malloc() failure has occurred since the previous
18478 ** invocation SQLITE_NOMEM is returned instead.
18480 ** If the first argument, db, is not NULL and a malloc() error has occurred,
18481 ** then the connection error-code (the value returned by sqlite3_errcode())
18482 ** is set to SQLITE_NOMEM.
18484 SQLITE_PRIVATE int sqlite3ApiExit(sqlite3* db, int rc){
18485 /* If the db handle is not NULL, then we must hold the connection handle
18486 ** mutex here. Otherwise the read (and possible write) of db->mallocFailed
18487 ** is unsafe, as is the call to sqlite3Error().
18489 assert( !db || sqlite3_mutex_held(db->mutex) );
18490 if( db && (db->mallocFailed || rc==SQLITE_IOERR_NOMEM) ){
18491 sqlite3Error(db, SQLITE_NOMEM, 0);
18492 db->mallocFailed = 0;
18493 rc = SQLITE_NOMEM;
18495 return rc & (db ? db->errMask : 0xff);
18498 /************** End of malloc.c **********************************************/
18499 /************** Begin file printf.c ******************************************/
18501 ** The "printf" code that follows dates from the 1980's. It is in
18502 ** the public domain. The original comments are included here for
18503 ** completeness. They are very out-of-date but might be useful as
18504 ** an historical reference. Most of the "enhancements" have been backed
18505 ** out so that the functionality is now the same as standard printf().
18507 **************************************************************************
18509 ** The following modules is an enhanced replacement for the "printf" subroutines
18510 ** found in the standard C library. The following enhancements are
18511 ** supported:
18513 ** + Additional functions. The standard set of "printf" functions
18514 ** includes printf, fprintf, sprintf, vprintf, vfprintf, and
18515 ** vsprintf. This module adds the following:
18517 ** * snprintf -- Works like sprintf, but has an extra argument
18518 ** which is the size of the buffer written to.
18520 ** * mprintf -- Similar to sprintf. Writes output to memory
18521 ** obtained from malloc.
18523 ** * xprintf -- Calls a function to dispose of output.
18525 ** * nprintf -- No output, but returns the number of characters
18526 ** that would have been output by printf.
18528 ** * A v- version (ex: vsnprintf) of every function is also
18529 ** supplied.
18531 ** + A few extensions to the formatting notation are supported:
18533 ** * The "=" flag (similar to "-") causes the output to be
18534 ** be centered in the appropriately sized field.
18536 ** * The %b field outputs an integer in binary notation.
18538 ** * The %c field now accepts a precision. The character output
18539 ** is repeated by the number of times the precision specifies.
18541 ** * The %' field works like %c, but takes as its character the
18542 ** next character of the format string, instead of the next
18543 ** argument. For example, printf("%.78'-") prints 78 minus
18544 ** signs, the same as printf("%.78c",'-').
18546 ** + When compiled using GCC on a SPARC, this version of printf is
18547 ** faster than the library printf for SUN OS 4.1.
18549 ** + All functions are fully reentrant.
18554 ** Conversion types fall into various categories as defined by the
18555 ** following enumeration.
18557 #define etRADIX 1 /* Integer types. %d, %x, %o, and so forth */
18558 #define etFLOAT 2 /* Floating point. %f */
18559 #define etEXP 3 /* Exponentional notation. %e and %E */
18560 #define etGENERIC 4 /* Floating or exponential, depending on exponent. %g */
18561 #define etSIZE 5 /* Return number of characters processed so far. %n */
18562 #define etSTRING 6 /* Strings. %s */
18563 #define etDYNSTRING 7 /* Dynamically allocated strings. %z */
18564 #define etPERCENT 8 /* Percent symbol. %% */
18565 #define etCHARX 9 /* Characters. %c */
18566 /* The rest are extensions, not normally found in printf() */
18567 #define etSQLESCAPE 10 /* Strings with '\'' doubled. %q */
18568 #define etSQLESCAPE2 11 /* Strings with '\'' doubled and enclosed in '',
18569 NULL pointers replaced by SQL NULL. %Q */
18570 #define etTOKEN 12 /* a pointer to a Token structure */
18571 #define etSRCLIST 13 /* a pointer to a SrcList */
18572 #define etPOINTER 14 /* The %p conversion */
18573 #define etSQLESCAPE3 15 /* %w -> Strings with '\"' doubled */
18574 #define etORDINAL 16 /* %r -> 1st, 2nd, 3rd, 4th, etc. English only */
18576 #define etINVALID 0 /* Any unrecognized conversion type */
18580 ** An "etByte" is an 8-bit unsigned value.
18582 typedef unsigned char etByte;
18585 ** Each builtin conversion character (ex: the 'd' in "%d") is described
18586 ** by an instance of the following structure
18588 typedef struct et_info { /* Information about each format field */
18589 char fmttype; /* The format field code letter */
18590 etByte base; /* The base for radix conversion */
18591 etByte flags; /* One or more of FLAG_ constants below */
18592 etByte type; /* Conversion paradigm */
18593 etByte charset; /* Offset into aDigits[] of the digits string */
18594 etByte prefix; /* Offset into aPrefix[] of the prefix string */
18595 } et_info;
18598 ** Allowed values for et_info.flags
18600 #define FLAG_SIGNED 1 /* True if the value to convert is signed */
18601 #define FLAG_INTERN 2 /* True if for internal use only */
18602 #define FLAG_STRING 4 /* Allow infinity precision */
18606 ** The following table is searched linearly, so it is good to put the
18607 ** most frequently used conversion types first.
18609 static const char aDigits[] = "0123456789ABCDEF0123456789abcdef";
18610 static const char aPrefix[] = "-x0\000X0";
18611 static const et_info fmtinfo[] = {
18612 { 'd', 10, 1, etRADIX, 0, 0 },
18613 { 's', 0, 4, etSTRING, 0, 0 },
18614 { 'g', 0, 1, etGENERIC, 30, 0 },
18615 { 'z', 0, 4, etDYNSTRING, 0, 0 },
18616 { 'q', 0, 4, etSQLESCAPE, 0, 0 },
18617 { 'Q', 0, 4, etSQLESCAPE2, 0, 0 },
18618 { 'w', 0, 4, etSQLESCAPE3, 0, 0 },
18619 { 'c', 0, 0, etCHARX, 0, 0 },
18620 { 'o', 8, 0, etRADIX, 0, 2 },
18621 { 'u', 10, 0, etRADIX, 0, 0 },
18622 { 'x', 16, 0, etRADIX, 16, 1 },
18623 { 'X', 16, 0, etRADIX, 0, 4 },
18624 #ifndef SQLITE_OMIT_FLOATING_POINT
18625 { 'f', 0, 1, etFLOAT, 0, 0 },
18626 { 'e', 0, 1, etEXP, 30, 0 },
18627 { 'E', 0, 1, etEXP, 14, 0 },
18628 { 'G', 0, 1, etGENERIC, 14, 0 },
18629 #endif
18630 { 'i', 10, 1, etRADIX, 0, 0 },
18631 { 'n', 0, 0, etSIZE, 0, 0 },
18632 { '%', 0, 0, etPERCENT, 0, 0 },
18633 { 'p', 16, 0, etPOINTER, 0, 1 },
18635 /* All the rest have the FLAG_INTERN bit set and are thus for internal
18636 ** use only */
18637 { 'T', 0, 2, etTOKEN, 0, 0 },
18638 { 'S', 0, 2, etSRCLIST, 0, 0 },
18639 { 'r', 10, 3, etORDINAL, 0, 0 },
18643 ** If SQLITE_OMIT_FLOATING_POINT is defined, then none of the floating point
18644 ** conversions will work.
18646 #ifndef SQLITE_OMIT_FLOATING_POINT
18648 ** "*val" is a double such that 0.1 <= *val < 10.0
18649 ** Return the ascii code for the leading digit of *val, then
18650 ** multiply "*val" by 10.0 to renormalize.
18652 ** Example:
18653 ** input: *val = 3.14159
18654 ** output: *val = 1.4159 function return = '3'
18656 ** The counter *cnt is incremented each time. After counter exceeds
18657 ** 16 (the number of significant digits in a 64-bit float) '0' is
18658 ** always returned.
18660 static char et_getdigit(LONGDOUBLE_TYPE *val, int *cnt){
18661 int digit;
18662 LONGDOUBLE_TYPE d;
18663 if( (*cnt)++ >= 16 ) return '0';
18664 digit = (int)*val;
18665 d = digit;
18666 digit += '0';
18667 *val = (*val - d)*10.0;
18668 return (char)digit;
18670 #endif /* SQLITE_OMIT_FLOATING_POINT */
18673 ** Append N space characters to the given string buffer.
18675 static void appendSpace(StrAccum *pAccum, int N){
18676 static const char zSpaces[] = " ";
18677 while( N>=(int)sizeof(zSpaces)-1 ){
18678 sqlite3StrAccumAppend(pAccum, zSpaces, sizeof(zSpaces)-1);
18679 N -= sizeof(zSpaces)-1;
18681 if( N>0 ){
18682 sqlite3StrAccumAppend(pAccum, zSpaces, N);
18687 ** On machines with a small stack size, you can redefine the
18688 ** SQLITE_PRINT_BUF_SIZE to be less than 350.
18690 #ifndef SQLITE_PRINT_BUF_SIZE
18691 # if defined(SQLITE_SMALL_STACK)
18692 # define SQLITE_PRINT_BUF_SIZE 50
18693 # else
18694 # define SQLITE_PRINT_BUF_SIZE 350
18695 # endif
18696 #endif
18697 #define etBUFSIZE SQLITE_PRINT_BUF_SIZE /* Size of the output buffer */
18700 ** The root program. All variations call this core.
18702 ** INPUTS:
18703 ** func This is a pointer to a function taking three arguments
18704 ** 1. A pointer to anything. Same as the "arg" parameter.
18705 ** 2. A pointer to the list of characters to be output
18706 ** (Note, this list is NOT null terminated.)
18707 ** 3. An integer number of characters to be output.
18708 ** (Note: This number might be zero.)
18710 ** arg This is the pointer to anything which will be passed as the
18711 ** first argument to "func". Use it for whatever you like.
18713 ** fmt This is the format string, as in the usual print.
18715 ** ap This is a pointer to a list of arguments. Same as in
18716 ** vfprint.
18718 ** OUTPUTS:
18719 ** The return value is the total number of characters sent to
18720 ** the function "func". Returns -1 on a error.
18722 ** Note that the order in which automatic variables are declared below
18723 ** seems to make a big difference in determining how fast this beast
18724 ** will run.
18726 SQLITE_PRIVATE void sqlite3VXPrintf(
18727 StrAccum *pAccum, /* Accumulate results here */
18728 int useExtended, /* Allow extended %-conversions */
18729 const char *fmt, /* Format string */
18730 va_list ap /* arguments */
18732 int c; /* Next character in the format string */
18733 char *bufpt; /* Pointer to the conversion buffer */
18734 int precision; /* Precision of the current field */
18735 int length; /* Length of the field */
18736 int idx; /* A general purpose loop counter */
18737 int width; /* Width of the current field */
18738 etByte flag_leftjustify; /* True if "-" flag is present */
18739 etByte flag_plussign; /* True if "+" flag is present */
18740 etByte flag_blanksign; /* True if " " flag is present */
18741 etByte flag_alternateform; /* True if "#" flag is present */
18742 etByte flag_altform2; /* True if "!" flag is present */
18743 etByte flag_zeropad; /* True if field width constant starts with zero */
18744 etByte flag_long; /* True if "l" flag is present */
18745 etByte flag_longlong; /* True if the "ll" flag is present */
18746 etByte done; /* Loop termination flag */
18747 sqlite_uint64 longvalue; /* Value for integer types */
18748 LONGDOUBLE_TYPE realvalue; /* Value for real types */
18749 const et_info *infop; /* Pointer to the appropriate info structure */
18750 char buf[etBUFSIZE]; /* Conversion buffer */
18751 char prefix; /* Prefix character. "+" or "-" or " " or '\0'. */
18752 etByte xtype = 0; /* Conversion paradigm */
18753 char *zExtra; /* Extra memory used for etTCLESCAPE conversions */
18754 #ifndef SQLITE_OMIT_FLOATING_POINT
18755 int exp, e2; /* exponent of real numbers */
18756 double rounder; /* Used for rounding floating point values */
18757 etByte flag_dp; /* True if decimal point should be shown */
18758 etByte flag_rtz; /* True if trailing zeros should be removed */
18759 etByte flag_exp; /* True to force display of the exponent */
18760 int nsd; /* Number of significant digits returned */
18761 #endif
18763 length = 0;
18764 bufpt = 0;
18765 for(; (c=(*fmt))!=0; ++fmt){
18766 if( c!='%' ){
18767 int amt;
18768 bufpt = (char *)fmt;
18769 amt = 1;
18770 while( (c=(*++fmt))!='%' && c!=0 ) amt++;
18771 sqlite3StrAccumAppend(pAccum, bufpt, amt);
18772 if( c==0 ) break;
18774 if( (c=(*++fmt))==0 ){
18775 sqlite3StrAccumAppend(pAccum, "%", 1);
18776 break;
18778 /* Find out what flags are present */
18779 flag_leftjustify = flag_plussign = flag_blanksign =
18780 flag_alternateform = flag_altform2 = flag_zeropad = 0;
18781 done = 0;
18783 switch( c ){
18784 case '-': flag_leftjustify = 1; break;
18785 case '+': flag_plussign = 1; break;
18786 case ' ': flag_blanksign = 1; break;
18787 case '#': flag_alternateform = 1; break;
18788 case '!': flag_altform2 = 1; break;
18789 case '0': flag_zeropad = 1; break;
18790 default: done = 1; break;
18792 }while( !done && (c=(*++fmt))!=0 );
18793 /* Get the field width */
18794 width = 0;
18795 if( c=='*' ){
18796 width = va_arg(ap,int);
18797 if( width<0 ){
18798 flag_leftjustify = 1;
18799 width = -width;
18801 c = *++fmt;
18802 }else{
18803 while( c>='0' && c<='9' ){
18804 width = width*10 + c - '0';
18805 c = *++fmt;
18808 if( width > etBUFSIZE-10 ){
18809 width = etBUFSIZE-10;
18811 /* Get the precision */
18812 if( c=='.' ){
18813 precision = 0;
18814 c = *++fmt;
18815 if( c=='*' ){
18816 precision = va_arg(ap,int);
18817 if( precision<0 ) precision = -precision;
18818 c = *++fmt;
18819 }else{
18820 while( c>='0' && c<='9' ){
18821 precision = precision*10 + c - '0';
18822 c = *++fmt;
18825 }else{
18826 precision = -1;
18828 /* Get the conversion type modifier */
18829 if( c=='l' ){
18830 flag_long = 1;
18831 c = *++fmt;
18832 if( c=='l' ){
18833 flag_longlong = 1;
18834 c = *++fmt;
18835 }else{
18836 flag_longlong = 0;
18838 }else{
18839 flag_long = flag_longlong = 0;
18841 /* Fetch the info entry for the field */
18842 infop = &fmtinfo[0];
18843 xtype = etINVALID;
18844 for(idx=0; idx<ArraySize(fmtinfo); idx++){
18845 if( c==fmtinfo[idx].fmttype ){
18846 infop = &fmtinfo[idx];
18847 if( useExtended || (infop->flags & FLAG_INTERN)==0 ){
18848 xtype = infop->type;
18849 }else{
18850 return;
18852 break;
18855 zExtra = 0;
18858 /* Limit the precision to prevent overflowing buf[] during conversion */
18859 if( precision>etBUFSIZE-40 && (infop->flags & FLAG_STRING)==0 ){
18860 precision = etBUFSIZE-40;
18864 ** At this point, variables are initialized as follows:
18866 ** flag_alternateform TRUE if a '#' is present.
18867 ** flag_altform2 TRUE if a '!' is present.
18868 ** flag_plussign TRUE if a '+' is present.
18869 ** flag_leftjustify TRUE if a '-' is present or if the
18870 ** field width was negative.
18871 ** flag_zeropad TRUE if the width began with 0.
18872 ** flag_long TRUE if the letter 'l' (ell) prefixed
18873 ** the conversion character.
18874 ** flag_longlong TRUE if the letter 'll' (ell ell) prefixed
18875 ** the conversion character.
18876 ** flag_blanksign TRUE if a ' ' is present.
18877 ** width The specified field width. This is
18878 ** always non-negative. Zero is the default.
18879 ** precision The specified precision. The default
18880 ** is -1.
18881 ** xtype The class of the conversion.
18882 ** infop Pointer to the appropriate info struct.
18884 switch( xtype ){
18885 case etPOINTER:
18886 flag_longlong = sizeof(char*)==sizeof(i64);
18887 flag_long = sizeof(char*)==sizeof(long int);
18888 /* Fall through into the next case */
18889 case etORDINAL:
18890 case etRADIX:
18891 if( infop->flags & FLAG_SIGNED ){
18892 i64 v;
18893 if( flag_longlong ){
18894 v = va_arg(ap,i64);
18895 }else if( flag_long ){
18896 v = va_arg(ap,long int);
18897 }else{
18898 v = va_arg(ap,int);
18900 if( v<0 ){
18901 if( v==SMALLEST_INT64 ){
18902 longvalue = ((u64)1)<<63;
18903 }else{
18904 longvalue = -v;
18906 prefix = '-';
18907 }else{
18908 longvalue = v;
18909 if( flag_plussign ) prefix = '+';
18910 else if( flag_blanksign ) prefix = ' ';
18911 else prefix = 0;
18913 }else{
18914 if( flag_longlong ){
18915 longvalue = va_arg(ap,u64);
18916 }else if( flag_long ){
18917 longvalue = va_arg(ap,unsigned long int);
18918 }else{
18919 longvalue = va_arg(ap,unsigned int);
18921 prefix = 0;
18923 if( longvalue==0 ) flag_alternateform = 0;
18924 if( flag_zeropad && precision<width-(prefix!=0) ){
18925 precision = width-(prefix!=0);
18927 bufpt = &buf[etBUFSIZE-1];
18928 if( xtype==etORDINAL ){
18929 static const char zOrd[] = "thstndrd";
18930 int x = (int)(longvalue % 10);
18931 if( x>=4 || (longvalue/10)%10==1 ){
18932 x = 0;
18934 buf[etBUFSIZE-3] = zOrd[x*2];
18935 buf[etBUFSIZE-2] = zOrd[x*2+1];
18936 bufpt -= 2;
18939 register const char *cset; /* Use registers for speed */
18940 register int base;
18941 cset = &aDigits[infop->charset];
18942 base = infop->base;
18943 do{ /* Convert to ascii */
18944 *(--bufpt) = cset[longvalue%base];
18945 longvalue = longvalue/base;
18946 }while( longvalue>0 );
18948 length = (int)(&buf[etBUFSIZE-1]-bufpt);
18949 for(idx=precision-length; idx>0; idx--){
18950 *(--bufpt) = '0'; /* Zero pad */
18952 if( prefix ) *(--bufpt) = prefix; /* Add sign */
18953 if( flag_alternateform && infop->prefix ){ /* Add "0" or "0x" */
18954 const char *pre;
18955 char x;
18956 pre = &aPrefix[infop->prefix];
18957 for(; (x=(*pre))!=0; pre++) *(--bufpt) = x;
18959 length = (int)(&buf[etBUFSIZE-1]-bufpt);
18960 break;
18961 case etFLOAT:
18962 case etEXP:
18963 case etGENERIC:
18964 realvalue = va_arg(ap,double);
18965 #ifdef SQLITE_OMIT_FLOATING_POINT
18966 length = 0;
18967 #else
18968 if( precision<0 ) precision = 6; /* Set default precision */
18969 if( precision>etBUFSIZE/2-10 ) precision = etBUFSIZE/2-10;
18970 if( realvalue<0.0 ){
18971 realvalue = -realvalue;
18972 prefix = '-';
18973 }else{
18974 if( flag_plussign ) prefix = '+';
18975 else if( flag_blanksign ) prefix = ' ';
18976 else prefix = 0;
18978 if( xtype==etGENERIC && precision>0 ) precision--;
18979 #if 0
18980 /* Rounding works like BSD when the constant 0.4999 is used. Wierd! */
18981 for(idx=precision, rounder=0.4999; idx>0; idx--, rounder*=0.1);
18982 #else
18983 /* It makes more sense to use 0.5 */
18984 for(idx=precision, rounder=0.5; idx>0; idx--, rounder*=0.1){}
18985 #endif
18986 if( xtype==etFLOAT ) realvalue += rounder;
18987 /* Normalize realvalue to within 10.0 > realvalue >= 1.0 */
18988 exp = 0;
18989 if( sqlite3IsNaN((double)realvalue) ){
18990 bufpt = "NaN";
18991 length = 3;
18992 break;
18994 if( realvalue>0.0 ){
18995 while( realvalue>=1e32 && exp<=350 ){ realvalue *= 1e-32; exp+=32; }
18996 while( realvalue>=1e8 && exp<=350 ){ realvalue *= 1e-8; exp+=8; }
18997 while( realvalue>=10.0 && exp<=350 ){ realvalue *= 0.1; exp++; }
18998 while( realvalue<1e-8 ){ realvalue *= 1e8; exp-=8; }
18999 while( realvalue<1.0 ){ realvalue *= 10.0; exp--; }
19000 if( exp>350 ){
19001 if( prefix=='-' ){
19002 bufpt = "-Inf";
19003 }else if( prefix=='+' ){
19004 bufpt = "+Inf";
19005 }else{
19006 bufpt = "Inf";
19008 length = sqlite3Strlen30(bufpt);
19009 break;
19012 bufpt = buf;
19014 ** If the field type is etGENERIC, then convert to either etEXP
19015 ** or etFLOAT, as appropriate.
19017 flag_exp = xtype==etEXP;
19018 if( xtype!=etFLOAT ){
19019 realvalue += rounder;
19020 if( realvalue>=10.0 ){ realvalue *= 0.1; exp++; }
19022 if( xtype==etGENERIC ){
19023 flag_rtz = !flag_alternateform;
19024 if( exp<-4 || exp>precision ){
19025 xtype = etEXP;
19026 }else{
19027 precision = precision - exp;
19028 xtype = etFLOAT;
19030 }else{
19031 flag_rtz = 0;
19033 if( xtype==etEXP ){
19034 e2 = 0;
19035 }else{
19036 e2 = exp;
19038 nsd = 0;
19039 flag_dp = (precision>0 ?1:0) | flag_alternateform | flag_altform2;
19040 /* The sign in front of the number */
19041 if( prefix ){
19042 *(bufpt++) = prefix;
19044 /* Digits prior to the decimal point */
19045 if( e2<0 ){
19046 *(bufpt++) = '0';
19047 }else{
19048 for(; e2>=0; e2--){
19049 *(bufpt++) = et_getdigit(&realvalue,&nsd);
19052 /* The decimal point */
19053 if( flag_dp ){
19054 *(bufpt++) = '.';
19056 /* "0" digits after the decimal point but before the first
19057 ** significant digit of the number */
19058 for(e2++; e2<0; precision--, e2++){
19059 assert( precision>0 );
19060 *(bufpt++) = '0';
19062 /* Significant digits after the decimal point */
19063 while( (precision--)>0 ){
19064 *(bufpt++) = et_getdigit(&realvalue,&nsd);
19066 /* Remove trailing zeros and the "." if no digits follow the "." */
19067 if( flag_rtz && flag_dp ){
19068 while( bufpt[-1]=='0' ) *(--bufpt) = 0;
19069 assert( bufpt>buf );
19070 if( bufpt[-1]=='.' ){
19071 if( flag_altform2 ){
19072 *(bufpt++) = '0';
19073 }else{
19074 *(--bufpt) = 0;
19078 /* Add the "eNNN" suffix */
19079 if( flag_exp || xtype==etEXP ){
19080 *(bufpt++) = aDigits[infop->charset];
19081 if( exp<0 ){
19082 *(bufpt++) = '-'; exp = -exp;
19083 }else{
19084 *(bufpt++) = '+';
19086 if( exp>=100 ){
19087 *(bufpt++) = (char)((exp/100)+'0'); /* 100's digit */
19088 exp %= 100;
19090 *(bufpt++) = (char)(exp/10+'0'); /* 10's digit */
19091 *(bufpt++) = (char)(exp%10+'0'); /* 1's digit */
19093 *bufpt = 0;
19095 /* The converted number is in buf[] and zero terminated. Output it.
19096 ** Note that the number is in the usual order, not reversed as with
19097 ** integer conversions. */
19098 length = (int)(bufpt-buf);
19099 bufpt = buf;
19101 /* Special case: Add leading zeros if the flag_zeropad flag is
19102 ** set and we are not left justified */
19103 if( flag_zeropad && !flag_leftjustify && length < width){
19104 int i;
19105 int nPad = width - length;
19106 for(i=width; i>=nPad; i--){
19107 bufpt[i] = bufpt[i-nPad];
19109 i = prefix!=0;
19110 while( nPad-- ) bufpt[i++] = '0';
19111 length = width;
19113 #endif /* !defined(SQLITE_OMIT_FLOATING_POINT) */
19114 break;
19115 case etSIZE:
19116 *(va_arg(ap,int*)) = pAccum->nChar;
19117 length = width = 0;
19118 break;
19119 case etPERCENT:
19120 buf[0] = '%';
19121 bufpt = buf;
19122 length = 1;
19123 break;
19124 case etCHARX:
19125 c = va_arg(ap,int);
19126 buf[0] = (char)c;
19127 if( precision>=0 ){
19128 for(idx=1; idx<precision; idx++) buf[idx] = (char)c;
19129 length = precision;
19130 }else{
19131 length =1;
19133 bufpt = buf;
19134 break;
19135 case etSTRING:
19136 case etDYNSTRING:
19137 bufpt = va_arg(ap,char*);
19138 if( bufpt==0 ){
19139 bufpt = "";
19140 }else if( xtype==etDYNSTRING ){
19141 zExtra = bufpt;
19143 if( precision>=0 ){
19144 for(length=0; length<precision && bufpt[length]; length++){}
19145 }else{
19146 length = sqlite3Strlen30(bufpt);
19148 break;
19149 case etSQLESCAPE:
19150 case etSQLESCAPE2:
19151 case etSQLESCAPE3: {
19152 int i, j, k, n, isnull;
19153 int needQuote;
19154 char ch;
19155 char q = ((xtype==etSQLESCAPE3)?'"':'\''); /* Quote character */
19156 char *escarg = va_arg(ap,char*);
19157 isnull = escarg==0;
19158 if( isnull ) escarg = (xtype==etSQLESCAPE2 ? "NULL" : "(NULL)");
19159 k = precision;
19160 for(i=n=0; k!=0 && (ch=escarg[i])!=0; i++, k--){
19161 if( ch==q ) n++;
19163 needQuote = !isnull && xtype==etSQLESCAPE2;
19164 n += i + 1 + needQuote*2;
19165 if( n>etBUFSIZE ){
19166 bufpt = zExtra = sqlite3Malloc( n );
19167 if( bufpt==0 ){
19168 pAccum->mallocFailed = 1;
19169 return;
19171 }else{
19172 bufpt = buf;
19174 j = 0;
19175 if( needQuote ) bufpt[j++] = q;
19176 k = i;
19177 for(i=0; i<k; i++){
19178 bufpt[j++] = ch = escarg[i];
19179 if( ch==q ) bufpt[j++] = ch;
19181 if( needQuote ) bufpt[j++] = q;
19182 bufpt[j] = 0;
19183 length = j;
19184 /* The precision in %q and %Q means how many input characters to
19185 ** consume, not the length of the output...
19186 ** if( precision>=0 && precision<length ) length = precision; */
19187 break;
19189 case etTOKEN: {
19190 Token *pToken = va_arg(ap, Token*);
19191 if( pToken ){
19192 sqlite3StrAccumAppend(pAccum, (const char*)pToken->z, pToken->n);
19194 length = width = 0;
19195 break;
19197 case etSRCLIST: {
19198 SrcList *pSrc = va_arg(ap, SrcList*);
19199 int k = va_arg(ap, int);
19200 struct SrcList_item *pItem = &pSrc->a[k];
19201 assert( k>=0 && k<pSrc->nSrc );
19202 if( pItem->zDatabase ){
19203 sqlite3StrAccumAppend(pAccum, pItem->zDatabase, -1);
19204 sqlite3StrAccumAppend(pAccum, ".", 1);
19206 sqlite3StrAccumAppend(pAccum, pItem->zName, -1);
19207 length = width = 0;
19208 break;
19210 default: {
19211 assert( xtype==etINVALID );
19212 return;
19214 }/* End switch over the format type */
19216 ** The text of the conversion is pointed to by "bufpt" and is
19217 ** "length" characters long. The field width is "width". Do
19218 ** the output.
19220 if( !flag_leftjustify ){
19221 register int nspace;
19222 nspace = width-length;
19223 if( nspace>0 ){
19224 appendSpace(pAccum, nspace);
19227 if( length>0 ){
19228 sqlite3StrAccumAppend(pAccum, bufpt, length);
19230 if( flag_leftjustify ){
19231 register int nspace;
19232 nspace = width-length;
19233 if( nspace>0 ){
19234 appendSpace(pAccum, nspace);
19237 if( zExtra ){
19238 sqlite3_free(zExtra);
19240 }/* End for loop over the format string */
19241 } /* End of function */
19244 ** Append N bytes of text from z to the StrAccum object.
19246 SQLITE_PRIVATE void sqlite3StrAccumAppend(StrAccum *p, const char *z, int N){
19247 assert( z!=0 || N==0 );
19248 if( p->tooBig | p->mallocFailed ){
19249 testcase(p->tooBig);
19250 testcase(p->mallocFailed);
19251 return;
19253 if( N<0 ){
19254 N = sqlite3Strlen30(z);
19256 if( N==0 || NEVER(z==0) ){
19257 return;
19259 if( p->nChar+N >= p->nAlloc ){
19260 char *zNew;
19261 if( !p->useMalloc ){
19262 p->tooBig = 1;
19263 N = p->nAlloc - p->nChar - 1;
19264 if( N<=0 ){
19265 return;
19267 }else{
19268 char *zOld = (p->zText==p->zBase ? 0 : p->zText);
19269 i64 szNew = p->nChar;
19270 szNew += N + 1;
19271 if( szNew > p->mxAlloc ){
19272 sqlite3StrAccumReset(p);
19273 p->tooBig = 1;
19274 return;
19275 }else{
19276 p->nAlloc = (int)szNew;
19278 if( p->useMalloc==1 ){
19279 zNew = sqlite3DbRealloc(p->db, zOld, p->nAlloc);
19280 }else{
19281 zNew = sqlite3_realloc(zOld, p->nAlloc);
19283 if( zNew ){
19284 if( zOld==0 ) memcpy(zNew, p->zText, p->nChar);
19285 p->zText = zNew;
19286 }else{
19287 p->mallocFailed = 1;
19288 sqlite3StrAccumReset(p);
19289 return;
19293 memcpy(&p->zText[p->nChar], z, N);
19294 p->nChar += N;
19298 ** Finish off a string by making sure it is zero-terminated.
19299 ** Return a pointer to the resulting string. Return a NULL
19300 ** pointer if any kind of error was encountered.
19302 SQLITE_PRIVATE char *sqlite3StrAccumFinish(StrAccum *p){
19303 if( p->zText ){
19304 p->zText[p->nChar] = 0;
19305 if( p->useMalloc && p->zText==p->zBase ){
19306 if( p->useMalloc==1 ){
19307 p->zText = sqlite3DbMallocRaw(p->db, p->nChar+1 );
19308 }else{
19309 p->zText = sqlite3_malloc(p->nChar+1);
19311 if( p->zText ){
19312 memcpy(p->zText, p->zBase, p->nChar+1);
19313 }else{
19314 p->mallocFailed = 1;
19318 return p->zText;
19322 ** Reset an StrAccum string. Reclaim all malloced memory.
19324 SQLITE_PRIVATE void sqlite3StrAccumReset(StrAccum *p){
19325 if( p->zText!=p->zBase ){
19326 if( p->useMalloc==1 ){
19327 sqlite3DbFree(p->db, p->zText);
19328 }else{
19329 sqlite3_free(p->zText);
19332 p->zText = 0;
19336 ** Initialize a string accumulator
19338 SQLITE_PRIVATE void sqlite3StrAccumInit(StrAccum *p, char *zBase, int n, int mx){
19339 p->zText = p->zBase = zBase;
19340 p->db = 0;
19341 p->nChar = 0;
19342 p->nAlloc = n;
19343 p->mxAlloc = mx;
19344 p->useMalloc = 1;
19345 p->tooBig = 0;
19346 p->mallocFailed = 0;
19350 ** Print into memory obtained from sqliteMalloc(). Use the internal
19351 ** %-conversion extensions.
19353 SQLITE_PRIVATE char *sqlite3VMPrintf(sqlite3 *db, const char *zFormat, va_list ap){
19354 char *z;
19355 char zBase[SQLITE_PRINT_BUF_SIZE];
19356 StrAccum acc;
19357 assert( db!=0 );
19358 sqlite3StrAccumInit(&acc, zBase, sizeof(zBase),
19359 db->aLimit[SQLITE_LIMIT_LENGTH]);
19360 acc.db = db;
19361 sqlite3VXPrintf(&acc, 1, zFormat, ap);
19362 z = sqlite3StrAccumFinish(&acc);
19363 if( acc.mallocFailed ){
19364 db->mallocFailed = 1;
19366 return z;
19370 ** Print into memory obtained from sqliteMalloc(). Use the internal
19371 ** %-conversion extensions.
19373 SQLITE_PRIVATE char *sqlite3MPrintf(sqlite3 *db, const char *zFormat, ...){
19374 va_list ap;
19375 char *z;
19376 va_start(ap, zFormat);
19377 z = sqlite3VMPrintf(db, zFormat, ap);
19378 va_end(ap);
19379 return z;
19383 ** Like sqlite3MPrintf(), but call sqlite3DbFree() on zStr after formatting
19384 ** the string and before returnning. This routine is intended to be used
19385 ** to modify an existing string. For example:
19387 ** x = sqlite3MPrintf(db, x, "prefix %s suffix", x);
19390 SQLITE_PRIVATE char *sqlite3MAppendf(sqlite3 *db, char *zStr, const char *zFormat, ...){
19391 va_list ap;
19392 char *z;
19393 va_start(ap, zFormat);
19394 z = sqlite3VMPrintf(db, zFormat, ap);
19395 va_end(ap);
19396 sqlite3DbFree(db, zStr);
19397 return z;
19401 ** Print into memory obtained from sqlite3_malloc(). Omit the internal
19402 ** %-conversion extensions.
19404 SQLITE_API char *sqlite3_vmprintf(const char *zFormat, va_list ap){
19405 char *z;
19406 char zBase[SQLITE_PRINT_BUF_SIZE];
19407 StrAccum acc;
19408 #ifndef SQLITE_OMIT_AUTOINIT
19409 if( sqlite3_initialize() ) return 0;
19410 #endif
19411 sqlite3StrAccumInit(&acc, zBase, sizeof(zBase), SQLITE_MAX_LENGTH);
19412 acc.useMalloc = 2;
19413 sqlite3VXPrintf(&acc, 0, zFormat, ap);
19414 z = sqlite3StrAccumFinish(&acc);
19415 return z;
19419 ** Print into memory obtained from sqlite3_malloc()(). Omit the internal
19420 ** %-conversion extensions.
19422 SQLITE_API char *sqlite3_mprintf(const char *zFormat, ...){
19423 va_list ap;
19424 char *z;
19425 #ifndef SQLITE_OMIT_AUTOINIT
19426 if( sqlite3_initialize() ) return 0;
19427 #endif
19428 va_start(ap, zFormat);
19429 z = sqlite3_vmprintf(zFormat, ap);
19430 va_end(ap);
19431 return z;
19435 ** sqlite3_snprintf() works like snprintf() except that it ignores the
19436 ** current locale settings. This is important for SQLite because we
19437 ** are not able to use a "," as the decimal point in place of "." as
19438 ** specified by some locales.
19440 ** Oops: The first two arguments of sqlite3_snprintf() are backwards
19441 ** from the snprintf() standard. Unfortunately, it is too late to change
19442 ** this without breaking compatibility, so we just have to live with the
19443 ** mistake.
19445 ** sqlite3_vsnprintf() is the varargs version.
19447 SQLITE_API char *sqlite3_vsnprintf(int n, char *zBuf, const char *zFormat, va_list ap){
19448 StrAccum acc;
19449 if( n<=0 ) return zBuf;
19450 sqlite3StrAccumInit(&acc, zBuf, n, 0);
19451 acc.useMalloc = 0;
19452 sqlite3VXPrintf(&acc, 0, zFormat, ap);
19453 return sqlite3StrAccumFinish(&acc);
19455 SQLITE_API char *sqlite3_snprintf(int n, char *zBuf, const char *zFormat, ...){
19456 char *z;
19457 va_list ap;
19458 va_start(ap,zFormat);
19459 z = sqlite3_vsnprintf(n, zBuf, zFormat, ap);
19460 va_end(ap);
19461 return z;
19465 ** This is the routine that actually formats the sqlite3_log() message.
19466 ** We house it in a separate routine from sqlite3_log() to avoid using
19467 ** stack space on small-stack systems when logging is disabled.
19469 ** sqlite3_log() must render into a static buffer. It cannot dynamically
19470 ** allocate memory because it might be called while the memory allocator
19471 ** mutex is held.
19473 static void renderLogMsg(int iErrCode, const char *zFormat, va_list ap){
19474 StrAccum acc; /* String accumulator */
19475 char zMsg[SQLITE_PRINT_BUF_SIZE*3]; /* Complete log message */
19477 sqlite3StrAccumInit(&acc, zMsg, sizeof(zMsg), 0);
19478 acc.useMalloc = 0;
19479 sqlite3VXPrintf(&acc, 0, zFormat, ap);
19480 sqlite3GlobalConfig.xLog(sqlite3GlobalConfig.pLogArg, iErrCode,
19481 sqlite3StrAccumFinish(&acc));
19485 ** Format and write a message to the log if logging is enabled.
19487 SQLITE_API void sqlite3_log(int iErrCode, const char *zFormat, ...){
19488 va_list ap; /* Vararg list */
19489 if( sqlite3GlobalConfig.xLog ){
19490 va_start(ap, zFormat);
19491 renderLogMsg(iErrCode, zFormat, ap);
19492 va_end(ap);
19496 #if defined(SQLITE_DEBUG)
19498 ** A version of printf() that understands %lld. Used for debugging.
19499 ** The printf() built into some versions of windows does not understand %lld
19500 ** and segfaults if you give it a long long int.
19502 SQLITE_PRIVATE void sqlite3DebugPrintf(const char *zFormat, ...){
19503 va_list ap;
19504 StrAccum acc;
19505 char zBuf[500];
19506 sqlite3StrAccumInit(&acc, zBuf, sizeof(zBuf), 0);
19507 acc.useMalloc = 0;
19508 va_start(ap,zFormat);
19509 sqlite3VXPrintf(&acc, 0, zFormat, ap);
19510 va_end(ap);
19511 sqlite3StrAccumFinish(&acc);
19512 fprintf(stdout,"%s", zBuf);
19513 fflush(stdout);
19515 #endif
19517 #ifndef SQLITE_OMIT_TRACE
19519 ** variable-argument wrapper around sqlite3VXPrintf().
19521 SQLITE_PRIVATE void sqlite3XPrintf(StrAccum *p, const char *zFormat, ...){
19522 va_list ap;
19523 va_start(ap,zFormat);
19524 sqlite3VXPrintf(p, 1, zFormat, ap);
19525 va_end(ap);
19527 #endif
19529 /************** End of printf.c **********************************************/
19530 /************** Begin file random.c ******************************************/
19532 ** 2001 September 15
19534 ** The author disclaims copyright to this source code. In place of
19535 ** a legal notice, here is a blessing:
19537 ** May you do good and not evil.
19538 ** May you find forgiveness for yourself and forgive others.
19539 ** May you share freely, never taking more than you give.
19541 *************************************************************************
19542 ** This file contains code to implement a pseudo-random number
19543 ** generator (PRNG) for SQLite.
19545 ** Random numbers are used by some of the database backends in order
19546 ** to generate random integer keys for tables or random filenames.
19550 /* All threads share a single random number generator.
19551 ** This structure is the current state of the generator.
19553 static SQLITE_WSD struct sqlite3PrngType {
19554 unsigned char isInit; /* True if initialized */
19555 unsigned char i, j; /* State variables */
19556 unsigned char s[256]; /* State variables */
19557 } sqlite3Prng;
19560 ** Get a single 8-bit random value from the RC4 PRNG. The Mutex
19561 ** must be held while executing this routine.
19563 ** Why not just use a library random generator like lrand48() for this?
19564 ** Because the OP_NewRowid opcode in the VDBE depends on having a very
19565 ** good source of random numbers. The lrand48() library function may
19566 ** well be good enough. But maybe not. Or maybe lrand48() has some
19567 ** subtle problems on some systems that could cause problems. It is hard
19568 ** to know. To minimize the risk of problems due to bad lrand48()
19569 ** implementations, SQLite uses this random number generator based
19570 ** on RC4, which we know works very well.
19572 ** (Later): Actually, OP_NewRowid does not depend on a good source of
19573 ** randomness any more. But we will leave this code in all the same.
19575 static u8 randomByte(void){
19576 unsigned char t;
19579 /* The "wsdPrng" macro will resolve to the pseudo-random number generator
19580 ** state vector. If writable static data is unsupported on the target,
19581 ** we have to locate the state vector at run-time. In the more common
19582 ** case where writable static data is supported, wsdPrng can refer directly
19583 ** to the "sqlite3Prng" state vector declared above.
19585 #ifdef SQLITE_OMIT_WSD
19586 struct sqlite3PrngType *p = &GLOBAL(struct sqlite3PrngType, sqlite3Prng);
19587 # define wsdPrng p[0]
19588 #else
19589 # define wsdPrng sqlite3Prng
19590 #endif
19593 /* Initialize the state of the random number generator once,
19594 ** the first time this routine is called. The seed value does
19595 ** not need to contain a lot of randomness since we are not
19596 ** trying to do secure encryption or anything like that...
19598 ** Nothing in this file or anywhere else in SQLite does any kind of
19599 ** encryption. The RC4 algorithm is being used as a PRNG (pseudo-random
19600 ** number generator) not as an encryption device.
19602 if( !wsdPrng.isInit ){
19603 int i;
19604 char k[256];
19605 wsdPrng.j = 0;
19606 wsdPrng.i = 0;
19607 sqlite3OsRandomness(sqlite3_vfs_find(0), 256, k);
19608 for(i=0; i<256; i++){
19609 wsdPrng.s[i] = (u8)i;
19611 for(i=0; i<256; i++){
19612 wsdPrng.j += wsdPrng.s[i] + k[i];
19613 t = wsdPrng.s[wsdPrng.j];
19614 wsdPrng.s[wsdPrng.j] = wsdPrng.s[i];
19615 wsdPrng.s[i] = t;
19617 wsdPrng.isInit = 1;
19620 /* Generate and return single random byte
19622 wsdPrng.i++;
19623 t = wsdPrng.s[wsdPrng.i];
19624 wsdPrng.j += t;
19625 wsdPrng.s[wsdPrng.i] = wsdPrng.s[wsdPrng.j];
19626 wsdPrng.s[wsdPrng.j] = t;
19627 t += wsdPrng.s[wsdPrng.i];
19628 return wsdPrng.s[t];
19632 ** Return N random bytes.
19634 SQLITE_API void sqlite3_randomness(int N, void *pBuf){
19635 unsigned char *zBuf = pBuf;
19636 #if SQLITE_THREADSAFE
19637 sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_PRNG);
19638 #endif
19639 sqlite3_mutex_enter(mutex);
19640 while( N-- ){
19641 *(zBuf++) = randomByte();
19643 sqlite3_mutex_leave(mutex);
19646 #ifndef SQLITE_OMIT_BUILTIN_TEST
19648 ** For testing purposes, we sometimes want to preserve the state of
19649 ** PRNG and restore the PRNG to its saved state at a later time, or
19650 ** to reset the PRNG to its initial state. These routines accomplish
19651 ** those tasks.
19653 ** The sqlite3_test_control() interface calls these routines to
19654 ** control the PRNG.
19656 static SQLITE_WSD struct sqlite3PrngType sqlite3SavedPrng;
19657 SQLITE_PRIVATE void sqlite3PrngSaveState(void){
19658 memcpy(
19659 &GLOBAL(struct sqlite3PrngType, sqlite3SavedPrng),
19660 &GLOBAL(struct sqlite3PrngType, sqlite3Prng),
19661 sizeof(sqlite3Prng)
19664 SQLITE_PRIVATE void sqlite3PrngRestoreState(void){
19665 memcpy(
19666 &GLOBAL(struct sqlite3PrngType, sqlite3Prng),
19667 &GLOBAL(struct sqlite3PrngType, sqlite3SavedPrng),
19668 sizeof(sqlite3Prng)
19671 SQLITE_PRIVATE void sqlite3PrngResetState(void){
19672 GLOBAL(struct sqlite3PrngType, sqlite3Prng).isInit = 0;
19674 #endif /* SQLITE_OMIT_BUILTIN_TEST */
19676 /************** End of random.c **********************************************/
19677 /************** Begin file utf.c *********************************************/
19679 ** 2004 April 13
19681 ** The author disclaims copyright to this source code. In place of
19682 ** a legal notice, here is a blessing:
19684 ** May you do good and not evil.
19685 ** May you find forgiveness for yourself and forgive others.
19686 ** May you share freely, never taking more than you give.
19688 *************************************************************************
19689 ** This file contains routines used to translate between UTF-8,
19690 ** UTF-16, UTF-16BE, and UTF-16LE.
19692 ** Notes on UTF-8:
19694 ** Byte-0 Byte-1 Byte-2 Byte-3 Value
19695 ** 0xxxxxxx 00000000 00000000 0xxxxxxx
19696 ** 110yyyyy 10xxxxxx 00000000 00000yyy yyxxxxxx
19697 ** 1110zzzz 10yyyyyy 10xxxxxx 00000000 zzzzyyyy yyxxxxxx
19698 ** 11110uuu 10uuzzzz 10yyyyyy 10xxxxxx 000uuuuu zzzzyyyy yyxxxxxx
19701 ** Notes on UTF-16: (with wwww+1==uuuuu)
19703 ** Word-0 Word-1 Value
19704 ** 110110ww wwzzzzyy 110111yy yyxxxxxx 000uuuuu zzzzyyyy yyxxxxxx
19705 ** zzzzyyyy yyxxxxxx 00000000 zzzzyyyy yyxxxxxx
19708 ** BOM or Byte Order Mark:
19709 ** 0xff 0xfe little-endian utf-16 follows
19710 ** 0xfe 0xff big-endian utf-16 follows
19714 #ifndef SQLITE_AMALGAMATION
19716 ** The following constant value is used by the SQLITE_BIGENDIAN and
19717 ** SQLITE_LITTLEENDIAN macros.
19719 SQLITE_PRIVATE const int sqlite3one = 1;
19720 #endif /* SQLITE_AMALGAMATION */
19723 ** This lookup table is used to help decode the first byte of
19724 ** a multi-byte UTF8 character.
19726 static const unsigned char sqlite3Utf8Trans1[] = {
19727 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
19728 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
19729 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
19730 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
19731 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
19732 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
19733 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
19734 0x00, 0x01, 0x02, 0x03, 0x00, 0x01, 0x00, 0x00,
19738 #define WRITE_UTF8(zOut, c) { \
19739 if( c<0x00080 ){ \
19740 *zOut++ = (u8)(c&0xFF); \
19742 else if( c<0x00800 ){ \
19743 *zOut++ = 0xC0 + (u8)((c>>6)&0x1F); \
19744 *zOut++ = 0x80 + (u8)(c & 0x3F); \
19746 else if( c<0x10000 ){ \
19747 *zOut++ = 0xE0 + (u8)((c>>12)&0x0F); \
19748 *zOut++ = 0x80 + (u8)((c>>6) & 0x3F); \
19749 *zOut++ = 0x80 + (u8)(c & 0x3F); \
19750 }else{ \
19751 *zOut++ = 0xF0 + (u8)((c>>18) & 0x07); \
19752 *zOut++ = 0x80 + (u8)((c>>12) & 0x3F); \
19753 *zOut++ = 0x80 + (u8)((c>>6) & 0x3F); \
19754 *zOut++ = 0x80 + (u8)(c & 0x3F); \
19758 #define WRITE_UTF16LE(zOut, c) { \
19759 if( c<=0xFFFF ){ \
19760 *zOut++ = (u8)(c&0x00FF); \
19761 *zOut++ = (u8)((c>>8)&0x00FF); \
19762 }else{ \
19763 *zOut++ = (u8)(((c>>10)&0x003F) + (((c-0x10000)>>10)&0x00C0)); \
19764 *zOut++ = (u8)(0x00D8 + (((c-0x10000)>>18)&0x03)); \
19765 *zOut++ = (u8)(c&0x00FF); \
19766 *zOut++ = (u8)(0x00DC + ((c>>8)&0x03)); \
19770 #define WRITE_UTF16BE(zOut, c) { \
19771 if( c<=0xFFFF ){ \
19772 *zOut++ = (u8)((c>>8)&0x00FF); \
19773 *zOut++ = (u8)(c&0x00FF); \
19774 }else{ \
19775 *zOut++ = (u8)(0x00D8 + (((c-0x10000)>>18)&0x03)); \
19776 *zOut++ = (u8)(((c>>10)&0x003F) + (((c-0x10000)>>10)&0x00C0)); \
19777 *zOut++ = (u8)(0x00DC + ((c>>8)&0x03)); \
19778 *zOut++ = (u8)(c&0x00FF); \
19782 #define READ_UTF16LE(zIn, TERM, c){ \
19783 c = (*zIn++); \
19784 c += ((*zIn++)<<8); \
19785 if( c>=0xD800 && c<0xE000 && TERM ){ \
19786 int c2 = (*zIn++); \
19787 c2 += ((*zIn++)<<8); \
19788 c = (c2&0x03FF) + ((c&0x003F)<<10) + (((c&0x03C0)+0x0040)<<10); \
19792 #define READ_UTF16BE(zIn, TERM, c){ \
19793 c = ((*zIn++)<<8); \
19794 c += (*zIn++); \
19795 if( c>=0xD800 && c<0xE000 && TERM ){ \
19796 int c2 = ((*zIn++)<<8); \
19797 c2 += (*zIn++); \
19798 c = (c2&0x03FF) + ((c&0x003F)<<10) + (((c&0x03C0)+0x0040)<<10); \
19803 ** Translate a single UTF-8 character. Return the unicode value.
19805 ** During translation, assume that the byte that zTerm points
19806 ** is a 0x00.
19808 ** Write a pointer to the next unread byte back into *pzNext.
19810 ** Notes On Invalid UTF-8:
19812 ** * This routine never allows a 7-bit character (0x00 through 0x7f) to
19813 ** be encoded as a multi-byte character. Any multi-byte character that
19814 ** attempts to encode a value between 0x00 and 0x7f is rendered as 0xfffd.
19816 ** * This routine never allows a UTF16 surrogate value to be encoded.
19817 ** If a multi-byte character attempts to encode a value between
19818 ** 0xd800 and 0xe000 then it is rendered as 0xfffd.
19820 ** * Bytes in the range of 0x80 through 0xbf which occur as the first
19821 ** byte of a character are interpreted as single-byte characters
19822 ** and rendered as themselves even though they are technically
19823 ** invalid characters.
19825 ** * This routine accepts an infinite number of different UTF8 encodings
19826 ** for unicode values 0x80 and greater. It do not change over-length
19827 ** encodings to 0xfffd as some systems recommend.
19829 #define READ_UTF8(zIn, zTerm, c) \
19830 c = *(zIn++); \
19831 if( c>=0xc0 ){ \
19832 c = sqlite3Utf8Trans1[c-0xc0]; \
19833 while( zIn!=zTerm && (*zIn & 0xc0)==0x80 ){ \
19834 c = (c<<6) + (0x3f & *(zIn++)); \
19836 if( c<0x80 \
19837 || (c&0xFFFFF800)==0xD800 \
19838 || (c&0xFFFFFFFE)==0xFFFE ){ c = 0xFFFD; } \
19840 SQLITE_PRIVATE int sqlite3Utf8Read(
19841 const unsigned char *zIn, /* First byte of UTF-8 character */
19842 const unsigned char **pzNext /* Write first byte past UTF-8 char here */
19844 unsigned int c;
19846 /* Same as READ_UTF8() above but without the zTerm parameter.
19847 ** For this routine, we assume the UTF8 string is always zero-terminated.
19849 c = *(zIn++);
19850 if( c>=0xc0 ){
19851 c = sqlite3Utf8Trans1[c-0xc0];
19852 while( (*zIn & 0xc0)==0x80 ){
19853 c = (c<<6) + (0x3f & *(zIn++));
19855 if( c<0x80
19856 || (c&0xFFFFF800)==0xD800
19857 || (c&0xFFFFFFFE)==0xFFFE ){ c = 0xFFFD; }
19859 *pzNext = zIn;
19860 return c;
19867 ** If the TRANSLATE_TRACE macro is defined, the value of each Mem is
19868 ** printed on stderr on the way into and out of sqlite3VdbeMemTranslate().
19870 /* #define TRANSLATE_TRACE 1 */
19872 #ifndef SQLITE_OMIT_UTF16
19874 ** This routine transforms the internal text encoding used by pMem to
19875 ** desiredEnc. It is an error if the string is already of the desired
19876 ** encoding, or if *pMem does not contain a string value.
19878 SQLITE_PRIVATE int sqlite3VdbeMemTranslate(Mem *pMem, u8 desiredEnc){
19879 int len; /* Maximum length of output string in bytes */
19880 unsigned char *zOut; /* Output buffer */
19881 unsigned char *zIn; /* Input iterator */
19882 unsigned char *zTerm; /* End of input */
19883 unsigned char *z; /* Output iterator */
19884 unsigned int c;
19886 assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
19887 assert( pMem->flags&MEM_Str );
19888 assert( pMem->enc!=desiredEnc );
19889 assert( pMem->enc!=0 );
19890 assert( pMem->n>=0 );
19892 #if defined(TRANSLATE_TRACE) && defined(SQLITE_DEBUG)
19894 char zBuf[100];
19895 sqlite3VdbeMemPrettyPrint(pMem, zBuf);
19896 fprintf(stderr, "INPUT: %s\n", zBuf);
19898 #endif
19900 /* If the translation is between UTF-16 little and big endian, then
19901 ** all that is required is to swap the byte order. This case is handled
19902 ** differently from the others.
19904 if( pMem->enc!=SQLITE_UTF8 && desiredEnc!=SQLITE_UTF8 ){
19905 u8 temp;
19906 int rc;
19907 rc = sqlite3VdbeMemMakeWriteable(pMem);
19908 if( rc!=SQLITE_OK ){
19909 assert( rc==SQLITE_NOMEM );
19910 return SQLITE_NOMEM;
19912 zIn = (u8*)pMem->z;
19913 zTerm = &zIn[pMem->n&~1];
19914 while( zIn<zTerm ){
19915 temp = *zIn;
19916 *zIn = *(zIn+1);
19917 zIn++;
19918 *zIn++ = temp;
19920 pMem->enc = desiredEnc;
19921 goto translate_out;
19924 /* Set len to the maximum number of bytes required in the output buffer. */
19925 if( desiredEnc==SQLITE_UTF8 ){
19926 /* When converting from UTF-16, the maximum growth results from
19927 ** translating a 2-byte character to a 4-byte UTF-8 character.
19928 ** A single byte is required for the output string
19929 ** nul-terminator.
19931 pMem->n &= ~1;
19932 len = pMem->n * 2 + 1;
19933 }else{
19934 /* When converting from UTF-8 to UTF-16 the maximum growth is caused
19935 ** when a 1-byte UTF-8 character is translated into a 2-byte UTF-16
19936 ** character. Two bytes are required in the output buffer for the
19937 ** nul-terminator.
19939 len = pMem->n * 2 + 2;
19942 /* Set zIn to point at the start of the input buffer and zTerm to point 1
19943 ** byte past the end.
19945 ** Variable zOut is set to point at the output buffer, space obtained
19946 ** from sqlite3_malloc().
19948 zIn = (u8*)pMem->z;
19949 zTerm = &zIn[pMem->n];
19950 zOut = sqlite3DbMallocRaw(pMem->db, len);
19951 if( !zOut ){
19952 return SQLITE_NOMEM;
19954 z = zOut;
19956 if( pMem->enc==SQLITE_UTF8 ){
19957 if( desiredEnc==SQLITE_UTF16LE ){
19958 /* UTF-8 -> UTF-16 Little-endian */
19959 while( zIn<zTerm ){
19960 /* c = sqlite3Utf8Read(zIn, zTerm, (const u8**)&zIn); */
19961 READ_UTF8(zIn, zTerm, c);
19962 WRITE_UTF16LE(z, c);
19964 }else{
19965 assert( desiredEnc==SQLITE_UTF16BE );
19966 /* UTF-8 -> UTF-16 Big-endian */
19967 while( zIn<zTerm ){
19968 /* c = sqlite3Utf8Read(zIn, zTerm, (const u8**)&zIn); */
19969 READ_UTF8(zIn, zTerm, c);
19970 WRITE_UTF16BE(z, c);
19973 pMem->n = (int)(z - zOut);
19974 *z++ = 0;
19975 }else{
19976 assert( desiredEnc==SQLITE_UTF8 );
19977 if( pMem->enc==SQLITE_UTF16LE ){
19978 /* UTF-16 Little-endian -> UTF-8 */
19979 while( zIn<zTerm ){
19980 READ_UTF16LE(zIn, zIn<zTerm, c);
19981 WRITE_UTF8(z, c);
19983 }else{
19984 /* UTF-16 Big-endian -> UTF-8 */
19985 while( zIn<zTerm ){
19986 READ_UTF16BE(zIn, zIn<zTerm, c);
19987 WRITE_UTF8(z, c);
19990 pMem->n = (int)(z - zOut);
19992 *z = 0;
19993 assert( (pMem->n+(desiredEnc==SQLITE_UTF8?1:2))<=len );
19995 sqlite3VdbeMemRelease(pMem);
19996 pMem->flags &= ~(MEM_Static|MEM_Dyn|MEM_Ephem);
19997 pMem->enc = desiredEnc;
19998 pMem->flags |= (MEM_Term|MEM_Dyn);
19999 pMem->z = (char*)zOut;
20000 pMem->zMalloc = pMem->z;
20002 translate_out:
20003 #if defined(TRANSLATE_TRACE) && defined(SQLITE_DEBUG)
20005 char zBuf[100];
20006 sqlite3VdbeMemPrettyPrint(pMem, zBuf);
20007 fprintf(stderr, "OUTPUT: %s\n", zBuf);
20009 #endif
20010 return SQLITE_OK;
20014 ** This routine checks for a byte-order mark at the beginning of the
20015 ** UTF-16 string stored in *pMem. If one is present, it is removed and
20016 ** the encoding of the Mem adjusted. This routine does not do any
20017 ** byte-swapping, it just sets Mem.enc appropriately.
20019 ** The allocation (static, dynamic etc.) and encoding of the Mem may be
20020 ** changed by this function.
20022 SQLITE_PRIVATE int sqlite3VdbeMemHandleBom(Mem *pMem){
20023 int rc = SQLITE_OK;
20024 u8 bom = 0;
20026 assert( pMem->n>=0 );
20027 if( pMem->n>1 ){
20028 u8 b1 = *(u8 *)pMem->z;
20029 u8 b2 = *(((u8 *)pMem->z) + 1);
20030 if( b1==0xFE && b2==0xFF ){
20031 bom = SQLITE_UTF16BE;
20033 if( b1==0xFF && b2==0xFE ){
20034 bom = SQLITE_UTF16LE;
20038 if( bom ){
20039 rc = sqlite3VdbeMemMakeWriteable(pMem);
20040 if( rc==SQLITE_OK ){
20041 pMem->n -= 2;
20042 memmove(pMem->z, &pMem->z[2], pMem->n);
20043 pMem->z[pMem->n] = '\0';
20044 pMem->z[pMem->n+1] = '\0';
20045 pMem->flags |= MEM_Term;
20046 pMem->enc = bom;
20049 return rc;
20051 #endif /* SQLITE_OMIT_UTF16 */
20054 ** pZ is a UTF-8 encoded unicode string. If nByte is less than zero,
20055 ** return the number of unicode characters in pZ up to (but not including)
20056 ** the first 0x00 byte. If nByte is not less than zero, return the
20057 ** number of unicode characters in the first nByte of pZ (or up to
20058 ** the first 0x00, whichever comes first).
20060 SQLITE_PRIVATE int sqlite3Utf8CharLen(const char *zIn, int nByte){
20061 int r = 0;
20062 const u8 *z = (const u8*)zIn;
20063 const u8 *zTerm;
20064 if( nByte>=0 ){
20065 zTerm = &z[nByte];
20066 }else{
20067 zTerm = (const u8*)(-1);
20069 assert( z<=zTerm );
20070 while( *z!=0 && z<zTerm ){
20071 SQLITE_SKIP_UTF8(z);
20072 r++;
20074 return r;
20077 /* This test function is not currently used by the automated test-suite.
20078 ** Hence it is only available in debug builds.
20080 #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
20082 ** Translate UTF-8 to UTF-8.
20084 ** This has the effect of making sure that the string is well-formed
20085 ** UTF-8. Miscoded characters are removed.
20087 ** The translation is done in-place and aborted if the output
20088 ** overruns the input.
20090 SQLITE_PRIVATE int sqlite3Utf8To8(unsigned char *zIn){
20091 unsigned char *zOut = zIn;
20092 unsigned char *zStart = zIn;
20093 u32 c;
20095 while( zIn[0] && zOut<=zIn ){
20096 c = sqlite3Utf8Read(zIn, (const u8**)&zIn);
20097 if( c!=0xfffd ){
20098 WRITE_UTF8(zOut, c);
20101 *zOut = 0;
20102 return (int)(zOut - zStart);
20104 #endif
20106 #ifndef SQLITE_OMIT_UTF16
20108 ** Convert a UTF-16 string in the native encoding into a UTF-8 string.
20109 ** Memory to hold the UTF-8 string is obtained from sqlite3_malloc and must
20110 ** be freed by the calling function.
20112 ** NULL is returned if there is an allocation error.
20114 SQLITE_PRIVATE char *sqlite3Utf16to8(sqlite3 *db, const void *z, int nByte, u8 enc){
20115 Mem m;
20116 memset(&m, 0, sizeof(m));
20117 m.db = db;
20118 sqlite3VdbeMemSetStr(&m, z, nByte, enc, SQLITE_STATIC);
20119 sqlite3VdbeChangeEncoding(&m, SQLITE_UTF8);
20120 if( db->mallocFailed ){
20121 sqlite3VdbeMemRelease(&m);
20122 m.z = 0;
20124 assert( (m.flags & MEM_Term)!=0 || db->mallocFailed );
20125 assert( (m.flags & MEM_Str)!=0 || db->mallocFailed );
20126 assert( (m.flags & MEM_Dyn)!=0 || db->mallocFailed );
20127 assert( m.z || db->mallocFailed );
20128 return m.z;
20132 ** Convert a UTF-8 string to the UTF-16 encoding specified by parameter
20133 ** enc. A pointer to the new string is returned, and the value of *pnOut
20134 ** is set to the length of the returned string in bytes. The call should
20135 ** arrange to call sqlite3DbFree() on the returned pointer when it is
20136 ** no longer required.
20138 ** If a malloc failure occurs, NULL is returned and the db.mallocFailed
20139 ** flag set.
20141 #ifdef SQLITE_ENABLE_STAT2
20142 SQLITE_PRIVATE char *sqlite3Utf8to16(sqlite3 *db, u8 enc, char *z, int n, int *pnOut){
20143 Mem m;
20144 memset(&m, 0, sizeof(m));
20145 m.db = db;
20146 sqlite3VdbeMemSetStr(&m, z, n, SQLITE_UTF8, SQLITE_STATIC);
20147 if( sqlite3VdbeMemTranslate(&m, enc) ){
20148 assert( db->mallocFailed );
20149 return 0;
20151 assert( m.z==m.zMalloc );
20152 *pnOut = m.n;
20153 return m.z;
20155 #endif
20158 ** zIn is a UTF-16 encoded unicode string at least nChar characters long.
20159 ** Return the number of bytes in the first nChar unicode characters
20160 ** in pZ. nChar must be non-negative.
20162 SQLITE_PRIVATE int sqlite3Utf16ByteLen(const void *zIn, int nChar){
20163 int c;
20164 unsigned char const *z = zIn;
20165 int n = 0;
20167 if( SQLITE_UTF16NATIVE==SQLITE_UTF16BE ){
20168 while( n<nChar ){
20169 READ_UTF16BE(z, 1, c);
20170 n++;
20172 }else{
20173 while( n<nChar ){
20174 READ_UTF16LE(z, 1, c);
20175 n++;
20178 return (int)(z-(unsigned char const *)zIn);
20181 #if defined(SQLITE_TEST)
20183 ** This routine is called from the TCL test function "translate_selftest".
20184 ** It checks that the primitives for serializing and deserializing
20185 ** characters in each encoding are inverses of each other.
20187 SQLITE_PRIVATE void sqlite3UtfSelfTest(void){
20188 unsigned int i, t;
20189 unsigned char zBuf[20];
20190 unsigned char *z;
20191 int n;
20192 unsigned int c;
20194 for(i=0; i<0x00110000; i++){
20195 z = zBuf;
20196 WRITE_UTF8(z, i);
20197 n = (int)(z-zBuf);
20198 assert( n>0 && n<=4 );
20199 z[0] = 0;
20200 z = zBuf;
20201 c = sqlite3Utf8Read(z, (const u8**)&z);
20202 t = i;
20203 if( i>=0xD800 && i<=0xDFFF ) t = 0xFFFD;
20204 if( (i&0xFFFFFFFE)==0xFFFE ) t = 0xFFFD;
20205 assert( c==t );
20206 assert( (z-zBuf)==n );
20208 for(i=0; i<0x00110000; i++){
20209 if( i>=0xD800 && i<0xE000 ) continue;
20210 z = zBuf;
20211 WRITE_UTF16LE(z, i);
20212 n = (int)(z-zBuf);
20213 assert( n>0 && n<=4 );
20214 z[0] = 0;
20215 z = zBuf;
20216 READ_UTF16LE(z, 1, c);
20217 assert( c==i );
20218 assert( (z-zBuf)==n );
20220 for(i=0; i<0x00110000; i++){
20221 if( i>=0xD800 && i<0xE000 ) continue;
20222 z = zBuf;
20223 WRITE_UTF16BE(z, i);
20224 n = (int)(z-zBuf);
20225 assert( n>0 && n<=4 );
20226 z[0] = 0;
20227 z = zBuf;
20228 READ_UTF16BE(z, 1, c);
20229 assert( c==i );
20230 assert( (z-zBuf)==n );
20233 #endif /* SQLITE_TEST */
20234 #endif /* SQLITE_OMIT_UTF16 */
20236 /************** End of utf.c *************************************************/
20237 /************** Begin file util.c ********************************************/
20239 ** 2001 September 15
20241 ** The author disclaims copyright to this source code. In place of
20242 ** a legal notice, here is a blessing:
20244 ** May you do good and not evil.
20245 ** May you find forgiveness for yourself and forgive others.
20246 ** May you share freely, never taking more than you give.
20248 *************************************************************************
20249 ** Utility functions used throughout sqlite.
20251 ** This file contains functions for allocating memory, comparing
20252 ** strings, and stuff like that.
20255 #ifdef SQLITE_HAVE_ISNAN
20256 # include <math.h>
20257 #endif
20260 ** Routine needed to support the testcase() macro.
20262 #ifdef SQLITE_COVERAGE_TEST
20263 SQLITE_PRIVATE void sqlite3Coverage(int x){
20264 static unsigned dummy = 0;
20265 dummy += (unsigned)x;
20267 #endif
20269 #ifndef SQLITE_OMIT_FLOATING_POINT
20271 ** Return true if the floating point value is Not a Number (NaN).
20273 ** Use the math library isnan() function if compiled with SQLITE_HAVE_ISNAN.
20274 ** Otherwise, we have our own implementation that works on most systems.
20276 SQLITE_PRIVATE int sqlite3IsNaN(double x){
20277 int rc; /* The value return */
20278 #if !defined(SQLITE_HAVE_ISNAN)
20280 ** Systems that support the isnan() library function should probably
20281 ** make use of it by compiling with -DSQLITE_HAVE_ISNAN. But we have
20282 ** found that many systems do not have a working isnan() function so
20283 ** this implementation is provided as an alternative.
20285 ** This NaN test sometimes fails if compiled on GCC with -ffast-math.
20286 ** On the other hand, the use of -ffast-math comes with the following
20287 ** warning:
20289 ** This option [-ffast-math] should never be turned on by any
20290 ** -O option since it can result in incorrect output for programs
20291 ** which depend on an exact implementation of IEEE or ISO
20292 ** rules/specifications for math functions.
20294 ** Under MSVC, this NaN test may fail if compiled with a floating-
20295 ** point precision mode other than /fp:precise. From the MSDN
20296 ** documentation:
20298 ** The compiler [with /fp:precise] will properly handle comparisons
20299 ** involving NaN. For example, x != x evaluates to true if x is NaN
20300 ** ...
20302 #ifdef __FAST_MATH__
20303 # error SQLite will not work correctly with the -ffast-math option of GCC.
20304 #endif
20305 volatile double y = x;
20306 volatile double z = y;
20307 rc = (y!=z);
20308 #else /* if defined(SQLITE_HAVE_ISNAN) */
20309 rc = isnan(x);
20310 #endif /* SQLITE_HAVE_ISNAN */
20311 testcase( rc );
20312 return rc;
20314 #endif /* SQLITE_OMIT_FLOATING_POINT */
20317 ** Compute a string length that is limited to what can be stored in
20318 ** lower 30 bits of a 32-bit signed integer.
20320 ** The value returned will never be negative. Nor will it ever be greater
20321 ** than the actual length of the string. For very long strings (greater
20322 ** than 1GiB) the value returned might be less than the true string length.
20324 SQLITE_PRIVATE int sqlite3Strlen30(const char *z){
20325 const char *z2 = z;
20326 if( z==0 ) return 0;
20327 while( *z2 ){ z2++; }
20328 return 0x3fffffff & (int)(z2 - z);
20332 ** Set the most recent error code and error string for the sqlite
20333 ** handle "db". The error code is set to "err_code".
20335 ** If it is not NULL, string zFormat specifies the format of the
20336 ** error string in the style of the printf functions: The following
20337 ** format characters are allowed:
20339 ** %s Insert a string
20340 ** %z A string that should be freed after use
20341 ** %d Insert an integer
20342 ** %T Insert a token
20343 ** %S Insert the first element of a SrcList
20345 ** zFormat and any string tokens that follow it are assumed to be
20346 ** encoded in UTF-8.
20348 ** To clear the most recent error for sqlite handle "db", sqlite3Error
20349 ** should be called with err_code set to SQLITE_OK and zFormat set
20350 ** to NULL.
20352 SQLITE_PRIVATE void sqlite3Error(sqlite3 *db, int err_code, const char *zFormat, ...){
20353 if( db && (db->pErr || (db->pErr = sqlite3ValueNew(db))!=0) ){
20354 db->errCode = err_code;
20355 if( zFormat ){
20356 char *z;
20357 va_list ap;
20358 va_start(ap, zFormat);
20359 z = sqlite3VMPrintf(db, zFormat, ap);
20360 va_end(ap);
20361 sqlite3ValueSetStr(db->pErr, -1, z, SQLITE_UTF8, SQLITE_DYNAMIC);
20362 }else{
20363 sqlite3ValueSetStr(db->pErr, 0, 0, SQLITE_UTF8, SQLITE_STATIC);
20369 ** Add an error message to pParse->zErrMsg and increment pParse->nErr.
20370 ** The following formatting characters are allowed:
20372 ** %s Insert a string
20373 ** %z A string that should be freed after use
20374 ** %d Insert an integer
20375 ** %T Insert a token
20376 ** %S Insert the first element of a SrcList
20378 ** This function should be used to report any error that occurs whilst
20379 ** compiling an SQL statement (i.e. within sqlite3_prepare()). The
20380 ** last thing the sqlite3_prepare() function does is copy the error
20381 ** stored by this function into the database handle using sqlite3Error().
20382 ** Function sqlite3Error() should be used during statement execution
20383 ** (sqlite3_step() etc.).
20385 SQLITE_PRIVATE void sqlite3ErrorMsg(Parse *pParse, const char *zFormat, ...){
20386 char *zMsg;
20387 va_list ap;
20388 sqlite3 *db = pParse->db;
20389 va_start(ap, zFormat);
20390 zMsg = sqlite3VMPrintf(db, zFormat, ap);
20391 va_end(ap);
20392 if( db->suppressErr ){
20393 sqlite3DbFree(db, zMsg);
20394 }else{
20395 pParse->nErr++;
20396 sqlite3DbFree(db, pParse->zErrMsg);
20397 pParse->zErrMsg = zMsg;
20398 pParse->rc = SQLITE_ERROR;
20403 ** Convert an SQL-style quoted string into a normal string by removing
20404 ** the quote characters. The conversion is done in-place. If the
20405 ** input does not begin with a quote character, then this routine
20406 ** is a no-op.
20408 ** The input string must be zero-terminated. A new zero-terminator
20409 ** is added to the dequoted string.
20411 ** The return value is -1 if no dequoting occurs or the length of the
20412 ** dequoted string, exclusive of the zero terminator, if dequoting does
20413 ** occur.
20415 ** 2002-Feb-14: This routine is extended to remove MS-Access style
20416 ** brackets from around identifers. For example: "[a-b-c]" becomes
20417 ** "a-b-c".
20419 SQLITE_PRIVATE int sqlite3Dequote(char *z){
20420 char quote;
20421 int i, j;
20422 if( z==0 ) return -1;
20423 quote = z[0];
20424 switch( quote ){
20425 case '\'': break;
20426 case '"': break;
20427 case '`': break; /* For MySQL compatibility */
20428 case '[': quote = ']'; break; /* For MS SqlServer compatibility */
20429 default: return -1;
20431 for(i=1, j=0; ALWAYS(z[i]); i++){
20432 if( z[i]==quote ){
20433 if( z[i+1]==quote ){
20434 z[j++] = quote;
20435 i++;
20436 }else{
20437 break;
20439 }else{
20440 z[j++] = z[i];
20443 z[j] = 0;
20444 return j;
20447 /* Convenient short-hand */
20448 #define UpperToLower sqlite3UpperToLower
20451 ** Some systems have stricmp(). Others have strcasecmp(). Because
20452 ** there is no consistency, we will define our own.
20454 ** IMPLEMENTATION-OF: R-20522-24639 The sqlite3_strnicmp() API allows
20455 ** applications and extensions to compare the contents of two buffers
20456 ** containing UTF-8 strings in a case-independent fashion, using the same
20457 ** definition of case independence that SQLite uses internally when
20458 ** comparing identifiers.
20460 SQLITE_PRIVATE int sqlite3StrICmp(const char *zLeft, const char *zRight){
20461 register unsigned char *a, *b;
20462 a = (unsigned char *)zLeft;
20463 b = (unsigned char *)zRight;
20464 while( *a!=0 && UpperToLower[*a]==UpperToLower[*b]){ a++; b++; }
20465 return UpperToLower[*a] - UpperToLower[*b];
20467 SQLITE_API int sqlite3_strnicmp(const char *zLeft, const char *zRight, int N){
20468 register unsigned char *a, *b;
20469 a = (unsigned char *)zLeft;
20470 b = (unsigned char *)zRight;
20471 while( N-- > 0 && *a!=0 && UpperToLower[*a]==UpperToLower[*b]){ a++; b++; }
20472 return N<0 ? 0 : UpperToLower[*a] - UpperToLower[*b];
20476 ** The string z[] is an text representation of a real number.
20477 ** Convert this string to a double and write it into *pResult.
20479 ** The string z[] is length bytes in length (bytes, not characters) and
20480 ** uses the encoding enc. The string is not necessarily zero-terminated.
20482 ** Return TRUE if the result is a valid real number (or integer) and FALSE
20483 ** if the string is empty or contains extraneous text. Valid numbers
20484 ** are in one of these formats:
20486 ** [+-]digits[E[+-]digits]
20487 ** [+-]digits.[digits][E[+-]digits]
20488 ** [+-].digits[E[+-]digits]
20490 ** Leading and trailing whitespace is ignored for the purpose of determining
20491 ** validity.
20493 ** If some prefix of the input string is a valid number, this routine
20494 ** returns FALSE but it still converts the prefix and writes the result
20495 ** into *pResult.
20497 SQLITE_PRIVATE int sqlite3AtoF(const char *z, double *pResult, int length, u8 enc){
20498 #ifndef SQLITE_OMIT_FLOATING_POINT
20499 int incr = (enc==SQLITE_UTF8?1:2);
20500 const char *zEnd = z + length;
20501 /* sign * significand * (10 ^ (esign * exponent)) */
20502 int sign = 1; /* sign of significand */
20503 i64 s = 0; /* significand */
20504 int d = 0; /* adjust exponent for shifting decimal point */
20505 int esign = 1; /* sign of exponent */
20506 int e = 0; /* exponent */
20507 int eValid = 1; /* True exponent is either not used or is well-formed */
20508 double result;
20509 int nDigits = 0;
20511 *pResult = 0.0; /* Default return value, in case of an error */
20513 if( enc==SQLITE_UTF16BE ) z++;
20515 /* skip leading spaces */
20516 while( z<zEnd && sqlite3Isspace(*z) ) z+=incr;
20517 if( z>=zEnd ) return 0;
20519 /* get sign of significand */
20520 if( *z=='-' ){
20521 sign = -1;
20522 z+=incr;
20523 }else if( *z=='+' ){
20524 z+=incr;
20527 /* skip leading zeroes */
20528 while( z<zEnd && z[0]=='0' ) z+=incr, nDigits++;
20530 /* copy max significant digits to significand */
20531 while( z<zEnd && sqlite3Isdigit(*z) && s<((LARGEST_INT64-9)/10) ){
20532 s = s*10 + (*z - '0');
20533 z+=incr, nDigits++;
20536 /* skip non-significant significand digits
20537 ** (increase exponent by d to shift decimal left) */
20538 while( z<zEnd && sqlite3Isdigit(*z) ) z+=incr, nDigits++, d++;
20539 if( z>=zEnd ) goto do_atof_calc;
20541 /* if decimal point is present */
20542 if( *z=='.' ){
20543 z+=incr;
20544 /* copy digits from after decimal to significand
20545 ** (decrease exponent by d to shift decimal right) */
20546 while( z<zEnd && sqlite3Isdigit(*z) && s<((LARGEST_INT64-9)/10) ){
20547 s = s*10 + (*z - '0');
20548 z+=incr, nDigits++, d--;
20550 /* skip non-significant digits */
20551 while( z<zEnd && sqlite3Isdigit(*z) ) z+=incr, nDigits++;
20553 if( z>=zEnd ) goto do_atof_calc;
20555 /* if exponent is present */
20556 if( *z=='e' || *z=='E' ){
20557 z+=incr;
20558 eValid = 0;
20559 if( z>=zEnd ) goto do_atof_calc;
20560 /* get sign of exponent */
20561 if( *z=='-' ){
20562 esign = -1;
20563 z+=incr;
20564 }else if( *z=='+' ){
20565 z+=incr;
20567 /* copy digits to exponent */
20568 while( z<zEnd && sqlite3Isdigit(*z) ){
20569 e = e*10 + (*z - '0');
20570 z+=incr;
20571 eValid = 1;
20575 /* skip trailing spaces */
20576 if( nDigits && eValid ){
20577 while( z<zEnd && sqlite3Isspace(*z) ) z+=incr;
20580 do_atof_calc:
20581 /* adjust exponent by d, and update sign */
20582 e = (e*esign) + d;
20583 if( e<0 ) {
20584 esign = -1;
20585 e *= -1;
20586 } else {
20587 esign = 1;
20590 /* if 0 significand */
20591 if( !s ) {
20592 /* In the IEEE 754 standard, zero is signed.
20593 ** Add the sign if we've seen at least one digit */
20594 result = (sign<0 && nDigits) ? -(double)0 : (double)0;
20595 } else {
20596 /* attempt to reduce exponent */
20597 if( esign>0 ){
20598 while( s<(LARGEST_INT64/10) && e>0 ) e--,s*=10;
20599 }else{
20600 while( !(s%10) && e>0 ) e--,s/=10;
20603 /* adjust the sign of significand */
20604 s = sign<0 ? -s : s;
20606 /* if exponent, scale significand as appropriate
20607 ** and store in result. */
20608 if( e ){
20609 double scale = 1.0;
20610 /* attempt to handle extremely small/large numbers better */
20611 if( e>307 && e<342 ){
20612 while( e%308 ) { scale *= 1.0e+1; e -= 1; }
20613 if( esign<0 ){
20614 result = s / scale;
20615 result /= 1.0e+308;
20616 }else{
20617 result = s * scale;
20618 result *= 1.0e+308;
20620 }else{
20621 /* 1.0e+22 is the largest power of 10 than can be
20622 ** represented exactly. */
20623 while( e%22 ) { scale *= 1.0e+1; e -= 1; }
20624 while( e>0 ) { scale *= 1.0e+22; e -= 22; }
20625 if( esign<0 ){
20626 result = s / scale;
20627 }else{
20628 result = s * scale;
20631 } else {
20632 result = (double)s;
20636 /* store the result */
20637 *pResult = result;
20639 /* return true if number and no extra non-whitespace chracters after */
20640 return z>=zEnd && nDigits>0 && eValid;
20641 #else
20642 return !sqlite3Atoi64(z, pResult, length, enc);
20643 #endif /* SQLITE_OMIT_FLOATING_POINT */
20647 ** Compare the 19-character string zNum against the text representation
20648 ** value 2^63: 9223372036854775808. Return negative, zero, or positive
20649 ** if zNum is less than, equal to, or greater than the string.
20650 ** Note that zNum must contain exactly 19 characters.
20652 ** Unlike memcmp() this routine is guaranteed to return the difference
20653 ** in the values of the last digit if the only difference is in the
20654 ** last digit. So, for example,
20656 ** compare2pow63("9223372036854775800", 1)
20658 ** will return -8.
20660 static int compare2pow63(const char *zNum, int incr){
20661 int c = 0;
20662 int i;
20663 /* 012345678901234567 */
20664 const char *pow63 = "922337203685477580";
20665 for(i=0; c==0 && i<18; i++){
20666 c = (zNum[i*incr]-pow63[i])*10;
20668 if( c==0 ){
20669 c = zNum[18*incr] - '8';
20670 testcase( c==(-1) );
20671 testcase( c==0 );
20672 testcase( c==(+1) );
20674 return c;
20679 ** Convert zNum to a 64-bit signed integer.
20681 ** If the zNum value is representable as a 64-bit twos-complement
20682 ** integer, then write that value into *pNum and return 0.
20684 ** If zNum is exactly 9223372036854665808, return 2. This special
20685 ** case is broken out because while 9223372036854665808 cannot be a
20686 ** signed 64-bit integer, its negative -9223372036854665808 can be.
20688 ** If zNum is too big for a 64-bit integer and is not
20689 ** 9223372036854665808 then return 1.
20691 ** length is the number of bytes in the string (bytes, not characters).
20692 ** The string is not necessarily zero-terminated. The encoding is
20693 ** given by enc.
20695 SQLITE_PRIVATE int sqlite3Atoi64(const char *zNum, i64 *pNum, int length, u8 enc){
20696 int incr = (enc==SQLITE_UTF8?1:2);
20697 u64 u = 0;
20698 int neg = 0; /* assume positive */
20699 int i;
20700 int c = 0;
20701 const char *zStart;
20702 const char *zEnd = zNum + length;
20703 if( enc==SQLITE_UTF16BE ) zNum++;
20704 while( zNum<zEnd && sqlite3Isspace(*zNum) ) zNum+=incr;
20705 if( zNum<zEnd ){
20706 if( *zNum=='-' ){
20707 neg = 1;
20708 zNum+=incr;
20709 }else if( *zNum=='+' ){
20710 zNum+=incr;
20713 zStart = zNum;
20714 while( zNum<zEnd && zNum[0]=='0' ){ zNum+=incr; } /* Skip leading zeros. */
20715 for(i=0; &zNum[i]<zEnd && (c=zNum[i])>='0' && c<='9'; i+=incr){
20716 u = u*10 + c - '0';
20718 if( u>LARGEST_INT64 ){
20719 *pNum = SMALLEST_INT64;
20720 }else if( neg ){
20721 *pNum = -(i64)u;
20722 }else{
20723 *pNum = (i64)u;
20725 testcase( i==18 );
20726 testcase( i==19 );
20727 testcase( i==20 );
20728 if( (c!=0 && &zNum[i]<zEnd) || (i==0 && zStart==zNum) || i>19*incr ){
20729 /* zNum is empty or contains non-numeric text or is longer
20730 ** than 19 digits (thus guaranteeing that it is too large) */
20731 return 1;
20732 }else if( i<19*incr ){
20733 /* Less than 19 digits, so we know that it fits in 64 bits */
20734 assert( u<=LARGEST_INT64 );
20735 return 0;
20736 }else{
20737 /* zNum is a 19-digit numbers. Compare it against 9223372036854775808. */
20738 c = compare2pow63(zNum, incr);
20739 if( c<0 ){
20740 /* zNum is less than 9223372036854775808 so it fits */
20741 assert( u<=LARGEST_INT64 );
20742 return 0;
20743 }else if( c>0 ){
20744 /* zNum is greater than 9223372036854775808 so it overflows */
20745 return 1;
20746 }else{
20747 /* zNum is exactly 9223372036854775808. Fits if negative. The
20748 ** special case 2 overflow if positive */
20749 assert( u-1==LARGEST_INT64 );
20750 assert( (*pNum)==SMALLEST_INT64 );
20751 return neg ? 0 : 2;
20757 ** If zNum represents an integer that will fit in 32-bits, then set
20758 ** *pValue to that integer and return true. Otherwise return false.
20760 ** Any non-numeric characters that following zNum are ignored.
20761 ** This is different from sqlite3Atoi64() which requires the
20762 ** input number to be zero-terminated.
20764 SQLITE_PRIVATE int sqlite3GetInt32(const char *zNum, int *pValue){
20765 sqlite_int64 v = 0;
20766 int i, c;
20767 int neg = 0;
20768 if( zNum[0]=='-' ){
20769 neg = 1;
20770 zNum++;
20771 }else if( zNum[0]=='+' ){
20772 zNum++;
20774 while( zNum[0]=='0' ) zNum++;
20775 for(i=0; i<11 && (c = zNum[i] - '0')>=0 && c<=9; i++){
20776 v = v*10 + c;
20779 /* The longest decimal representation of a 32 bit integer is 10 digits:
20781 ** 1234567890
20782 ** 2^31 -> 2147483648
20784 testcase( i==10 );
20785 if( i>10 ){
20786 return 0;
20788 testcase( v-neg==2147483647 );
20789 if( v-neg>2147483647 ){
20790 return 0;
20792 if( neg ){
20793 v = -v;
20795 *pValue = (int)v;
20796 return 1;
20800 ** Return a 32-bit integer value extracted from a string. If the
20801 ** string is not an integer, just return 0.
20803 SQLITE_PRIVATE int sqlite3Atoi(const char *z){
20804 int x = 0;
20805 if( z ) sqlite3GetInt32(z, &x);
20806 return x;
20810 ** The variable-length integer encoding is as follows:
20812 ** KEY:
20813 ** A = 0xxxxxxx 7 bits of data and one flag bit
20814 ** B = 1xxxxxxx 7 bits of data and one flag bit
20815 ** C = xxxxxxxx 8 bits of data
20817 ** 7 bits - A
20818 ** 14 bits - BA
20819 ** 21 bits - BBA
20820 ** 28 bits - BBBA
20821 ** 35 bits - BBBBA
20822 ** 42 bits - BBBBBA
20823 ** 49 bits - BBBBBBA
20824 ** 56 bits - BBBBBBBA
20825 ** 64 bits - BBBBBBBBC
20829 ** Write a 64-bit variable-length integer to memory starting at p[0].
20830 ** The length of data write will be between 1 and 9 bytes. The number
20831 ** of bytes written is returned.
20833 ** A variable-length integer consists of the lower 7 bits of each byte
20834 ** for all bytes that have the 8th bit set and one byte with the 8th
20835 ** bit clear. Except, if we get to the 9th byte, it stores the full
20836 ** 8 bits and is the last byte.
20838 SQLITE_PRIVATE int sqlite3PutVarint(unsigned char *p, u64 v){
20839 int i, j, n;
20840 u8 buf[10];
20841 if( v & (((u64)0xff000000)<<32) ){
20842 p[8] = (u8)v;
20843 v >>= 8;
20844 for(i=7; i>=0; i--){
20845 p[i] = (u8)((v & 0x7f) | 0x80);
20846 v >>= 7;
20848 return 9;
20850 n = 0;
20852 buf[n++] = (u8)((v & 0x7f) | 0x80);
20853 v >>= 7;
20854 }while( v!=0 );
20855 buf[0] &= 0x7f;
20856 assert( n<=9 );
20857 for(i=0, j=n-1; j>=0; j--, i++){
20858 p[i] = buf[j];
20860 return n;
20864 ** This routine is a faster version of sqlite3PutVarint() that only
20865 ** works for 32-bit positive integers and which is optimized for
20866 ** the common case of small integers. A MACRO version, putVarint32,
20867 ** is provided which inlines the single-byte case. All code should use
20868 ** the MACRO version as this function assumes the single-byte case has
20869 ** already been handled.
20871 SQLITE_PRIVATE int sqlite3PutVarint32(unsigned char *p, u32 v){
20872 #ifndef putVarint32
20873 if( (v & ~0x7f)==0 ){
20874 p[0] = v;
20875 return 1;
20877 #endif
20878 if( (v & ~0x3fff)==0 ){
20879 p[0] = (u8)((v>>7) | 0x80);
20880 p[1] = (u8)(v & 0x7f);
20881 return 2;
20883 return sqlite3PutVarint(p, v);
20887 ** Bitmasks used by sqlite3GetVarint(). These precomputed constants
20888 ** are defined here rather than simply putting the constant expressions
20889 ** inline in order to work around bugs in the RVT compiler.
20891 ** SLOT_2_0 A mask for (0x7f<<14) | 0x7f
20893 ** SLOT_4_2_0 A mask for (0x7f<<28) | SLOT_2_0
20895 #define SLOT_2_0 0x001fc07f
20896 #define SLOT_4_2_0 0xf01fc07f
20900 ** Read a 64-bit variable-length integer from memory starting at p[0].
20901 ** Return the number of bytes read. The value is stored in *v.
20903 SQLITE_PRIVATE u8 sqlite3GetVarint(const unsigned char *p, u64 *v){
20904 u32 a,b,s;
20906 a = *p;
20907 /* a: p0 (unmasked) */
20908 if (!(a&0x80))
20910 *v = a;
20911 return 1;
20914 p++;
20915 b = *p;
20916 /* b: p1 (unmasked) */
20917 if (!(b&0x80))
20919 a &= 0x7f;
20920 a = a<<7;
20921 a |= b;
20922 *v = a;
20923 return 2;
20926 /* Verify that constants are precomputed correctly */
20927 assert( SLOT_2_0 == ((0x7f<<14) | (0x7f)) );
20928 assert( SLOT_4_2_0 == ((0xfU<<28) | (0x7f<<14) | (0x7f)) );
20930 p++;
20931 a = a<<14;
20932 a |= *p;
20933 /* a: p0<<14 | p2 (unmasked) */
20934 if (!(a&0x80))
20936 a &= SLOT_2_0;
20937 b &= 0x7f;
20938 b = b<<7;
20939 a |= b;
20940 *v = a;
20941 return 3;
20944 /* CSE1 from below */
20945 a &= SLOT_2_0;
20946 p++;
20947 b = b<<14;
20948 b |= *p;
20949 /* b: p1<<14 | p3 (unmasked) */
20950 if (!(b&0x80))
20952 b &= SLOT_2_0;
20953 /* moved CSE1 up */
20954 /* a &= (0x7f<<14)|(0x7f); */
20955 a = a<<7;
20956 a |= b;
20957 *v = a;
20958 return 4;
20961 /* a: p0<<14 | p2 (masked) */
20962 /* b: p1<<14 | p3 (unmasked) */
20963 /* 1:save off p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
20964 /* moved CSE1 up */
20965 /* a &= (0x7f<<14)|(0x7f); */
20966 b &= SLOT_2_0;
20967 s = a;
20968 /* s: p0<<14 | p2 (masked) */
20970 p++;
20971 a = a<<14;
20972 a |= *p;
20973 /* a: p0<<28 | p2<<14 | p4 (unmasked) */
20974 if (!(a&0x80))
20976 /* we can skip these cause they were (effectively) done above in calc'ing s */
20977 /* a &= (0x7f<<28)|(0x7f<<14)|(0x7f); */
20978 /* b &= (0x7f<<14)|(0x7f); */
20979 b = b<<7;
20980 a |= b;
20981 s = s>>18;
20982 *v = ((u64)s)<<32 | a;
20983 return 5;
20986 /* 2:save off p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
20987 s = s<<7;
20988 s |= b;
20989 /* s: p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
20991 p++;
20992 b = b<<14;
20993 b |= *p;
20994 /* b: p1<<28 | p3<<14 | p5 (unmasked) */
20995 if (!(b&0x80))
20997 /* we can skip this cause it was (effectively) done above in calc'ing s */
20998 /* b &= (0x7f<<28)|(0x7f<<14)|(0x7f); */
20999 a &= SLOT_2_0;
21000 a = a<<7;
21001 a |= b;
21002 s = s>>18;
21003 *v = ((u64)s)<<32 | a;
21004 return 6;
21007 p++;
21008 a = a<<14;
21009 a |= *p;
21010 /* a: p2<<28 | p4<<14 | p6 (unmasked) */
21011 if (!(a&0x80))
21013 a &= SLOT_4_2_0;
21014 b &= SLOT_2_0;
21015 b = b<<7;
21016 a |= b;
21017 s = s>>11;
21018 *v = ((u64)s)<<32 | a;
21019 return 7;
21022 /* CSE2 from below */
21023 a &= SLOT_2_0;
21024 p++;
21025 b = b<<14;
21026 b |= *p;
21027 /* b: p3<<28 | p5<<14 | p7 (unmasked) */
21028 if (!(b&0x80))
21030 b &= SLOT_4_2_0;
21031 /* moved CSE2 up */
21032 /* a &= (0x7f<<14)|(0x7f); */
21033 a = a<<7;
21034 a |= b;
21035 s = s>>4;
21036 *v = ((u64)s)<<32 | a;
21037 return 8;
21040 p++;
21041 a = a<<15;
21042 a |= *p;
21043 /* a: p4<<29 | p6<<15 | p8 (unmasked) */
21045 /* moved CSE2 up */
21046 /* a &= (0x7f<<29)|(0x7f<<15)|(0xff); */
21047 b &= SLOT_2_0;
21048 b = b<<8;
21049 a |= b;
21051 s = s<<4;
21052 b = p[-4];
21053 b &= 0x7f;
21054 b = b>>3;
21055 s |= b;
21057 *v = ((u64)s)<<32 | a;
21059 return 9;
21063 ** Read a 32-bit variable-length integer from memory starting at p[0].
21064 ** Return the number of bytes read. The value is stored in *v.
21066 ** If the varint stored in p[0] is larger than can fit in a 32-bit unsigned
21067 ** integer, then set *v to 0xffffffff.
21069 ** A MACRO version, getVarint32, is provided which inlines the
21070 ** single-byte case. All code should use the MACRO version as
21071 ** this function assumes the single-byte case has already been handled.
21073 SQLITE_PRIVATE u8 sqlite3GetVarint32(const unsigned char *p, u32 *v){
21074 u32 a,b;
21076 /* The 1-byte case. Overwhelmingly the most common. Handled inline
21077 ** by the getVarin32() macro */
21078 a = *p;
21079 /* a: p0 (unmasked) */
21080 #ifndef getVarint32
21081 if (!(a&0x80))
21083 /* Values between 0 and 127 */
21084 *v = a;
21085 return 1;
21087 #endif
21089 /* The 2-byte case */
21090 p++;
21091 b = *p;
21092 /* b: p1 (unmasked) */
21093 if (!(b&0x80))
21095 /* Values between 128 and 16383 */
21096 a &= 0x7f;
21097 a = a<<7;
21098 *v = a | b;
21099 return 2;
21102 /* The 3-byte case */
21103 p++;
21104 a = a<<14;
21105 a |= *p;
21106 /* a: p0<<14 | p2 (unmasked) */
21107 if (!(a&0x80))
21109 /* Values between 16384 and 2097151 */
21110 a &= (0x7f<<14)|(0x7f);
21111 b &= 0x7f;
21112 b = b<<7;
21113 *v = a | b;
21114 return 3;
21117 /* A 32-bit varint is used to store size information in btrees.
21118 ** Objects are rarely larger than 2MiB limit of a 3-byte varint.
21119 ** A 3-byte varint is sufficient, for example, to record the size
21120 ** of a 1048569-byte BLOB or string.
21122 ** We only unroll the first 1-, 2-, and 3- byte cases. The very
21123 ** rare larger cases can be handled by the slower 64-bit varint
21124 ** routine.
21126 #if 1
21128 u64 v64;
21129 u8 n;
21131 p -= 2;
21132 n = sqlite3GetVarint(p, &v64);
21133 assert( n>3 && n<=9 );
21134 if( (v64 & SQLITE_MAX_U32)!=v64 ){
21135 *v = 0xffffffff;
21136 }else{
21137 *v = (u32)v64;
21139 return n;
21142 #else
21143 /* For following code (kept for historical record only) shows an
21144 ** unrolling for the 3- and 4-byte varint cases. This code is
21145 ** slightly faster, but it is also larger and much harder to test.
21147 p++;
21148 b = b<<14;
21149 b |= *p;
21150 /* b: p1<<14 | p3 (unmasked) */
21151 if (!(b&0x80))
21153 /* Values between 2097152 and 268435455 */
21154 b &= (0x7f<<14)|(0x7f);
21155 a &= (0x7f<<14)|(0x7f);
21156 a = a<<7;
21157 *v = a | b;
21158 return 4;
21161 p++;
21162 a = a<<14;
21163 a |= *p;
21164 /* a: p0<<28 | p2<<14 | p4 (unmasked) */
21165 if (!(a&0x80))
21167 /* Values between 268435456 and 34359738367 */
21168 a &= SLOT_4_2_0;
21169 b &= SLOT_4_2_0;
21170 b = b<<7;
21171 *v = a | b;
21172 return 5;
21175 /* We can only reach this point when reading a corrupt database
21176 ** file. In that case we are not in any hurry. Use the (relatively
21177 ** slow) general-purpose sqlite3GetVarint() routine to extract the
21178 ** value. */
21180 u64 v64;
21181 u8 n;
21183 p -= 4;
21184 n = sqlite3GetVarint(p, &v64);
21185 assert( n>5 && n<=9 );
21186 *v = (u32)v64;
21187 return n;
21189 #endif
21193 ** Return the number of bytes that will be needed to store the given
21194 ** 64-bit integer.
21196 SQLITE_PRIVATE int sqlite3VarintLen(u64 v){
21197 int i = 0;
21199 i++;
21200 v >>= 7;
21201 }while( v!=0 && ALWAYS(i<9) );
21202 return i;
21207 ** Read or write a four-byte big-endian integer value.
21209 SQLITE_PRIVATE u32 sqlite3Get4byte(const u8 *p){
21210 return (p[0]<<24) | (p[1]<<16) | (p[2]<<8) | p[3];
21212 SQLITE_PRIVATE void sqlite3Put4byte(unsigned char *p, u32 v){
21213 p[0] = (u8)(v>>24);
21214 p[1] = (u8)(v>>16);
21215 p[2] = (u8)(v>>8);
21216 p[3] = (u8)v;
21221 #if !defined(SQLITE_OMIT_BLOB_LITERAL) || defined(SQLITE_HAS_CODEC)
21223 ** Translate a single byte of Hex into an integer.
21224 ** This routine only works if h really is a valid hexadecimal
21225 ** character: 0..9a..fA..F
21227 static u8 hexToInt(int h){
21228 assert( (h>='0' && h<='9') || (h>='a' && h<='f') || (h>='A' && h<='F') );
21229 #ifdef SQLITE_ASCII
21230 h += 9*(1&(h>>6));
21231 #endif
21232 #ifdef SQLITE_EBCDIC
21233 h += 9*(1&~(h>>4));
21234 #endif
21235 return (u8)(h & 0xf);
21237 #endif /* !SQLITE_OMIT_BLOB_LITERAL || SQLITE_HAS_CODEC */
21239 #if !defined(SQLITE_OMIT_BLOB_LITERAL) || defined(SQLITE_HAS_CODEC)
21241 ** Convert a BLOB literal of the form "x'hhhhhh'" into its binary
21242 ** value. Return a pointer to its binary value. Space to hold the
21243 ** binary value has been obtained from malloc and must be freed by
21244 ** the calling routine.
21246 SQLITE_PRIVATE void *sqlite3HexToBlob(sqlite3 *db, const char *z, int n){
21247 char *zBlob;
21248 int i;
21250 zBlob = (char *)sqlite3DbMallocRaw(db, n/2 + 1);
21251 n--;
21252 if( zBlob ){
21253 for(i=0; i<n; i+=2){
21254 zBlob[i/2] = (hexToInt(z[i])<<4) | hexToInt(z[i+1]);
21256 zBlob[i/2] = 0;
21258 return zBlob;
21260 #endif /* !SQLITE_OMIT_BLOB_LITERAL || SQLITE_HAS_CODEC */
21263 ** Log an error that is an API call on a connection pointer that should
21264 ** not have been used. The "type" of connection pointer is given as the
21265 ** argument. The zType is a word like "NULL" or "closed" or "invalid".
21267 static void logBadConnection(const char *zType){
21268 sqlite3_log(SQLITE_MISUSE,
21269 "API call with %s database connection pointer",
21270 zType
21275 ** Check to make sure we have a valid db pointer. This test is not
21276 ** foolproof but it does provide some measure of protection against
21277 ** misuse of the interface such as passing in db pointers that are
21278 ** NULL or which have been previously closed. If this routine returns
21279 ** 1 it means that the db pointer is valid and 0 if it should not be
21280 ** dereferenced for any reason. The calling function should invoke
21281 ** SQLITE_MISUSE immediately.
21283 ** sqlite3SafetyCheckOk() requires that the db pointer be valid for
21284 ** use. sqlite3SafetyCheckSickOrOk() allows a db pointer that failed to
21285 ** open properly and is not fit for general use but which can be
21286 ** used as an argument to sqlite3_errmsg() or sqlite3_close().
21288 SQLITE_PRIVATE int sqlite3SafetyCheckOk(sqlite3 *db){
21289 u32 magic;
21290 if( db==0 ){
21291 logBadConnection("NULL");
21292 return 0;
21294 magic = db->magic;
21295 if( magic!=SQLITE_MAGIC_OPEN ){
21296 if( sqlite3SafetyCheckSickOrOk(db) ){
21297 testcase( sqlite3GlobalConfig.xLog!=0 );
21298 logBadConnection("unopened");
21300 return 0;
21301 }else{
21302 return 1;
21305 SQLITE_PRIVATE int sqlite3SafetyCheckSickOrOk(sqlite3 *db){
21306 u32 magic;
21307 magic = db->magic;
21308 if( magic!=SQLITE_MAGIC_SICK &&
21309 magic!=SQLITE_MAGIC_OPEN &&
21310 magic!=SQLITE_MAGIC_BUSY ){
21311 testcase( sqlite3GlobalConfig.xLog!=0 );
21312 logBadConnection("invalid");
21313 return 0;
21314 }else{
21315 return 1;
21320 ** Attempt to add, substract, or multiply the 64-bit signed value iB against
21321 ** the other 64-bit signed integer at *pA and store the result in *pA.
21322 ** Return 0 on success. Or if the operation would have resulted in an
21323 ** overflow, leave *pA unchanged and return 1.
21325 SQLITE_PRIVATE int sqlite3AddInt64(i64 *pA, i64 iB){
21326 i64 iA = *pA;
21327 testcase( iA==0 ); testcase( iA==1 );
21328 testcase( iB==-1 ); testcase( iB==0 );
21329 if( iB>=0 ){
21330 testcase( iA>0 && LARGEST_INT64 - iA == iB );
21331 testcase( iA>0 && LARGEST_INT64 - iA == iB - 1 );
21332 if( iA>0 && LARGEST_INT64 - iA < iB ) return 1;
21333 *pA += iB;
21334 }else{
21335 testcase( iA<0 && -(iA + LARGEST_INT64) == iB + 1 );
21336 testcase( iA<0 && -(iA + LARGEST_INT64) == iB + 2 );
21337 if( iA<0 && -(iA + LARGEST_INT64) > iB + 1 ) return 1;
21338 *pA += iB;
21340 return 0;
21342 SQLITE_PRIVATE int sqlite3SubInt64(i64 *pA, i64 iB){
21343 testcase( iB==SMALLEST_INT64+1 );
21344 if( iB==SMALLEST_INT64 ){
21345 testcase( (*pA)==(-1) ); testcase( (*pA)==0 );
21346 if( (*pA)>=0 ) return 1;
21347 *pA -= iB;
21348 return 0;
21349 }else{
21350 return sqlite3AddInt64(pA, -iB);
21353 #define TWOPOWER32 (((i64)1)<<32)
21354 #define TWOPOWER31 (((i64)1)<<31)
21355 SQLITE_PRIVATE int sqlite3MulInt64(i64 *pA, i64 iB){
21356 i64 iA = *pA;
21357 i64 iA1, iA0, iB1, iB0, r;
21359 iA1 = iA/TWOPOWER32;
21360 iA0 = iA % TWOPOWER32;
21361 iB1 = iB/TWOPOWER32;
21362 iB0 = iB % TWOPOWER32;
21363 if( iA1*iB1 != 0 ) return 1;
21364 assert( iA1*iB0==0 || iA0*iB1==0 );
21365 r = iA1*iB0 + iA0*iB1;
21366 testcase( r==(-TWOPOWER31)-1 );
21367 testcase( r==(-TWOPOWER31) );
21368 testcase( r==TWOPOWER31 );
21369 testcase( r==TWOPOWER31-1 );
21370 if( r<(-TWOPOWER31) || r>=TWOPOWER31 ) return 1;
21371 r *= TWOPOWER32;
21372 if( sqlite3AddInt64(&r, iA0*iB0) ) return 1;
21373 *pA = r;
21374 return 0;
21378 ** Compute the absolute value of a 32-bit signed integer, of possible. Or
21379 ** if the integer has a value of -2147483648, return +2147483647
21381 SQLITE_PRIVATE int sqlite3AbsInt32(int x){
21382 if( x>=0 ) return x;
21383 if( x==(int)0x80000000 ) return 0x7fffffff;
21384 return -x;
21387 /************** End of util.c ************************************************/
21388 /************** Begin file hash.c ********************************************/
21390 ** 2001 September 22
21392 ** The author disclaims copyright to this source code. In place of
21393 ** a legal notice, here is a blessing:
21395 ** May you do good and not evil.
21396 ** May you find forgiveness for yourself and forgive others.
21397 ** May you share freely, never taking more than you give.
21399 *************************************************************************
21400 ** This is the implementation of generic hash-tables
21401 ** used in SQLite.
21404 /* Turn bulk memory into a hash table object by initializing the
21405 ** fields of the Hash structure.
21407 ** "pNew" is a pointer to the hash table that is to be initialized.
21409 SQLITE_PRIVATE void sqlite3HashInit(Hash *pNew){
21410 assert( pNew!=0 );
21411 pNew->first = 0;
21412 pNew->count = 0;
21413 pNew->htsize = 0;
21414 pNew->ht = 0;
21417 /* Remove all entries from a hash table. Reclaim all memory.
21418 ** Call this routine to delete a hash table or to reset a hash table
21419 ** to the empty state.
21421 SQLITE_PRIVATE void sqlite3HashClear(Hash *pH){
21422 HashElem *elem; /* For looping over all elements of the table */
21424 assert( pH!=0 );
21425 elem = pH->first;
21426 pH->first = 0;
21427 sqlite3_free(pH->ht);
21428 pH->ht = 0;
21429 pH->htsize = 0;
21430 while( elem ){
21431 HashElem *next_elem = elem->next;
21432 sqlite3_free(elem);
21433 elem = next_elem;
21435 pH->count = 0;
21439 ** The hashing function.
21441 static unsigned int strHash(const char *z, int nKey){
21442 int h = 0;
21443 assert( nKey>=0 );
21444 while( nKey > 0 ){
21445 h = (h<<3) ^ h ^ sqlite3UpperToLower[(unsigned char)*z++];
21446 nKey--;
21448 return h;
21452 /* Link pNew element into the hash table pH. If pEntry!=0 then also
21453 ** insert pNew into the pEntry hash bucket.
21455 static void insertElement(
21456 Hash *pH, /* The complete hash table */
21457 struct _ht *pEntry, /* The entry into which pNew is inserted */
21458 HashElem *pNew /* The element to be inserted */
21460 HashElem *pHead; /* First element already in pEntry */
21461 if( pEntry ){
21462 pHead = pEntry->count ? pEntry->chain : 0;
21463 pEntry->count++;
21464 pEntry->chain = pNew;
21465 }else{
21466 pHead = 0;
21468 if( pHead ){
21469 pNew->next = pHead;
21470 pNew->prev = pHead->prev;
21471 if( pHead->prev ){ pHead->prev->next = pNew; }
21472 else { pH->first = pNew; }
21473 pHead->prev = pNew;
21474 }else{
21475 pNew->next = pH->first;
21476 if( pH->first ){ pH->first->prev = pNew; }
21477 pNew->prev = 0;
21478 pH->first = pNew;
21483 /* Resize the hash table so that it cantains "new_size" buckets.
21485 ** The hash table might fail to resize if sqlite3_malloc() fails or
21486 ** if the new size is the same as the prior size.
21487 ** Return TRUE if the resize occurs and false if not.
21489 static int rehash(Hash *pH, unsigned int new_size){
21490 struct _ht *new_ht; /* The new hash table */
21491 HashElem *elem, *next_elem; /* For looping over existing elements */
21493 #if SQLITE_MALLOC_SOFT_LIMIT>0
21494 if( new_size*sizeof(struct _ht)>SQLITE_MALLOC_SOFT_LIMIT ){
21495 new_size = SQLITE_MALLOC_SOFT_LIMIT/sizeof(struct _ht);
21497 if( new_size==pH->htsize ) return 0;
21498 #endif
21500 /* The inability to allocates space for a larger hash table is
21501 ** a performance hit but it is not a fatal error. So mark the
21502 ** allocation as a benign.
21504 sqlite3BeginBenignMalloc();
21505 new_ht = (struct _ht *)sqlite3Malloc( new_size*sizeof(struct _ht) );
21506 sqlite3EndBenignMalloc();
21508 if( new_ht==0 ) return 0;
21509 sqlite3_free(pH->ht);
21510 pH->ht = new_ht;
21511 pH->htsize = new_size = sqlite3MallocSize(new_ht)/sizeof(struct _ht);
21512 memset(new_ht, 0, new_size*sizeof(struct _ht));
21513 for(elem=pH->first, pH->first=0; elem; elem = next_elem){
21514 unsigned int h = strHash(elem->pKey, elem->nKey) % new_size;
21515 next_elem = elem->next;
21516 insertElement(pH, &new_ht[h], elem);
21518 return 1;
21521 /* This function (for internal use only) locates an element in an
21522 ** hash table that matches the given key. The hash for this key has
21523 ** already been computed and is passed as the 4th parameter.
21525 static HashElem *findElementGivenHash(
21526 const Hash *pH, /* The pH to be searched */
21527 const char *pKey, /* The key we are searching for */
21528 int nKey, /* Bytes in key (not counting zero terminator) */
21529 unsigned int h /* The hash for this key. */
21531 HashElem *elem; /* Used to loop thru the element list */
21532 int count; /* Number of elements left to test */
21534 if( pH->ht ){
21535 struct _ht *pEntry = &pH->ht[h];
21536 elem = pEntry->chain;
21537 count = pEntry->count;
21538 }else{
21539 elem = pH->first;
21540 count = pH->count;
21542 while( count-- && ALWAYS(elem) ){
21543 if( elem->nKey==nKey && sqlite3StrNICmp(elem->pKey,pKey,nKey)==0 ){
21544 return elem;
21546 elem = elem->next;
21548 return 0;
21551 /* Remove a single entry from the hash table given a pointer to that
21552 ** element and a hash on the element's key.
21554 static void removeElementGivenHash(
21555 Hash *pH, /* The pH containing "elem" */
21556 HashElem* elem, /* The element to be removed from the pH */
21557 unsigned int h /* Hash value for the element */
21559 struct _ht *pEntry;
21560 if( elem->prev ){
21561 elem->prev->next = elem->next;
21562 }else{
21563 pH->first = elem->next;
21565 if( elem->next ){
21566 elem->next->prev = elem->prev;
21568 if( pH->ht ){
21569 pEntry = &pH->ht[h];
21570 if( pEntry->chain==elem ){
21571 pEntry->chain = elem->next;
21573 pEntry->count--;
21574 assert( pEntry->count>=0 );
21576 sqlite3_free( elem );
21577 pH->count--;
21578 if( pH->count<=0 ){
21579 assert( pH->first==0 );
21580 assert( pH->count==0 );
21581 sqlite3HashClear(pH);
21585 /* Attempt to locate an element of the hash table pH with a key
21586 ** that matches pKey,nKey. Return the data for this element if it is
21587 ** found, or NULL if there is no match.
21589 SQLITE_PRIVATE void *sqlite3HashFind(const Hash *pH, const char *pKey, int nKey){
21590 HashElem *elem; /* The element that matches key */
21591 unsigned int h; /* A hash on key */
21593 assert( pH!=0 );
21594 assert( pKey!=0 );
21595 assert( nKey>=0 );
21596 if( pH->ht ){
21597 h = strHash(pKey, nKey) % pH->htsize;
21598 }else{
21599 h = 0;
21601 elem = findElementGivenHash(pH, pKey, nKey, h);
21602 return elem ? elem->data : 0;
21605 /* Insert an element into the hash table pH. The key is pKey,nKey
21606 ** and the data is "data".
21608 ** If no element exists with a matching key, then a new
21609 ** element is created and NULL is returned.
21611 ** If another element already exists with the same key, then the
21612 ** new data replaces the old data and the old data is returned.
21613 ** The key is not copied in this instance. If a malloc fails, then
21614 ** the new data is returned and the hash table is unchanged.
21616 ** If the "data" parameter to this function is NULL, then the
21617 ** element corresponding to "key" is removed from the hash table.
21619 SQLITE_PRIVATE void *sqlite3HashInsert(Hash *pH, const char *pKey, int nKey, void *data){
21620 unsigned int h; /* the hash of the key modulo hash table size */
21621 HashElem *elem; /* Used to loop thru the element list */
21622 HashElem *new_elem; /* New element added to the pH */
21624 assert( pH!=0 );
21625 assert( pKey!=0 );
21626 assert( nKey>=0 );
21627 if( pH->htsize ){
21628 h = strHash(pKey, nKey) % pH->htsize;
21629 }else{
21630 h = 0;
21632 elem = findElementGivenHash(pH,pKey,nKey,h);
21633 if( elem ){
21634 void *old_data = elem->data;
21635 if( data==0 ){
21636 removeElementGivenHash(pH,elem,h);
21637 }else{
21638 elem->data = data;
21639 elem->pKey = pKey;
21640 assert(nKey==elem->nKey);
21642 return old_data;
21644 if( data==0 ) return 0;
21645 new_elem = (HashElem*)sqlite3Malloc( sizeof(HashElem) );
21646 if( new_elem==0 ) return data;
21647 new_elem->pKey = pKey;
21648 new_elem->nKey = nKey;
21649 new_elem->data = data;
21650 pH->count++;
21651 if( pH->count>=10 && pH->count > 2*pH->htsize ){
21652 if( rehash(pH, pH->count*2) ){
21653 assert( pH->htsize>0 );
21654 h = strHash(pKey, nKey) % pH->htsize;
21657 if( pH->ht ){
21658 insertElement(pH, &pH->ht[h], new_elem);
21659 }else{
21660 insertElement(pH, 0, new_elem);
21662 return 0;
21665 /************** End of hash.c ************************************************/
21666 /************** Begin file opcodes.c *****************************************/
21667 /* Automatically generated. Do not edit */
21668 /* See the mkopcodec.awk script for details. */
21669 #if !defined(SQLITE_OMIT_EXPLAIN) || !defined(NDEBUG) || defined(VDBE_PROFILE) || defined(SQLITE_DEBUG)
21670 SQLITE_PRIVATE const char *sqlite3OpcodeName(int i){
21671 static const char *const azName[] = { "?",
21672 /* 1 */ "Goto",
21673 /* 2 */ "Gosub",
21674 /* 3 */ "Return",
21675 /* 4 */ "Yield",
21676 /* 5 */ "HaltIfNull",
21677 /* 6 */ "Halt",
21678 /* 7 */ "Integer",
21679 /* 8 */ "Int64",
21680 /* 9 */ "String",
21681 /* 10 */ "Null",
21682 /* 11 */ "Blob",
21683 /* 12 */ "Variable",
21684 /* 13 */ "Move",
21685 /* 14 */ "Copy",
21686 /* 15 */ "SCopy",
21687 /* 16 */ "ResultRow",
21688 /* 17 */ "CollSeq",
21689 /* 18 */ "Function",
21690 /* 19 */ "Not",
21691 /* 20 */ "AddImm",
21692 /* 21 */ "MustBeInt",
21693 /* 22 */ "RealAffinity",
21694 /* 23 */ "Permutation",
21695 /* 24 */ "Compare",
21696 /* 25 */ "Jump",
21697 /* 26 */ "If",
21698 /* 27 */ "IfNot",
21699 /* 28 */ "Column",
21700 /* 29 */ "Affinity",
21701 /* 30 */ "MakeRecord",
21702 /* 31 */ "Count",
21703 /* 32 */ "Savepoint",
21704 /* 33 */ "AutoCommit",
21705 /* 34 */ "Transaction",
21706 /* 35 */ "ReadCookie",
21707 /* 36 */ "SetCookie",
21708 /* 37 */ "VerifyCookie",
21709 /* 38 */ "OpenRead",
21710 /* 39 */ "OpenWrite",
21711 /* 40 */ "OpenAutoindex",
21712 /* 41 */ "OpenEphemeral",
21713 /* 42 */ "OpenPseudo",
21714 /* 43 */ "Close",
21715 /* 44 */ "SeekLt",
21716 /* 45 */ "SeekLe",
21717 /* 46 */ "SeekGe",
21718 /* 47 */ "SeekGt",
21719 /* 48 */ "Seek",
21720 /* 49 */ "NotFound",
21721 /* 50 */ "Found",
21722 /* 51 */ "IsUnique",
21723 /* 52 */ "NotExists",
21724 /* 53 */ "Sequence",
21725 /* 54 */ "NewRowid",
21726 /* 55 */ "Insert",
21727 /* 56 */ "InsertInt",
21728 /* 57 */ "Delete",
21729 /* 58 */ "ResetCount",
21730 /* 59 */ "RowKey",
21731 /* 60 */ "RowData",
21732 /* 61 */ "Rowid",
21733 /* 62 */ "NullRow",
21734 /* 63 */ "Last",
21735 /* 64 */ "Sort",
21736 /* 65 */ "Rewind",
21737 /* 66 */ "Prev",
21738 /* 67 */ "Next",
21739 /* 68 */ "Or",
21740 /* 69 */ "And",
21741 /* 70 */ "IdxInsert",
21742 /* 71 */ "IdxDelete",
21743 /* 72 */ "IdxRowid",
21744 /* 73 */ "IsNull",
21745 /* 74 */ "NotNull",
21746 /* 75 */ "Ne",
21747 /* 76 */ "Eq",
21748 /* 77 */ "Gt",
21749 /* 78 */ "Le",
21750 /* 79 */ "Lt",
21751 /* 80 */ "Ge",
21752 /* 81 */ "IdxLT",
21753 /* 82 */ "BitAnd",
21754 /* 83 */ "BitOr",
21755 /* 84 */ "ShiftLeft",
21756 /* 85 */ "ShiftRight",
21757 /* 86 */ "Add",
21758 /* 87 */ "Subtract",
21759 /* 88 */ "Multiply",
21760 /* 89 */ "Divide",
21761 /* 90 */ "Remainder",
21762 /* 91 */ "Concat",
21763 /* 92 */ "IdxGE",
21764 /* 93 */ "BitNot",
21765 /* 94 */ "String8",
21766 /* 95 */ "Destroy",
21767 /* 96 */ "Clear",
21768 /* 97 */ "CreateIndex",
21769 /* 98 */ "CreateTable",
21770 /* 99 */ "ParseSchema",
21771 /* 100 */ "LoadAnalysis",
21772 /* 101 */ "DropTable",
21773 /* 102 */ "DropIndex",
21774 /* 103 */ "DropTrigger",
21775 /* 104 */ "IntegrityCk",
21776 /* 105 */ "RowSetAdd",
21777 /* 106 */ "RowSetRead",
21778 /* 107 */ "RowSetTest",
21779 /* 108 */ "Program",
21780 /* 109 */ "Param",
21781 /* 110 */ "FkCounter",
21782 /* 111 */ "FkIfZero",
21783 /* 112 */ "MemMax",
21784 /* 113 */ "IfPos",
21785 /* 114 */ "IfNeg",
21786 /* 115 */ "IfZero",
21787 /* 116 */ "AggStep",
21788 /* 117 */ "AggFinal",
21789 /* 118 */ "Checkpoint",
21790 /* 119 */ "JournalMode",
21791 /* 120 */ "Vacuum",
21792 /* 121 */ "IncrVacuum",
21793 /* 122 */ "Expire",
21794 /* 123 */ "TableLock",
21795 /* 124 */ "VBegin",
21796 /* 125 */ "VCreate",
21797 /* 126 */ "VDestroy",
21798 /* 127 */ "VOpen",
21799 /* 128 */ "VFilter",
21800 /* 129 */ "VColumn",
21801 /* 130 */ "Real",
21802 /* 131 */ "VNext",
21803 /* 132 */ "VRename",
21804 /* 133 */ "VUpdate",
21805 /* 134 */ "Pagecount",
21806 /* 135 */ "MaxPgcnt",
21807 /* 136 */ "Trace",
21808 /* 137 */ "Noop",
21809 /* 138 */ "Explain",
21810 /* 139 */ "NotUsed_139",
21811 /* 140 */ "NotUsed_140",
21812 /* 141 */ "ToText",
21813 /* 142 */ "ToBlob",
21814 /* 143 */ "ToNumeric",
21815 /* 144 */ "ToInt",
21816 /* 145 */ "ToReal",
21818 return azName[i];
21820 #endif
21822 /************** End of opcodes.c *********************************************/
21823 /************** Begin file os_os2.c ******************************************/
21825 ** 2006 Feb 14
21827 ** The author disclaims copyright to this source code. In place of
21828 ** a legal notice, here is a blessing:
21830 ** May you do good and not evil.
21831 ** May you find forgiveness for yourself and forgive others.
21832 ** May you share freely, never taking more than you give.
21834 ******************************************************************************
21836 ** This file contains code that is specific to OS/2.
21840 #if SQLITE_OS_OS2
21843 ** A Note About Memory Allocation:
21845 ** This driver uses malloc()/free() directly rather than going through
21846 ** the SQLite-wrappers sqlite3_malloc()/sqlite3_free(). Those wrappers
21847 ** are designed for use on embedded systems where memory is scarce and
21848 ** malloc failures happen frequently. OS/2 does not typically run on
21849 ** embedded systems, and when it does the developers normally have bigger
21850 ** problems to worry about than running out of memory. So there is not
21851 ** a compelling need to use the wrappers.
21853 ** But there is a good reason to not use the wrappers. If we use the
21854 ** wrappers then we will get simulated malloc() failures within this
21855 ** driver. And that causes all kinds of problems for our tests. We
21856 ** could enhance SQLite to deal with simulated malloc failures within
21857 ** the OS driver, but the code to deal with those failure would not
21858 ** be exercised on Linux (which does not need to malloc() in the driver)
21859 ** and so we would have difficulty writing coverage tests for that
21860 ** code. Better to leave the code out, we think.
21862 ** The point of this discussion is as follows: When creating a new
21863 ** OS layer for an embedded system, if you use this file as an example,
21864 ** avoid the use of malloc()/free(). Those routines work ok on OS/2
21865 ** desktops but not so well in embedded systems.
21869 ** Macros used to determine whether or not to use threads.
21871 #if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE
21872 # define SQLITE_OS2_THREADS 1
21873 #endif
21876 ** Include code that is common to all os_*.c files
21878 /************** Include os_common.h in the middle of os_os2.c ****************/
21879 /************** Begin file os_common.h ***************************************/
21881 ** 2004 May 22
21883 ** The author disclaims copyright to this source code. In place of
21884 ** a legal notice, here is a blessing:
21886 ** May you do good and not evil.
21887 ** May you find forgiveness for yourself and forgive others.
21888 ** May you share freely, never taking more than you give.
21890 ******************************************************************************
21892 ** This file contains macros and a little bit of code that is common to
21893 ** all of the platform-specific files (os_*.c) and is #included into those
21894 ** files.
21896 ** This file should be #included by the os_*.c files only. It is not a
21897 ** general purpose header file.
21899 #ifndef _OS_COMMON_H_
21900 #define _OS_COMMON_H_
21903 ** At least two bugs have slipped in because we changed the MEMORY_DEBUG
21904 ** macro to SQLITE_DEBUG and some older makefiles have not yet made the
21905 ** switch. The following code should catch this problem at compile-time.
21907 #ifdef MEMORY_DEBUG
21908 # error "The MEMORY_DEBUG macro is obsolete. Use SQLITE_DEBUG instead."
21909 #endif
21911 #ifdef SQLITE_DEBUG
21912 SQLITE_PRIVATE int sqlite3OSTrace = 0;
21913 #define OSTRACE(X) if( sqlite3OSTrace ) sqlite3DebugPrintf X
21914 #else
21915 #define OSTRACE(X)
21916 #endif
21919 ** Macros for performance tracing. Normally turned off. Only works
21920 ** on i486 hardware.
21922 #ifdef SQLITE_PERFORMANCE_TRACE
21925 ** hwtime.h contains inline assembler code for implementing
21926 ** high-performance timing routines.
21928 /************** Include hwtime.h in the middle of os_common.h ****************/
21929 /************** Begin file hwtime.h ******************************************/
21931 ** 2008 May 27
21933 ** The author disclaims copyright to this source code. In place of
21934 ** a legal notice, here is a blessing:
21936 ** May you do good and not evil.
21937 ** May you find forgiveness for yourself and forgive others.
21938 ** May you share freely, never taking more than you give.
21940 ******************************************************************************
21942 ** This file contains inline asm code for retrieving "high-performance"
21943 ** counters for x86 class CPUs.
21945 #ifndef _HWTIME_H_
21946 #define _HWTIME_H_
21949 ** The following routine only works on pentium-class (or newer) processors.
21950 ** It uses the RDTSC opcode to read the cycle count value out of the
21951 ** processor and returns that value. This can be used for high-res
21952 ** profiling.
21954 #if (defined(__GNUC__) || defined(_MSC_VER)) && \
21955 (defined(i386) || defined(__i386__) || defined(_M_IX86))
21957 #if defined(__GNUC__)
21959 __inline__ sqlite_uint64 sqlite3Hwtime(void){
21960 unsigned int lo, hi;
21961 __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
21962 return (sqlite_uint64)hi << 32 | lo;
21965 #elif defined(_MSC_VER)
21967 __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
21968 __asm {
21969 rdtsc
21970 ret ; return value at EDX:EAX
21974 #endif
21976 #elif (defined(__GNUC__) && defined(__x86_64__))
21978 __inline__ sqlite_uint64 sqlite3Hwtime(void){
21979 unsigned long val;
21980 __asm__ __volatile__ ("rdtsc" : "=A" (val));
21981 return val;
21984 #elif (defined(__GNUC__) && defined(__ppc__))
21986 __inline__ sqlite_uint64 sqlite3Hwtime(void){
21987 unsigned long long retval;
21988 unsigned long junk;
21989 __asm__ __volatile__ ("\n\
21990 1: mftbu %1\n\
21991 mftb %L0\n\
21992 mftbu %0\n\
21993 cmpw %0,%1\n\
21994 bne 1b"
21995 : "=r" (retval), "=r" (junk));
21996 return retval;
21999 #else
22001 #error Need implementation of sqlite3Hwtime() for your platform.
22004 ** To compile without implementing sqlite3Hwtime() for your platform,
22005 ** you can remove the above #error and use the following
22006 ** stub function. You will lose timing support for many
22007 ** of the debugging and testing utilities, but it should at
22008 ** least compile and run.
22010 SQLITE_PRIVATE sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
22012 #endif
22014 #endif /* !defined(_HWTIME_H_) */
22016 /************** End of hwtime.h **********************************************/
22017 /************** Continuing where we left off in os_common.h ******************/
22019 static sqlite_uint64 g_start;
22020 static sqlite_uint64 g_elapsed;
22021 #define TIMER_START g_start=sqlite3Hwtime()
22022 #define TIMER_END g_elapsed=sqlite3Hwtime()-g_start
22023 #define TIMER_ELAPSED g_elapsed
22024 #else
22025 #define TIMER_START
22026 #define TIMER_END
22027 #define TIMER_ELAPSED ((sqlite_uint64)0)
22028 #endif
22031 ** If we compile with the SQLITE_TEST macro set, then the following block
22032 ** of code will give us the ability to simulate a disk I/O error. This
22033 ** is used for testing the I/O recovery logic.
22035 #ifdef SQLITE_TEST
22036 SQLITE_API int sqlite3_io_error_hit = 0; /* Total number of I/O Errors */
22037 SQLITE_API int sqlite3_io_error_hardhit = 0; /* Number of non-benign errors */
22038 SQLITE_API int sqlite3_io_error_pending = 0; /* Count down to first I/O error */
22039 SQLITE_API int sqlite3_io_error_persist = 0; /* True if I/O errors persist */
22040 SQLITE_API int sqlite3_io_error_benign = 0; /* True if errors are benign */
22041 SQLITE_API int sqlite3_diskfull_pending = 0;
22042 SQLITE_API int sqlite3_diskfull = 0;
22043 #define SimulateIOErrorBenign(X) sqlite3_io_error_benign=(X)
22044 #define SimulateIOError(CODE) \
22045 if( (sqlite3_io_error_persist && sqlite3_io_error_hit) \
22046 || sqlite3_io_error_pending-- == 1 ) \
22047 { local_ioerr(); CODE; }
22048 static void local_ioerr(){
22049 IOTRACE(("IOERR\n"));
22050 sqlite3_io_error_hit++;
22051 if( !sqlite3_io_error_benign ) sqlite3_io_error_hardhit++;
22053 #define SimulateDiskfullError(CODE) \
22054 if( sqlite3_diskfull_pending ){ \
22055 if( sqlite3_diskfull_pending == 1 ){ \
22056 local_ioerr(); \
22057 sqlite3_diskfull = 1; \
22058 sqlite3_io_error_hit = 1; \
22059 CODE; \
22060 }else{ \
22061 sqlite3_diskfull_pending--; \
22064 #else
22065 #define SimulateIOErrorBenign(X)
22066 #define SimulateIOError(A)
22067 #define SimulateDiskfullError(A)
22068 #endif
22071 ** When testing, keep a count of the number of open files.
22073 #ifdef SQLITE_TEST
22074 SQLITE_API int sqlite3_open_file_count = 0;
22075 #define OpenCounter(X) sqlite3_open_file_count+=(X)
22076 #else
22077 #define OpenCounter(X)
22078 #endif
22080 #endif /* !defined(_OS_COMMON_H_) */
22082 /************** End of os_common.h *******************************************/
22083 /************** Continuing where we left off in os_os2.c *********************/
22085 /* Forward references */
22086 typedef struct os2File os2File; /* The file structure */
22087 typedef struct os2ShmNode os2ShmNode; /* A shared descritive memory node */
22088 typedef struct os2ShmLink os2ShmLink; /* A connection to shared-memory */
22091 ** The os2File structure is subclass of sqlite3_file specific for the OS/2
22092 ** protability layer.
22094 struct os2File {
22095 const sqlite3_io_methods *pMethod; /* Always the first entry */
22096 HFILE h; /* Handle for accessing the file */
22097 int flags; /* Flags provided to os2Open() */
22098 int locktype; /* Type of lock currently held on this file */
22099 int szChunk; /* Chunk size configured by FCNTL_CHUNK_SIZE */
22100 char *zFullPathCp; /* Full path name of this file */
22101 os2ShmLink *pShmLink; /* Instance of shared memory on this file */
22104 #define LOCK_TIMEOUT 10L /* the default locking timeout */
22107 ** Missing from some versions of the OS/2 toolkit -
22108 ** used to allocate from high memory if possible
22110 #ifndef OBJ_ANY
22111 # define OBJ_ANY 0x00000400
22112 #endif
22114 /*****************************************************************************
22115 ** The next group of routines implement the I/O methods specified
22116 ** by the sqlite3_io_methods object.
22117 ******************************************************************************/
22120 ** Close a file.
22122 static int os2Close( sqlite3_file *id ){
22123 APIRET rc;
22124 os2File *pFile = (os2File*)id;
22126 assert( id!=0 );
22127 OSTRACE(( "CLOSE %d (%s)\n", pFile->h, pFile->zFullPathCp ));
22129 rc = DosClose( pFile->h );
22131 if( pFile->flags & SQLITE_OPEN_DELETEONCLOSE )
22132 DosForceDelete( (PSZ)pFile->zFullPathCp );
22134 free( pFile->zFullPathCp );
22135 pFile->zFullPathCp = NULL;
22136 pFile->locktype = NO_LOCK;
22137 pFile->h = (HFILE)-1;
22138 pFile->flags = 0;
22140 OpenCounter( -1 );
22141 return rc == NO_ERROR ? SQLITE_OK : SQLITE_IOERR;
22145 ** Read data from a file into a buffer. Return SQLITE_OK if all
22146 ** bytes were read successfully and SQLITE_IOERR if anything goes
22147 ** wrong.
22149 static int os2Read(
22150 sqlite3_file *id, /* File to read from */
22151 void *pBuf, /* Write content into this buffer */
22152 int amt, /* Number of bytes to read */
22153 sqlite3_int64 offset /* Begin reading at this offset */
22155 ULONG fileLocation = 0L;
22156 ULONG got;
22157 os2File *pFile = (os2File*)id;
22158 assert( id!=0 );
22159 SimulateIOError( return SQLITE_IOERR_READ );
22160 OSTRACE(( "READ %d lock=%d\n", pFile->h, pFile->locktype ));
22161 if( DosSetFilePtr(pFile->h, offset, FILE_BEGIN, &fileLocation) != NO_ERROR ){
22162 return SQLITE_IOERR;
22164 if( DosRead( pFile->h, pBuf, amt, &got ) != NO_ERROR ){
22165 return SQLITE_IOERR_READ;
22167 if( got == (ULONG)amt )
22168 return SQLITE_OK;
22169 else {
22170 /* Unread portions of the input buffer must be zero-filled */
22171 memset(&((char*)pBuf)[got], 0, amt-got);
22172 return SQLITE_IOERR_SHORT_READ;
22177 ** Write data from a buffer into a file. Return SQLITE_OK on success
22178 ** or some other error code on failure.
22180 static int os2Write(
22181 sqlite3_file *id, /* File to write into */
22182 const void *pBuf, /* The bytes to be written */
22183 int amt, /* Number of bytes to write */
22184 sqlite3_int64 offset /* Offset into the file to begin writing at */
22186 ULONG fileLocation = 0L;
22187 APIRET rc = NO_ERROR;
22188 ULONG wrote;
22189 os2File *pFile = (os2File*)id;
22190 assert( id!=0 );
22191 SimulateIOError( return SQLITE_IOERR_WRITE );
22192 SimulateDiskfullError( return SQLITE_FULL );
22193 OSTRACE(( "WRITE %d lock=%d\n", pFile->h, pFile->locktype ));
22194 if( DosSetFilePtr(pFile->h, offset, FILE_BEGIN, &fileLocation) != NO_ERROR ){
22195 return SQLITE_IOERR;
22197 assert( amt>0 );
22198 while( amt > 0 &&
22199 ( rc = DosWrite( pFile->h, (PVOID)pBuf, amt, &wrote ) ) == NO_ERROR &&
22200 wrote > 0
22202 amt -= wrote;
22203 pBuf = &((char*)pBuf)[wrote];
22206 return ( rc != NO_ERROR || amt > (int)wrote ) ? SQLITE_FULL : SQLITE_OK;
22210 ** Truncate an open file to a specified size
22212 static int os2Truncate( sqlite3_file *id, i64 nByte ){
22213 APIRET rc;
22214 os2File *pFile = (os2File*)id;
22215 assert( id!=0 );
22216 OSTRACE(( "TRUNCATE %d %lld\n", pFile->h, nByte ));
22217 SimulateIOError( return SQLITE_IOERR_TRUNCATE );
22219 /* If the user has configured a chunk-size for this file, truncate the
22220 ** file so that it consists of an integer number of chunks (i.e. the
22221 ** actual file size after the operation may be larger than the requested
22222 ** size).
22224 if( pFile->szChunk ){
22225 nByte = ((nByte + pFile->szChunk - 1)/pFile->szChunk) * pFile->szChunk;
22228 rc = DosSetFileSize( pFile->h, nByte );
22229 return rc == NO_ERROR ? SQLITE_OK : SQLITE_IOERR_TRUNCATE;
22232 #ifdef SQLITE_TEST
22234 ** Count the number of fullsyncs and normal syncs. This is used to test
22235 ** that syncs and fullsyncs are occuring at the right times.
22237 SQLITE_API int sqlite3_sync_count = 0;
22238 SQLITE_API int sqlite3_fullsync_count = 0;
22239 #endif
22242 ** Make sure all writes to a particular file are committed to disk.
22244 static int os2Sync( sqlite3_file *id, int flags ){
22245 os2File *pFile = (os2File*)id;
22246 OSTRACE(( "SYNC %d lock=%d\n", pFile->h, pFile->locktype ));
22247 #ifdef SQLITE_TEST
22248 if( flags & SQLITE_SYNC_FULL){
22249 sqlite3_fullsync_count++;
22251 sqlite3_sync_count++;
22252 #endif
22253 /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
22254 ** no-op
22256 #ifdef SQLITE_NO_SYNC
22257 UNUSED_PARAMETER(pFile);
22258 return SQLITE_OK;
22259 #else
22260 return DosResetBuffer( pFile->h ) == NO_ERROR ? SQLITE_OK : SQLITE_IOERR;
22261 #endif
22265 ** Determine the current size of a file in bytes
22267 static int os2FileSize( sqlite3_file *id, sqlite3_int64 *pSize ){
22268 APIRET rc = NO_ERROR;
22269 FILESTATUS3 fsts3FileInfo;
22270 memset(&fsts3FileInfo, 0, sizeof(fsts3FileInfo));
22271 assert( id!=0 );
22272 SimulateIOError( return SQLITE_IOERR_FSTAT );
22273 rc = DosQueryFileInfo( ((os2File*)id)->h, FIL_STANDARD, &fsts3FileInfo, sizeof(FILESTATUS3) );
22274 if( rc == NO_ERROR ){
22275 *pSize = fsts3FileInfo.cbFile;
22276 return SQLITE_OK;
22277 }else{
22278 return SQLITE_IOERR_FSTAT;
22283 ** Acquire a reader lock.
22285 static int getReadLock( os2File *pFile ){
22286 FILELOCK LockArea,
22287 UnlockArea;
22288 APIRET res;
22289 memset(&LockArea, 0, sizeof(LockArea));
22290 memset(&UnlockArea, 0, sizeof(UnlockArea));
22291 LockArea.lOffset = SHARED_FIRST;
22292 LockArea.lRange = SHARED_SIZE;
22293 UnlockArea.lOffset = 0L;
22294 UnlockArea.lRange = 0L;
22295 res = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 1L );
22296 OSTRACE(( "GETREADLOCK %d res=%d\n", pFile->h, res ));
22297 return res;
22301 ** Undo a readlock
22303 static int unlockReadLock( os2File *id ){
22304 FILELOCK LockArea,
22305 UnlockArea;
22306 APIRET res;
22307 memset(&LockArea, 0, sizeof(LockArea));
22308 memset(&UnlockArea, 0, sizeof(UnlockArea));
22309 LockArea.lOffset = 0L;
22310 LockArea.lRange = 0L;
22311 UnlockArea.lOffset = SHARED_FIRST;
22312 UnlockArea.lRange = SHARED_SIZE;
22313 res = DosSetFileLocks( id->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 1L );
22314 OSTRACE(( "UNLOCK-READLOCK file handle=%d res=%d?\n", id->h, res ));
22315 return res;
22319 ** Lock the file with the lock specified by parameter locktype - one
22320 ** of the following:
22322 ** (1) SHARED_LOCK
22323 ** (2) RESERVED_LOCK
22324 ** (3) PENDING_LOCK
22325 ** (4) EXCLUSIVE_LOCK
22327 ** Sometimes when requesting one lock state, additional lock states
22328 ** are inserted in between. The locking might fail on one of the later
22329 ** transitions leaving the lock state different from what it started but
22330 ** still short of its goal. The following chart shows the allowed
22331 ** transitions and the inserted intermediate states:
22333 ** UNLOCKED -> SHARED
22334 ** SHARED -> RESERVED
22335 ** SHARED -> (PENDING) -> EXCLUSIVE
22336 ** RESERVED -> (PENDING) -> EXCLUSIVE
22337 ** PENDING -> EXCLUSIVE
22339 ** This routine will only increase a lock. The os2Unlock() routine
22340 ** erases all locks at once and returns us immediately to locking level 0.
22341 ** It is not possible to lower the locking level one step at a time. You
22342 ** must go straight to locking level 0.
22344 static int os2Lock( sqlite3_file *id, int locktype ){
22345 int rc = SQLITE_OK; /* Return code from subroutines */
22346 APIRET res = NO_ERROR; /* Result of an OS/2 lock call */
22347 int newLocktype; /* Set pFile->locktype to this value before exiting */
22348 int gotPendingLock = 0;/* True if we acquired a PENDING lock this time */
22349 FILELOCK LockArea,
22350 UnlockArea;
22351 os2File *pFile = (os2File*)id;
22352 memset(&LockArea, 0, sizeof(LockArea));
22353 memset(&UnlockArea, 0, sizeof(UnlockArea));
22354 assert( pFile!=0 );
22355 OSTRACE(( "LOCK %d %d was %d\n", pFile->h, locktype, pFile->locktype ));
22357 /* If there is already a lock of this type or more restrictive on the
22358 ** os2File, do nothing. Don't use the end_lock: exit path, as
22359 ** sqlite3_mutex_enter() hasn't been called yet.
22361 if( pFile->locktype>=locktype ){
22362 OSTRACE(( "LOCK %d %d ok (already held)\n", pFile->h, locktype ));
22363 return SQLITE_OK;
22366 /* Make sure the locking sequence is correct
22368 assert( pFile->locktype!=NO_LOCK || locktype==SHARED_LOCK );
22369 assert( locktype!=PENDING_LOCK );
22370 assert( locktype!=RESERVED_LOCK || pFile->locktype==SHARED_LOCK );
22372 /* Lock the PENDING_LOCK byte if we need to acquire a PENDING lock or
22373 ** a SHARED lock. If we are acquiring a SHARED lock, the acquisition of
22374 ** the PENDING_LOCK byte is temporary.
22376 newLocktype = pFile->locktype;
22377 if( pFile->locktype==NO_LOCK
22378 || (locktype==EXCLUSIVE_LOCK && pFile->locktype==RESERVED_LOCK)
22380 LockArea.lOffset = PENDING_BYTE;
22381 LockArea.lRange = 1L;
22382 UnlockArea.lOffset = 0L;
22383 UnlockArea.lRange = 0L;
22385 /* wait longer than LOCK_TIMEOUT here not to have to try multiple times */
22386 res = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, 100L, 0L );
22387 if( res == NO_ERROR ){
22388 gotPendingLock = 1;
22389 OSTRACE(( "LOCK %d pending lock boolean set. res=%d\n", pFile->h, res ));
22393 /* Acquire a shared lock
22395 if( locktype==SHARED_LOCK && res == NO_ERROR ){
22396 assert( pFile->locktype==NO_LOCK );
22397 res = getReadLock(pFile);
22398 if( res == NO_ERROR ){
22399 newLocktype = SHARED_LOCK;
22401 OSTRACE(( "LOCK %d acquire shared lock. res=%d\n", pFile->h, res ));
22404 /* Acquire a RESERVED lock
22406 if( locktype==RESERVED_LOCK && res == NO_ERROR ){
22407 assert( pFile->locktype==SHARED_LOCK );
22408 LockArea.lOffset = RESERVED_BYTE;
22409 LockArea.lRange = 1L;
22410 UnlockArea.lOffset = 0L;
22411 UnlockArea.lRange = 0L;
22412 res = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
22413 if( res == NO_ERROR ){
22414 newLocktype = RESERVED_LOCK;
22416 OSTRACE(( "LOCK %d acquire reserved lock. res=%d\n", pFile->h, res ));
22419 /* Acquire a PENDING lock
22421 if( locktype==EXCLUSIVE_LOCK && res == NO_ERROR ){
22422 newLocktype = PENDING_LOCK;
22423 gotPendingLock = 0;
22424 OSTRACE(( "LOCK %d acquire pending lock. pending lock boolean unset.\n",
22425 pFile->h ));
22428 /* Acquire an EXCLUSIVE lock
22430 if( locktype==EXCLUSIVE_LOCK && res == NO_ERROR ){
22431 assert( pFile->locktype>=SHARED_LOCK );
22432 res = unlockReadLock(pFile);
22433 OSTRACE(( "unreadlock = %d\n", res ));
22434 LockArea.lOffset = SHARED_FIRST;
22435 LockArea.lRange = SHARED_SIZE;
22436 UnlockArea.lOffset = 0L;
22437 UnlockArea.lRange = 0L;
22438 res = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
22439 if( res == NO_ERROR ){
22440 newLocktype = EXCLUSIVE_LOCK;
22441 }else{
22442 OSTRACE(( "OS/2 error-code = %d\n", res ));
22443 getReadLock(pFile);
22445 OSTRACE(( "LOCK %d acquire exclusive lock. res=%d\n", pFile->h, res ));
22448 /* If we are holding a PENDING lock that ought to be released, then
22449 ** release it now.
22451 if( gotPendingLock && locktype==SHARED_LOCK ){
22452 int r;
22453 LockArea.lOffset = 0L;
22454 LockArea.lRange = 0L;
22455 UnlockArea.lOffset = PENDING_BYTE;
22456 UnlockArea.lRange = 1L;
22457 r = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
22458 OSTRACE(( "LOCK %d unlocking pending/is shared. r=%d\n", pFile->h, r ));
22461 /* Update the state of the lock has held in the file descriptor then
22462 ** return the appropriate result code.
22464 if( res == NO_ERROR ){
22465 rc = SQLITE_OK;
22466 }else{
22467 OSTRACE(( "LOCK FAILED %d trying for %d but got %d\n", pFile->h,
22468 locktype, newLocktype ));
22469 rc = SQLITE_BUSY;
22471 pFile->locktype = newLocktype;
22472 OSTRACE(( "LOCK %d now %d\n", pFile->h, pFile->locktype ));
22473 return rc;
22477 ** This routine checks if there is a RESERVED lock held on the specified
22478 ** file by this or any other process. If such a lock is held, return
22479 ** non-zero, otherwise zero.
22481 static int os2CheckReservedLock( sqlite3_file *id, int *pOut ){
22482 int r = 0;
22483 os2File *pFile = (os2File*)id;
22484 assert( pFile!=0 );
22485 if( pFile->locktype>=RESERVED_LOCK ){
22486 r = 1;
22487 OSTRACE(( "TEST WR-LOCK %d %d (local)\n", pFile->h, r ));
22488 }else{
22489 FILELOCK LockArea,
22490 UnlockArea;
22491 APIRET rc = NO_ERROR;
22492 memset(&LockArea, 0, sizeof(LockArea));
22493 memset(&UnlockArea, 0, sizeof(UnlockArea));
22494 LockArea.lOffset = RESERVED_BYTE;
22495 LockArea.lRange = 1L;
22496 UnlockArea.lOffset = 0L;
22497 UnlockArea.lRange = 0L;
22498 rc = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
22499 OSTRACE(( "TEST WR-LOCK %d lock reserved byte rc=%d\n", pFile->h, rc ));
22500 if( rc == NO_ERROR ){
22501 APIRET rcu = NO_ERROR; /* return code for unlocking */
22502 LockArea.lOffset = 0L;
22503 LockArea.lRange = 0L;
22504 UnlockArea.lOffset = RESERVED_BYTE;
22505 UnlockArea.lRange = 1L;
22506 rcu = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
22507 OSTRACE(( "TEST WR-LOCK %d unlock reserved byte r=%d\n", pFile->h, rcu ));
22509 r = !(rc == NO_ERROR);
22510 OSTRACE(( "TEST WR-LOCK %d %d (remote)\n", pFile->h, r ));
22512 *pOut = r;
22513 return SQLITE_OK;
22517 ** Lower the locking level on file descriptor id to locktype. locktype
22518 ** must be either NO_LOCK or SHARED_LOCK.
22520 ** If the locking level of the file descriptor is already at or below
22521 ** the requested locking level, this routine is a no-op.
22523 ** It is not possible for this routine to fail if the second argument
22524 ** is NO_LOCK. If the second argument is SHARED_LOCK then this routine
22525 ** might return SQLITE_IOERR;
22527 static int os2Unlock( sqlite3_file *id, int locktype ){
22528 int type;
22529 os2File *pFile = (os2File*)id;
22530 APIRET rc = SQLITE_OK;
22531 APIRET res = NO_ERROR;
22532 FILELOCK LockArea,
22533 UnlockArea;
22534 memset(&LockArea, 0, sizeof(LockArea));
22535 memset(&UnlockArea, 0, sizeof(UnlockArea));
22536 assert( pFile!=0 );
22537 assert( locktype<=SHARED_LOCK );
22538 OSTRACE(( "UNLOCK %d to %d was %d\n", pFile->h, locktype, pFile->locktype ));
22539 type = pFile->locktype;
22540 if( type>=EXCLUSIVE_LOCK ){
22541 LockArea.lOffset = 0L;
22542 LockArea.lRange = 0L;
22543 UnlockArea.lOffset = SHARED_FIRST;
22544 UnlockArea.lRange = SHARED_SIZE;
22545 res = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
22546 OSTRACE(( "UNLOCK %d exclusive lock res=%d\n", pFile->h, res ));
22547 if( locktype==SHARED_LOCK && getReadLock(pFile) != NO_ERROR ){
22548 /* This should never happen. We should always be able to
22549 ** reacquire the read lock */
22550 OSTRACE(( "UNLOCK %d to %d getReadLock() failed\n", pFile->h, locktype ));
22551 rc = SQLITE_IOERR_UNLOCK;
22554 if( type>=RESERVED_LOCK ){
22555 LockArea.lOffset = 0L;
22556 LockArea.lRange = 0L;
22557 UnlockArea.lOffset = RESERVED_BYTE;
22558 UnlockArea.lRange = 1L;
22559 res = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
22560 OSTRACE(( "UNLOCK %d reserved res=%d\n", pFile->h, res ));
22562 if( locktype==NO_LOCK && type>=SHARED_LOCK ){
22563 res = unlockReadLock(pFile);
22564 OSTRACE(( "UNLOCK %d is %d want %d res=%d\n",
22565 pFile->h, type, locktype, res ));
22567 if( type>=PENDING_LOCK ){
22568 LockArea.lOffset = 0L;
22569 LockArea.lRange = 0L;
22570 UnlockArea.lOffset = PENDING_BYTE;
22571 UnlockArea.lRange = 1L;
22572 res = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
22573 OSTRACE(( "UNLOCK %d pending res=%d\n", pFile->h, res ));
22575 pFile->locktype = locktype;
22576 OSTRACE(( "UNLOCK %d now %d\n", pFile->h, pFile->locktype ));
22577 return rc;
22581 ** Control and query of the open file handle.
22583 static int os2FileControl(sqlite3_file *id, int op, void *pArg){
22584 switch( op ){
22585 case SQLITE_FCNTL_LOCKSTATE: {
22586 *(int*)pArg = ((os2File*)id)->locktype;
22587 OSTRACE(( "FCNTL_LOCKSTATE %d lock=%d\n",
22588 ((os2File*)id)->h, ((os2File*)id)->locktype ));
22589 return SQLITE_OK;
22591 case SQLITE_FCNTL_CHUNK_SIZE: {
22592 ((os2File*)id)->szChunk = *(int*)pArg;
22593 return SQLITE_OK;
22595 case SQLITE_FCNTL_SIZE_HINT: {
22596 sqlite3_int64 sz = *(sqlite3_int64*)pArg;
22597 SimulateIOErrorBenign(1);
22598 os2Truncate(id, sz);
22599 SimulateIOErrorBenign(0);
22600 return SQLITE_OK;
22602 case SQLITE_FCNTL_SYNC_OMITTED: {
22603 return SQLITE_OK;
22606 return SQLITE_NOTFOUND;
22610 ** Return the sector size in bytes of the underlying block device for
22611 ** the specified file. This is almost always 512 bytes, but may be
22612 ** larger for some devices.
22614 ** SQLite code assumes this function cannot fail. It also assumes that
22615 ** if two files are created in the same file-system directory (i.e.
22616 ** a database and its journal file) that the sector size will be the
22617 ** same for both.
22619 static int os2SectorSize(sqlite3_file *id){
22620 UNUSED_PARAMETER(id);
22621 return SQLITE_DEFAULT_SECTOR_SIZE;
22625 ** Return a vector of device characteristics.
22627 static int os2DeviceCharacteristics(sqlite3_file *id){
22628 UNUSED_PARAMETER(id);
22629 return SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN;
22634 ** Character set conversion objects used by conversion routines.
22636 static UconvObject ucUtf8 = NULL; /* convert between UTF-8 and UCS-2 */
22637 static UconvObject uclCp = NULL; /* convert between local codepage and UCS-2 */
22640 ** Helper function to initialize the conversion objects from and to UTF-8.
22642 static void initUconvObjects( void ){
22643 if( UniCreateUconvObject( UTF_8, &ucUtf8 ) != ULS_SUCCESS )
22644 ucUtf8 = NULL;
22645 if ( UniCreateUconvObject( (UniChar *)L"@path=yes", &uclCp ) != ULS_SUCCESS )
22646 uclCp = NULL;
22650 ** Helper function to free the conversion objects from and to UTF-8.
22652 static void freeUconvObjects( void ){
22653 if ( ucUtf8 )
22654 UniFreeUconvObject( ucUtf8 );
22655 if ( uclCp )
22656 UniFreeUconvObject( uclCp );
22657 ucUtf8 = NULL;
22658 uclCp = NULL;
22662 ** Helper function to convert UTF-8 filenames to local OS/2 codepage.
22663 ** The two-step process: first convert the incoming UTF-8 string
22664 ** into UCS-2 and then from UCS-2 to the current codepage.
22665 ** The returned char pointer has to be freed.
22667 static char *convertUtf8PathToCp( const char *in ){
22668 UniChar tempPath[CCHMAXPATH];
22669 char *out = (char *)calloc( CCHMAXPATH, 1 );
22671 if( !out )
22672 return NULL;
22674 if( !ucUtf8 || !uclCp )
22675 initUconvObjects();
22677 /* determine string for the conversion of UTF-8 which is CP1208 */
22678 if( UniStrToUcs( ucUtf8, tempPath, (char *)in, CCHMAXPATH ) != ULS_SUCCESS )
22679 return out; /* if conversion fails, return the empty string */
22681 /* conversion for current codepage which can be used for paths */
22682 UniStrFromUcs( uclCp, out, tempPath, CCHMAXPATH );
22684 return out;
22688 ** Helper function to convert filenames from local codepage to UTF-8.
22689 ** The two-step process: first convert the incoming codepage-specific
22690 ** string into UCS-2 and then from UCS-2 to the codepage of UTF-8.
22691 ** The returned char pointer has to be freed.
22693 ** This function is non-static to be able to use this in shell.c and
22694 ** similar applications that take command line arguments.
22696 char *convertCpPathToUtf8( const char *in ){
22697 UniChar tempPath[CCHMAXPATH];
22698 char *out = (char *)calloc( CCHMAXPATH, 1 );
22700 if( !out )
22701 return NULL;
22703 if( !ucUtf8 || !uclCp )
22704 initUconvObjects();
22706 /* conversion for current codepage which can be used for paths */
22707 if( UniStrToUcs( uclCp, tempPath, (char *)in, CCHMAXPATH ) != ULS_SUCCESS )
22708 return out; /* if conversion fails, return the empty string */
22710 /* determine string for the conversion of UTF-8 which is CP1208 */
22711 UniStrFromUcs( ucUtf8, out, tempPath, CCHMAXPATH );
22713 return out;
22717 #ifndef SQLITE_OMIT_WAL
22720 ** Use main database file for interprocess locking. If un-defined
22721 ** a separate file is created for this purpose. The file will be
22722 ** used only to set file locks. There will be no data written to it.
22724 #define SQLITE_OS2_NO_WAL_LOCK_FILE
22726 #if 0
22727 static void _ERR_TRACE( const char *fmt, ... ) {
22728 va_list ap;
22729 va_start(ap, fmt);
22730 vfprintf(stderr, fmt, ap);
22731 fflush(stderr);
22733 #define ERR_TRACE(rc, msg) \
22734 if( (rc) != SQLITE_OK ) _ERR_TRACE msg;
22735 #else
22736 #define ERR_TRACE(rc, msg)
22737 #endif
22740 ** Helper functions to obtain and relinquish the global mutex. The
22741 ** global mutex is used to protect os2ShmNodeList.
22743 ** Function os2ShmMutexHeld() is used to assert() that the global mutex
22744 ** is held when required. This function is only used as part of assert()
22745 ** statements. e.g.
22747 ** os2ShmEnterMutex()
22748 ** assert( os2ShmMutexHeld() );
22749 ** os2ShmLeaveMutex()
22751 static void os2ShmEnterMutex(void){
22752 sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
22754 static void os2ShmLeaveMutex(void){
22755 sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
22757 #ifdef SQLITE_DEBUG
22758 static int os2ShmMutexHeld(void) {
22759 return sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
22761 int GetCurrentProcessId(void) {
22762 PPIB pib;
22763 DosGetInfoBlocks(NULL, &pib);
22764 return (int)pib->pib_ulpid;
22766 #endif
22769 ** Object used to represent a the shared memory area for a single log file.
22770 ** When multiple threads all reference the same log-summary, each thread has
22771 ** its own os2File object, but they all point to a single instance of this
22772 ** object. In other words, each log-summary is opened only once per process.
22774 ** os2ShmMutexHeld() must be true when creating or destroying
22775 ** this object or while reading or writing the following fields:
22777 ** nRef
22778 ** pNext
22780 ** The following fields are read-only after the object is created:
22782 ** szRegion
22783 ** hLockFile
22784 ** shmBaseName
22786 ** Either os2ShmNode.mutex must be held or os2ShmNode.nRef==0 and
22787 ** os2ShmMutexHeld() is true when reading or writing any other field
22788 ** in this structure.
22791 struct os2ShmNode {
22792 sqlite3_mutex *mutex; /* Mutex to access this object */
22793 os2ShmNode *pNext; /* Next in list of all os2ShmNode objects */
22795 int szRegion; /* Size of shared-memory regions */
22797 int nRegion; /* Size of array apRegion */
22798 void **apRegion; /* Array of pointers to shared-memory regions */
22800 int nRef; /* Number of os2ShmLink objects pointing to this */
22801 os2ShmLink *pFirst; /* First os2ShmLink object pointing to this */
22803 HFILE hLockFile; /* File used for inter-process memory locking */
22804 char shmBaseName[1]; /* Name of the memory object !!! must last !!! */
22809 ** Structure used internally by this VFS to record the state of an
22810 ** open shared memory connection.
22812 ** The following fields are initialized when this object is created and
22813 ** are read-only thereafter:
22815 ** os2Shm.pShmNode
22816 ** os2Shm.id
22818 ** All other fields are read/write. The os2Shm.pShmNode->mutex must be held
22819 ** while accessing any read/write fields.
22821 struct os2ShmLink {
22822 os2ShmNode *pShmNode; /* The underlying os2ShmNode object */
22823 os2ShmLink *pNext; /* Next os2Shm with the same os2ShmNode */
22824 u32 sharedMask; /* Mask of shared locks held */
22825 u32 exclMask; /* Mask of exclusive locks held */
22826 #ifdef SQLITE_DEBUG
22827 u8 id; /* Id of this connection with its os2ShmNode */
22828 #endif
22833 ** A global list of all os2ShmNode objects.
22835 ** The os2ShmMutexHeld() must be true while reading or writing this list.
22837 static os2ShmNode *os2ShmNodeList = NULL;
22840 ** Constants used for locking
22842 #ifdef SQLITE_OS2_NO_WAL_LOCK_FILE
22843 #define OS2_SHM_BASE (PENDING_BYTE + 0x10000) /* first lock byte */
22844 #else
22845 #define OS2_SHM_BASE ((22+SQLITE_SHM_NLOCK)*4) /* first lock byte */
22846 #endif
22848 #define OS2_SHM_DMS (OS2_SHM_BASE+SQLITE_SHM_NLOCK) /* deadman switch */
22851 ** Apply advisory locks for all n bytes beginning at ofst.
22853 #define _SHM_UNLCK 1 /* no lock */
22854 #define _SHM_RDLCK 2 /* shared lock, no wait */
22855 #define _SHM_WRLCK 3 /* exlusive lock, no wait */
22856 #define _SHM_WRLCK_WAIT 4 /* exclusive lock, wait */
22857 static int os2ShmSystemLock(
22858 os2ShmNode *pNode, /* Apply locks to this open shared-memory segment */
22859 int lockType, /* _SHM_UNLCK, _SHM_RDLCK, _SHM_WRLCK or _SHM_WRLCK_WAIT */
22860 int ofst, /* Offset to first byte to be locked/unlocked */
22861 int nByte /* Number of bytes to lock or unlock */
22863 APIRET rc;
22864 FILELOCK area;
22865 ULONG mode, timeout;
22867 /* Access to the os2ShmNode object is serialized by the caller */
22868 assert( sqlite3_mutex_held(pNode->mutex) || pNode->nRef==0 );
22870 mode = 1; /* shared lock */
22871 timeout = 0; /* no wait */
22872 area.lOffset = ofst;
22873 area.lRange = nByte;
22875 switch( lockType ) {
22876 case _SHM_WRLCK_WAIT:
22877 timeout = (ULONG)-1; /* wait forever */
22878 case _SHM_WRLCK:
22879 mode = 0; /* exclusive lock */
22880 case _SHM_RDLCK:
22881 rc = DosSetFileLocks(pNode->hLockFile,
22882 NULL, &area, timeout, mode);
22883 break;
22884 /* case _SHM_UNLCK: */
22885 default:
22886 rc = DosSetFileLocks(pNode->hLockFile,
22887 &area, NULL, 0, 0);
22888 break;
22891 OSTRACE(("SHM-LOCK %d %s %s 0x%08lx\n",
22892 pNode->hLockFile,
22893 rc==SQLITE_OK ? "ok" : "failed",
22894 lockType==_SHM_UNLCK ? "Unlock" : "Lock",
22895 rc));
22897 ERR_TRACE(rc, ("os2ShmSystemLock: %d %s\n", rc, pNode->shmBaseName))
22899 return ( rc == 0 ) ? SQLITE_OK : SQLITE_BUSY;
22903 ** Find an os2ShmNode in global list or allocate a new one, if not found.
22905 ** This is not a VFS shared-memory method; it is a utility function called
22906 ** by VFS shared-memory methods.
22908 static int os2OpenSharedMemory( os2File *fd, int szRegion ) {
22909 os2ShmLink *pLink;
22910 os2ShmNode *pNode;
22911 int cbShmName, rc = SQLITE_OK;
22912 char shmName[CCHMAXPATH + 30];
22913 #ifndef SQLITE_OS2_NO_WAL_LOCK_FILE
22914 ULONG action;
22915 #endif
22917 /* We need some additional space at the end to append the region number */
22918 cbShmName = sprintf(shmName, "\\SHAREMEM\\%s", fd->zFullPathCp );
22919 if( cbShmName >= CCHMAXPATH-8 )
22920 return SQLITE_IOERR_SHMOPEN;
22922 /* Replace colon in file name to form a valid shared memory name */
22923 shmName[10+1] = '!';
22925 /* Allocate link object (we free it later in case of failure) */
22926 pLink = sqlite3_malloc( sizeof(*pLink) );
22927 if( !pLink )
22928 return SQLITE_NOMEM;
22930 /* Access node list */
22931 os2ShmEnterMutex();
22933 /* Find node by it's shared memory base name */
22934 for( pNode = os2ShmNodeList;
22935 pNode && stricmp(shmName, pNode->shmBaseName) != 0;
22936 pNode = pNode->pNext ) ;
22938 /* Not found: allocate a new node */
22939 if( !pNode ) {
22940 pNode = sqlite3_malloc( sizeof(*pNode) + cbShmName );
22941 if( pNode ) {
22942 memset(pNode, 0, sizeof(*pNode) );
22943 pNode->szRegion = szRegion;
22944 pNode->hLockFile = (HFILE)-1;
22945 strcpy(pNode->shmBaseName, shmName);
22947 #ifdef SQLITE_OS2_NO_WAL_LOCK_FILE
22948 if( DosDupHandle(fd->h, &pNode->hLockFile) != 0 ) {
22949 #else
22950 sprintf(shmName, "%s-lck", fd->zFullPathCp);
22951 if( DosOpen((PSZ)shmName, &pNode->hLockFile, &action, 0, FILE_NORMAL,
22952 OPEN_ACTION_OPEN_IF_EXISTS | OPEN_ACTION_CREATE_IF_NEW,
22953 OPEN_ACCESS_READWRITE | OPEN_SHARE_DENYNONE |
22954 OPEN_FLAGS_NOINHERIT | OPEN_FLAGS_FAIL_ON_ERROR,
22955 NULL) != 0 ) {
22956 #endif
22957 sqlite3_free(pNode);
22958 rc = SQLITE_IOERR;
22959 } else {
22960 pNode->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
22961 if( !pNode->mutex ) {
22962 sqlite3_free(pNode);
22963 rc = SQLITE_NOMEM;
22966 } else {
22967 rc = SQLITE_NOMEM;
22970 if( rc == SQLITE_OK ) {
22971 pNode->pNext = os2ShmNodeList;
22972 os2ShmNodeList = pNode;
22973 } else {
22974 pNode = NULL;
22976 } else if( pNode->szRegion != szRegion ) {
22977 rc = SQLITE_IOERR_SHMSIZE;
22978 pNode = NULL;
22981 if( pNode ) {
22982 sqlite3_mutex_enter(pNode->mutex);
22984 memset(pLink, 0, sizeof(*pLink));
22986 pLink->pShmNode = pNode;
22987 pLink->pNext = pNode->pFirst;
22988 pNode->pFirst = pLink;
22989 pNode->nRef++;
22991 fd->pShmLink = pLink;
22993 sqlite3_mutex_leave(pNode->mutex);
22995 } else {
22996 /* Error occured. Free our link object. */
22997 sqlite3_free(pLink);
23000 os2ShmLeaveMutex();
23002 ERR_TRACE(rc, ("os2OpenSharedMemory: %d %s\n", rc, fd->zFullPathCp))
23004 return rc;
23008 ** Purge the os2ShmNodeList list of all entries with nRef==0.
23010 ** This is not a VFS shared-memory method; it is a utility function called
23011 ** by VFS shared-memory methods.
23013 static void os2PurgeShmNodes( int deleteFlag ) {
23014 os2ShmNode *pNode;
23015 os2ShmNode **ppNode;
23017 os2ShmEnterMutex();
23019 ppNode = &os2ShmNodeList;
23021 while( *ppNode ) {
23022 pNode = *ppNode;
23024 if( pNode->nRef == 0 ) {
23025 *ppNode = pNode->pNext;
23027 if( pNode->apRegion ) {
23028 /* Prevent other processes from resizing the shared memory */
23029 os2ShmSystemLock(pNode, _SHM_WRLCK_WAIT, OS2_SHM_DMS, 1);
23031 while( pNode->nRegion-- ) {
23032 #ifdef SQLITE_DEBUG
23033 int rc =
23034 #endif
23035 DosFreeMem(pNode->apRegion[pNode->nRegion]);
23037 OSTRACE(("SHM-PURGE pid-%d unmap region=%d %s\n",
23038 (int)GetCurrentProcessId(), pNode->nRegion,
23039 rc == 0 ? "ok" : "failed"));
23042 /* Allow other processes to resize the shared memory */
23043 os2ShmSystemLock(pNode, _SHM_UNLCK, OS2_SHM_DMS, 1);
23045 sqlite3_free(pNode->apRegion);
23048 DosClose(pNode->hLockFile);
23050 #ifndef SQLITE_OS2_NO_WAL_LOCK_FILE
23051 if( deleteFlag ) {
23052 char fileName[CCHMAXPATH];
23053 /* Skip "\\SHAREMEM\\" */
23054 sprintf(fileName, "%s-lck", pNode->shmBaseName + 10);
23055 /* restore colon */
23056 fileName[1] = ':';
23058 DosForceDelete(fileName);
23060 #endif
23062 sqlite3_mutex_free(pNode->mutex);
23064 sqlite3_free(pNode);
23066 } else {
23067 ppNode = &pNode->pNext;
23071 os2ShmLeaveMutex();
23075 ** This function is called to obtain a pointer to region iRegion of the
23076 ** shared-memory associated with the database file id. Shared-memory regions
23077 ** are numbered starting from zero. Each shared-memory region is szRegion
23078 ** bytes in size.
23080 ** If an error occurs, an error code is returned and *pp is set to NULL.
23082 ** Otherwise, if the bExtend parameter is 0 and the requested shared-memory
23083 ** region has not been allocated (by any client, including one running in a
23084 ** separate process), then *pp is set to NULL and SQLITE_OK returned. If
23085 ** bExtend is non-zero and the requested shared-memory region has not yet
23086 ** been allocated, it is allocated by this function.
23088 ** If the shared-memory region has already been allocated or is allocated by
23089 ** this call as described above, then it is mapped into this processes
23090 ** address space (if it is not already), *pp is set to point to the mapped
23091 ** memory and SQLITE_OK returned.
23093 static int os2ShmMap(
23094 sqlite3_file *id, /* Handle open on database file */
23095 int iRegion, /* Region to retrieve */
23096 int szRegion, /* Size of regions */
23097 int bExtend, /* True to extend block if necessary */
23098 void volatile **pp /* OUT: Mapped memory */
23100 PVOID pvTemp;
23101 void **apRegion;
23102 os2ShmNode *pNode;
23103 int n, rc = SQLITE_OK;
23104 char shmName[CCHMAXPATH];
23105 os2File *pFile = (os2File*)id;
23107 *pp = NULL;
23109 if( !pFile->pShmLink )
23110 rc = os2OpenSharedMemory( pFile, szRegion );
23112 if( rc == SQLITE_OK ) {
23113 pNode = pFile->pShmLink->pShmNode ;
23115 sqlite3_mutex_enter(pNode->mutex);
23117 assert( szRegion==pNode->szRegion );
23119 /* Unmapped region ? */
23120 if( iRegion >= pNode->nRegion ) {
23121 /* Prevent other processes from resizing the shared memory */
23122 os2ShmSystemLock(pNode, _SHM_WRLCK_WAIT, OS2_SHM_DMS, 1);
23124 apRegion = sqlite3_realloc(
23125 pNode->apRegion, (iRegion + 1) * sizeof(apRegion[0]));
23127 if( apRegion ) {
23128 pNode->apRegion = apRegion;
23130 while( pNode->nRegion <= iRegion ) {
23131 sprintf(shmName, "%s-%u",
23132 pNode->shmBaseName, pNode->nRegion);
23134 if( DosGetNamedSharedMem(&pvTemp, (PSZ)shmName,
23135 PAG_READ | PAG_WRITE) != NO_ERROR ) {
23136 if( !bExtend )
23137 break;
23139 if( DosAllocSharedMem(&pvTemp, (PSZ)shmName, szRegion,
23140 PAG_READ | PAG_WRITE | PAG_COMMIT | OBJ_ANY) != NO_ERROR &&
23141 DosAllocSharedMem(&pvTemp, (PSZ)shmName, szRegion,
23142 PAG_READ | PAG_WRITE | PAG_COMMIT) != NO_ERROR ) {
23143 rc = SQLITE_NOMEM;
23144 break;
23148 apRegion[pNode->nRegion++] = pvTemp;
23151 /* zero out remaining entries */
23152 for( n = pNode->nRegion; n <= iRegion; n++ )
23153 pNode->apRegion[n] = NULL;
23155 /* Return this region (maybe zero) */
23156 *pp = pNode->apRegion[iRegion];
23157 } else {
23158 rc = SQLITE_NOMEM;
23161 /* Allow other processes to resize the shared memory */
23162 os2ShmSystemLock(pNode, _SHM_UNLCK, OS2_SHM_DMS, 1);
23164 } else {
23165 /* Region has been mapped previously */
23166 *pp = pNode->apRegion[iRegion];
23169 sqlite3_mutex_leave(pNode->mutex);
23172 ERR_TRACE(rc, ("os2ShmMap: %s iRgn = %d, szRgn = %d, bExt = %d : %d\n",
23173 pFile->zFullPathCp, iRegion, szRegion, bExtend, rc))
23175 return rc;
23179 ** Close a connection to shared-memory. Delete the underlying
23180 ** storage if deleteFlag is true.
23182 ** If there is no shared memory associated with the connection then this
23183 ** routine is a harmless no-op.
23185 static int os2ShmUnmap(
23186 sqlite3_file *id, /* The underlying database file */
23187 int deleteFlag /* Delete shared-memory if true */
23189 os2File *pFile = (os2File*)id;
23190 os2ShmLink *pLink = pFile->pShmLink;
23192 if( pLink ) {
23193 int nRef = -1;
23194 os2ShmLink **ppLink;
23195 os2ShmNode *pNode = pLink->pShmNode;
23197 sqlite3_mutex_enter(pNode->mutex);
23199 for( ppLink = &pNode->pFirst;
23200 *ppLink && *ppLink != pLink;
23201 ppLink = &(*ppLink)->pNext ) ;
23203 assert(*ppLink);
23205 if( *ppLink ) {
23206 *ppLink = pLink->pNext;
23207 nRef = --pNode->nRef;
23208 } else {
23209 ERR_TRACE(1, ("os2ShmUnmap: link not found ! %s\n",
23210 pNode->shmBaseName))
23213 pFile->pShmLink = NULL;
23214 sqlite3_free(pLink);
23216 sqlite3_mutex_leave(pNode->mutex);
23218 if( nRef == 0 )
23219 os2PurgeShmNodes( deleteFlag );
23222 return SQLITE_OK;
23226 ** Change the lock state for a shared-memory segment.
23228 ** Note that the relationship between SHAREd and EXCLUSIVE locks is a little
23229 ** different here than in posix. In xShmLock(), one can go from unlocked
23230 ** to shared and back or from unlocked to exclusive and back. But one may
23231 ** not go from shared to exclusive or from exclusive to shared.
23233 static int os2ShmLock(
23234 sqlite3_file *id, /* Database file holding the shared memory */
23235 int ofst, /* First lock to acquire or release */
23236 int n, /* Number of locks to acquire or release */
23237 int flags /* What to do with the lock */
23239 u32 mask; /* Mask of locks to take or release */
23240 int rc = SQLITE_OK; /* Result code */
23241 os2File *pFile = (os2File*)id;
23242 os2ShmLink *p = pFile->pShmLink; /* The shared memory being locked */
23243 os2ShmLink *pX; /* For looping over all siblings */
23244 os2ShmNode *pShmNode = p->pShmNode; /* Our node */
23246 assert( ofst>=0 && ofst+n<=SQLITE_SHM_NLOCK );
23247 assert( n>=1 );
23248 assert( flags==(SQLITE_SHM_LOCK | SQLITE_SHM_SHARED)
23249 || flags==(SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE)
23250 || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED)
23251 || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE) );
23252 assert( n==1 || (flags & SQLITE_SHM_EXCLUSIVE)!=0 );
23254 mask = (u32)((1U<<(ofst+n)) - (1U<<ofst));
23255 assert( n>1 || mask==(1<<ofst) );
23258 sqlite3_mutex_enter(pShmNode->mutex);
23260 if( flags & SQLITE_SHM_UNLOCK ){
23261 u32 allMask = 0; /* Mask of locks held by siblings */
23263 /* See if any siblings hold this same lock */
23264 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
23265 if( pX==p ) continue;
23266 assert( (pX->exclMask & (p->exclMask|p->sharedMask))==0 );
23267 allMask |= pX->sharedMask;
23270 /* Unlock the system-level locks */
23271 if( (mask & allMask)==0 ){
23272 rc = os2ShmSystemLock(pShmNode, _SHM_UNLCK, ofst+OS2_SHM_BASE, n);
23273 }else{
23274 rc = SQLITE_OK;
23277 /* Undo the local locks */
23278 if( rc==SQLITE_OK ){
23279 p->exclMask &= ~mask;
23280 p->sharedMask &= ~mask;
23282 }else if( flags & SQLITE_SHM_SHARED ){
23283 u32 allShared = 0; /* Union of locks held by connections other than "p" */
23285 /* Find out which shared locks are already held by sibling connections.
23286 ** If any sibling already holds an exclusive lock, go ahead and return
23287 ** SQLITE_BUSY.
23289 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
23290 if( (pX->exclMask & mask)!=0 ){
23291 rc = SQLITE_BUSY;
23292 break;
23294 allShared |= pX->sharedMask;
23297 /* Get shared locks at the system level, if necessary */
23298 if( rc==SQLITE_OK ){
23299 if( (allShared & mask)==0 ){
23300 rc = os2ShmSystemLock(pShmNode, _SHM_RDLCK, ofst+OS2_SHM_BASE, n);
23301 }else{
23302 rc = SQLITE_OK;
23306 /* Get the local shared locks */
23307 if( rc==SQLITE_OK ){
23308 p->sharedMask |= mask;
23310 }else{
23311 /* Make sure no sibling connections hold locks that will block this
23312 ** lock. If any do, return SQLITE_BUSY right away.
23314 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
23315 if( (pX->exclMask & mask)!=0 || (pX->sharedMask & mask)!=0 ){
23316 rc = SQLITE_BUSY;
23317 break;
23321 /* Get the exclusive locks at the system level. Then if successful
23322 ** also mark the local connection as being locked.
23324 if( rc==SQLITE_OK ){
23325 rc = os2ShmSystemLock(pShmNode, _SHM_WRLCK, ofst+OS2_SHM_BASE, n);
23326 if( rc==SQLITE_OK ){
23327 assert( (p->sharedMask & mask)==0 );
23328 p->exclMask |= mask;
23333 sqlite3_mutex_leave(pShmNode->mutex);
23335 OSTRACE(("SHM-LOCK shmid-%d, pid-%d got %03x,%03x %s\n",
23336 p->id, (int)GetCurrentProcessId(), p->sharedMask, p->exclMask,
23337 rc ? "failed" : "ok"));
23339 ERR_TRACE(rc, ("os2ShmLock: ofst = %d, n = %d, flags = 0x%x -> %d \n",
23340 ofst, n, flags, rc))
23342 return rc;
23346 ** Implement a memory barrier or memory fence on shared memory.
23348 ** All loads and stores begun before the barrier must complete before
23349 ** any load or store begun after the barrier.
23351 static void os2ShmBarrier(
23352 sqlite3_file *id /* Database file holding the shared memory */
23354 UNUSED_PARAMETER(id);
23355 os2ShmEnterMutex();
23356 os2ShmLeaveMutex();
23359 #else
23360 # define os2ShmMap 0
23361 # define os2ShmLock 0
23362 # define os2ShmBarrier 0
23363 # define os2ShmUnmap 0
23364 #endif /* #ifndef SQLITE_OMIT_WAL */
23368 ** This vector defines all the methods that can operate on an
23369 ** sqlite3_file for os2.
23371 static const sqlite3_io_methods os2IoMethod = {
23372 2, /* iVersion */
23373 os2Close, /* xClose */
23374 os2Read, /* xRead */
23375 os2Write, /* xWrite */
23376 os2Truncate, /* xTruncate */
23377 os2Sync, /* xSync */
23378 os2FileSize, /* xFileSize */
23379 os2Lock, /* xLock */
23380 os2Unlock, /* xUnlock */
23381 os2CheckReservedLock, /* xCheckReservedLock */
23382 os2FileControl, /* xFileControl */
23383 os2SectorSize, /* xSectorSize */
23384 os2DeviceCharacteristics, /* xDeviceCharacteristics */
23385 os2ShmMap, /* xShmMap */
23386 os2ShmLock, /* xShmLock */
23387 os2ShmBarrier, /* xShmBarrier */
23388 os2ShmUnmap /* xShmUnmap */
23392 /***************************************************************************
23393 ** Here ends the I/O methods that form the sqlite3_io_methods object.
23395 ** The next block of code implements the VFS methods.
23396 ****************************************************************************/
23399 ** Create a temporary file name in zBuf. zBuf must be big enough to
23400 ** hold at pVfs->mxPathname characters.
23402 static int getTempname(int nBuf, char *zBuf ){
23403 static const char zChars[] =
23404 "abcdefghijklmnopqrstuvwxyz"
23405 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
23406 "0123456789";
23407 int i, j;
23408 PSZ zTempPathCp;
23409 char zTempPath[CCHMAXPATH];
23410 ULONG ulDriveNum, ulDriveMap;
23412 /* It's odd to simulate an io-error here, but really this is just
23413 ** using the io-error infrastructure to test that SQLite handles this
23414 ** function failing.
23416 SimulateIOError( return SQLITE_IOERR );
23418 if( sqlite3_temp_directory ) {
23419 sqlite3_snprintf(CCHMAXPATH-30, zTempPath, "%s", sqlite3_temp_directory);
23420 } else if( DosScanEnv( (PSZ)"TEMP", &zTempPathCp ) == NO_ERROR ||
23421 DosScanEnv( (PSZ)"TMP", &zTempPathCp ) == NO_ERROR ||
23422 DosScanEnv( (PSZ)"TMPDIR", &zTempPathCp ) == NO_ERROR ) {
23423 char *zTempPathUTF = convertCpPathToUtf8( (char *)zTempPathCp );
23424 sqlite3_snprintf(CCHMAXPATH-30, zTempPath, "%s", zTempPathUTF);
23425 free( zTempPathUTF );
23426 } else if( DosQueryCurrentDisk( &ulDriveNum, &ulDriveMap ) == NO_ERROR ) {
23427 zTempPath[0] = (char)('A' + ulDriveNum - 1);
23428 zTempPath[1] = ':';
23429 zTempPath[2] = '\0';
23430 } else {
23431 zTempPath[0] = '\0';
23434 /* Strip off a trailing slashes or backslashes, otherwise we would get *
23435 * multiple (back)slashes which causes DosOpen() to fail. *
23436 * Trailing spaces are not allowed, either. */
23437 j = sqlite3Strlen30(zTempPath);
23438 while( j > 0 && ( zTempPath[j-1] == '\\' || zTempPath[j-1] == '/' ||
23439 zTempPath[j-1] == ' ' ) ){
23440 j--;
23442 zTempPath[j] = '\0';
23444 /* We use 20 bytes to randomize the name */
23445 sqlite3_snprintf(nBuf-22, zBuf,
23446 "%s\\"SQLITE_TEMP_FILE_PREFIX, zTempPath);
23447 j = sqlite3Strlen30(zBuf);
23448 sqlite3_randomness( 20, &zBuf[j] );
23449 for( i = 0; i < 20; i++, j++ ){
23450 zBuf[j] = zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
23452 zBuf[j] = 0;
23454 OSTRACE(( "TEMP FILENAME: %s\n", zBuf ));
23455 return SQLITE_OK;
23460 ** Turn a relative pathname into a full pathname. Write the full
23461 ** pathname into zFull[]. zFull[] will be at least pVfs->mxPathname
23462 ** bytes in size.
23464 static int os2FullPathname(
23465 sqlite3_vfs *pVfs, /* Pointer to vfs object */
23466 const char *zRelative, /* Possibly relative input path */
23467 int nFull, /* Size of output buffer in bytes */
23468 char *zFull /* Output buffer */
23470 char *zRelativeCp = convertUtf8PathToCp( zRelative );
23471 char zFullCp[CCHMAXPATH] = "\0";
23472 char *zFullUTF;
23473 APIRET rc = DosQueryPathInfo( (PSZ)zRelativeCp, FIL_QUERYFULLNAME,
23474 zFullCp, CCHMAXPATH );
23475 free( zRelativeCp );
23476 zFullUTF = convertCpPathToUtf8( zFullCp );
23477 sqlite3_snprintf( nFull, zFull, zFullUTF );
23478 free( zFullUTF );
23479 return rc == NO_ERROR ? SQLITE_OK : SQLITE_IOERR;
23484 ** Open a file.
23486 static int os2Open(
23487 sqlite3_vfs *pVfs, /* Not used */
23488 const char *zName, /* Name of the file (UTF-8) */
23489 sqlite3_file *id, /* Write the SQLite file handle here */
23490 int flags, /* Open mode flags */
23491 int *pOutFlags /* Status return flags */
23493 HFILE h;
23494 ULONG ulOpenFlags = 0;
23495 ULONG ulOpenMode = 0;
23496 ULONG ulAction = 0;
23497 ULONG rc;
23498 os2File *pFile = (os2File*)id;
23499 const char *zUtf8Name = zName;
23500 char *zNameCp;
23501 char zTmpname[CCHMAXPATH];
23503 int isExclusive = (flags & SQLITE_OPEN_EXCLUSIVE);
23504 int isCreate = (flags & SQLITE_OPEN_CREATE);
23505 int isReadWrite = (flags & SQLITE_OPEN_READWRITE);
23506 #ifndef NDEBUG
23507 int isDelete = (flags & SQLITE_OPEN_DELETEONCLOSE);
23508 int isReadonly = (flags & SQLITE_OPEN_READONLY);
23509 int eType = (flags & 0xFFFFFF00);
23510 int isOpenJournal = (isCreate && (
23511 eType==SQLITE_OPEN_MASTER_JOURNAL
23512 || eType==SQLITE_OPEN_MAIN_JOURNAL
23513 || eType==SQLITE_OPEN_WAL
23515 #endif
23517 UNUSED_PARAMETER(pVfs);
23518 assert( id!=0 );
23520 /* Check the following statements are true:
23522 ** (a) Exactly one of the READWRITE and READONLY flags must be set, and
23523 ** (b) if CREATE is set, then READWRITE must also be set, and
23524 ** (c) if EXCLUSIVE is set, then CREATE must also be set.
23525 ** (d) if DELETEONCLOSE is set, then CREATE must also be set.
23527 assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
23528 assert(isCreate==0 || isReadWrite);
23529 assert(isExclusive==0 || isCreate);
23530 assert(isDelete==0 || isCreate);
23532 /* The main DB, main journal, WAL file and master journal are never
23533 ** automatically deleted. Nor are they ever temporary files. */
23534 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB );
23535 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL );
23536 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MASTER_JOURNAL );
23537 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_WAL );
23539 /* Assert that the upper layer has set one of the "file-type" flags. */
23540 assert( eType==SQLITE_OPEN_MAIN_DB || eType==SQLITE_OPEN_TEMP_DB
23541 || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL
23542 || eType==SQLITE_OPEN_SUBJOURNAL || eType==SQLITE_OPEN_MASTER_JOURNAL
23543 || eType==SQLITE_OPEN_TRANSIENT_DB || eType==SQLITE_OPEN_WAL
23546 memset( pFile, 0, sizeof(*pFile) );
23547 pFile->h = (HFILE)-1;
23549 /* If the second argument to this function is NULL, generate a
23550 ** temporary file name to use
23552 if( !zUtf8Name ){
23553 assert(isDelete && !isOpenJournal);
23554 rc = getTempname(CCHMAXPATH, zTmpname);
23555 if( rc!=SQLITE_OK ){
23556 return rc;
23558 zUtf8Name = zTmpname;
23561 if( isReadWrite ){
23562 ulOpenMode |= OPEN_ACCESS_READWRITE;
23563 }else{
23564 ulOpenMode |= OPEN_ACCESS_READONLY;
23567 /* Open in random access mode for possibly better speed. Allow full
23568 ** sharing because file locks will provide exclusive access when needed.
23569 ** The handle should not be inherited by child processes and we don't
23570 ** want popups from the critical error handler.
23572 ulOpenMode |= OPEN_FLAGS_RANDOM | OPEN_SHARE_DENYNONE |
23573 OPEN_FLAGS_NOINHERIT | OPEN_FLAGS_FAIL_ON_ERROR;
23575 /* SQLITE_OPEN_EXCLUSIVE is used to make sure that a new file is
23576 ** created. SQLite doesn't use it to indicate "exclusive access"
23577 ** as it is usually understood.
23579 if( isExclusive ){
23580 /* Creates a new file, only if it does not already exist. */
23581 /* If the file exists, it fails. */
23582 ulOpenFlags |= OPEN_ACTION_CREATE_IF_NEW | OPEN_ACTION_FAIL_IF_EXISTS;
23583 }else if( isCreate ){
23584 /* Open existing file, or create if it doesn't exist */
23585 ulOpenFlags |= OPEN_ACTION_CREATE_IF_NEW | OPEN_ACTION_OPEN_IF_EXISTS;
23586 }else{
23587 /* Opens a file, only if it exists. */
23588 ulOpenFlags |= OPEN_ACTION_FAIL_IF_NEW | OPEN_ACTION_OPEN_IF_EXISTS;
23591 zNameCp = convertUtf8PathToCp( zUtf8Name );
23592 rc = DosOpen( (PSZ)zNameCp,
23594 &ulAction,
23596 FILE_NORMAL,
23597 ulOpenFlags,
23598 ulOpenMode,
23599 (PEAOP2)NULL );
23600 free( zNameCp );
23602 if( rc != NO_ERROR ){
23603 OSTRACE(( "OPEN Invalid handle rc=%d: zName=%s, ulAction=%#lx, ulFlags=%#lx, ulMode=%#lx\n",
23604 rc, zUtf8Name, ulAction, ulOpenFlags, ulOpenMode ));
23606 if( isReadWrite ){
23607 return os2Open( pVfs, zName, id,
23608 ((flags|SQLITE_OPEN_READONLY)&~(SQLITE_OPEN_CREATE|SQLITE_OPEN_READWRITE)),
23609 pOutFlags );
23610 }else{
23611 return SQLITE_CANTOPEN;
23615 if( pOutFlags ){
23616 *pOutFlags = isReadWrite ? SQLITE_OPEN_READWRITE : SQLITE_OPEN_READONLY;
23619 os2FullPathname( pVfs, zUtf8Name, sizeof( zTmpname ), zTmpname );
23620 pFile->zFullPathCp = convertUtf8PathToCp( zTmpname );
23621 pFile->pMethod = &os2IoMethod;
23622 pFile->flags = flags;
23623 pFile->h = h;
23625 OpenCounter(+1);
23626 OSTRACE(( "OPEN %d pOutFlags=%d\n", pFile->h, pOutFlags ));
23627 return SQLITE_OK;
23631 ** Delete the named file.
23633 static int os2Delete(
23634 sqlite3_vfs *pVfs, /* Not used on os2 */
23635 const char *zFilename, /* Name of file to delete */
23636 int syncDir /* Not used on os2 */
23638 APIRET rc;
23639 char *zFilenameCp;
23640 SimulateIOError( return SQLITE_IOERR_DELETE );
23641 zFilenameCp = convertUtf8PathToCp( zFilename );
23642 rc = DosDelete( (PSZ)zFilenameCp );
23643 free( zFilenameCp );
23644 OSTRACE(( "DELETE \"%s\"\n", zFilename ));
23645 return (rc == NO_ERROR ||
23646 rc == ERROR_FILE_NOT_FOUND ||
23647 rc == ERROR_PATH_NOT_FOUND ) ? SQLITE_OK : SQLITE_IOERR_DELETE;
23651 ** Check the existance and status of a file.
23653 static int os2Access(
23654 sqlite3_vfs *pVfs, /* Not used on os2 */
23655 const char *zFilename, /* Name of file to check */
23656 int flags, /* Type of test to make on this file */
23657 int *pOut /* Write results here */
23659 APIRET rc;
23660 FILESTATUS3 fsts3ConfigInfo;
23661 char *zFilenameCp;
23663 UNUSED_PARAMETER(pVfs);
23664 SimulateIOError( return SQLITE_IOERR_ACCESS; );
23666 zFilenameCp = convertUtf8PathToCp( zFilename );
23667 rc = DosQueryPathInfo( (PSZ)zFilenameCp, FIL_STANDARD,
23668 &fsts3ConfigInfo, sizeof(FILESTATUS3) );
23669 free( zFilenameCp );
23670 OSTRACE(( "ACCESS fsts3ConfigInfo.attrFile=%d flags=%d rc=%d\n",
23671 fsts3ConfigInfo.attrFile, flags, rc ));
23673 switch( flags ){
23674 case SQLITE_ACCESS_EXISTS:
23675 /* For an SQLITE_ACCESS_EXISTS query, treat a zero-length file
23676 ** as if it does not exist.
23678 if( fsts3ConfigInfo.cbFile == 0 )
23679 rc = ERROR_FILE_NOT_FOUND;
23680 break;
23681 case SQLITE_ACCESS_READ:
23682 break;
23683 case SQLITE_ACCESS_READWRITE:
23684 if( fsts3ConfigInfo.attrFile & FILE_READONLY )
23685 rc = ERROR_ACCESS_DENIED;
23686 break;
23687 default:
23688 rc = ERROR_FILE_NOT_FOUND;
23689 assert( !"Invalid flags argument" );
23692 *pOut = (rc == NO_ERROR);
23693 OSTRACE(( "ACCESS %s flags %d: rc=%d\n", zFilename, flags, *pOut ));
23695 return SQLITE_OK;
23699 #ifndef SQLITE_OMIT_LOAD_EXTENSION
23701 ** Interfaces for opening a shared library, finding entry points
23702 ** within the shared library, and closing the shared library.
23705 ** Interfaces for opening a shared library, finding entry points
23706 ** within the shared library, and closing the shared library.
23708 static void *os2DlOpen(sqlite3_vfs *pVfs, const char *zFilename){
23709 HMODULE hmod;
23710 APIRET rc;
23711 char *zFilenameCp = convertUtf8PathToCp(zFilename);
23712 rc = DosLoadModule(NULL, 0, (PSZ)zFilenameCp, &hmod);
23713 free(zFilenameCp);
23714 return rc != NO_ERROR ? 0 : (void*)hmod;
23717 ** A no-op since the error code is returned on the DosLoadModule call.
23718 ** os2Dlopen returns zero if DosLoadModule is not successful.
23720 static void os2DlError(sqlite3_vfs *pVfs, int nBuf, char *zBufOut){
23721 /* no-op */
23723 static void (*os2DlSym(sqlite3_vfs *pVfs, void *pHandle, const char *zSymbol))(void){
23724 PFN pfn;
23725 APIRET rc;
23726 rc = DosQueryProcAddr((HMODULE)pHandle, 0L, (PSZ)zSymbol, &pfn);
23727 if( rc != NO_ERROR ){
23728 /* if the symbol itself was not found, search again for the same
23729 * symbol with an extra underscore, that might be needed depending
23730 * on the calling convention */
23731 char _zSymbol[256] = "_";
23732 strncat(_zSymbol, zSymbol, 254);
23733 rc = DosQueryProcAddr((HMODULE)pHandle, 0L, (PSZ)_zSymbol, &pfn);
23735 return rc != NO_ERROR ? 0 : (void(*)(void))pfn;
23737 static void os2DlClose(sqlite3_vfs *pVfs, void *pHandle){
23738 DosFreeModule((HMODULE)pHandle);
23740 #else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
23741 #define os2DlOpen 0
23742 #define os2DlError 0
23743 #define os2DlSym 0
23744 #define os2DlClose 0
23745 #endif
23749 ** Write up to nBuf bytes of randomness into zBuf.
23751 static int os2Randomness(sqlite3_vfs *pVfs, int nBuf, char *zBuf ){
23752 int n = 0;
23753 #if defined(SQLITE_TEST)
23754 n = nBuf;
23755 memset(zBuf, 0, nBuf);
23756 #else
23757 int i;
23758 PPIB ppib;
23759 PTIB ptib;
23760 DATETIME dt;
23761 static unsigned c = 0;
23762 /* Ordered by variation probability */
23763 static ULONG svIdx[6] = { QSV_MS_COUNT, QSV_TIME_LOW,
23764 QSV_MAXPRMEM, QSV_MAXSHMEM,
23765 QSV_TOTAVAILMEM, QSV_TOTRESMEM };
23767 /* 8 bytes; timezone and weekday don't increase the randomness much */
23768 if( (int)sizeof(dt)-3 <= nBuf - n ){
23769 c += 0x0100;
23770 DosGetDateTime(&dt);
23771 dt.year = (USHORT)((dt.year - 1900) | c);
23772 memcpy(&zBuf[n], &dt, sizeof(dt)-3);
23773 n += sizeof(dt)-3;
23776 /* 4 bytes; PIDs and TIDs are 16 bit internally, so combine them */
23777 if( (int)sizeof(ULONG) <= nBuf - n ){
23778 DosGetInfoBlocks(&ptib, &ppib);
23779 *(PULONG)&zBuf[n] = MAKELONG(ppib->pib_ulpid,
23780 ptib->tib_ptib2->tib2_ultid);
23781 n += sizeof(ULONG);
23784 /* Up to 6 * 4 bytes; variables depend on the system state */
23785 for( i = 0; i < 6 && (int)sizeof(ULONG) <= nBuf - n; i++ ){
23786 DosQuerySysInfo(svIdx[i], svIdx[i],
23787 (PULONG)&zBuf[n], sizeof(ULONG));
23788 n += sizeof(ULONG);
23790 #endif
23792 return n;
23796 ** Sleep for a little while. Return the amount of time slept.
23797 ** The argument is the number of microseconds we want to sleep.
23798 ** The return value is the number of microseconds of sleep actually
23799 ** requested from the underlying operating system, a number which
23800 ** might be greater than or equal to the argument, but not less
23801 ** than the argument.
23803 static int os2Sleep( sqlite3_vfs *pVfs, int microsec ){
23804 DosSleep( (microsec/1000) );
23805 return microsec;
23809 ** The following variable, if set to a non-zero value, becomes the result
23810 ** returned from sqlite3OsCurrentTime(). This is used for testing.
23812 #ifdef SQLITE_TEST
23813 SQLITE_API int sqlite3_current_time = 0;
23814 #endif
23817 ** Find the current time (in Universal Coordinated Time). Write into *piNow
23818 ** the current time and date as a Julian Day number times 86_400_000. In
23819 ** other words, write into *piNow the number of milliseconds since the Julian
23820 ** epoch of noon in Greenwich on November 24, 4714 B.C according to the
23821 ** proleptic Gregorian calendar.
23823 ** On success, return 0. Return 1 if the time and date cannot be found.
23825 static int os2CurrentTimeInt64(sqlite3_vfs *pVfs, sqlite3_int64 *piNow){
23826 #ifdef SQLITE_TEST
23827 static const sqlite3_int64 unixEpoch = 24405875*(sqlite3_int64)8640000;
23828 #endif
23829 int year, month, datepart, timepart;
23831 DATETIME dt;
23832 DosGetDateTime( &dt );
23834 year = dt.year;
23835 month = dt.month;
23837 /* Calculations from http://www.astro.keele.ac.uk/~rno/Astronomy/hjd.html
23838 ** http://www.astro.keele.ac.uk/~rno/Astronomy/hjd-0.1.c
23839 ** Calculate the Julian days
23841 datepart = (int)dt.day - 32076 +
23842 1461*(year + 4800 + (month - 14)/12)/4 +
23843 367*(month - 2 - (month - 14)/12*12)/12 -
23844 3*((year + 4900 + (month - 14)/12)/100)/4;
23846 /* Time in milliseconds, hours to noon added */
23847 timepart = 12*3600*1000 + dt.hundredths*10 + dt.seconds*1000 +
23848 ((int)dt.minutes + dt.timezone)*60*1000 + dt.hours*3600*1000;
23850 *piNow = (sqlite3_int64)datepart*86400*1000 + timepart;
23852 #ifdef SQLITE_TEST
23853 if( sqlite3_current_time ){
23854 *piNow = 1000*(sqlite3_int64)sqlite3_current_time + unixEpoch;
23856 #endif
23858 UNUSED_PARAMETER(pVfs);
23859 return 0;
23863 ** Find the current time (in Universal Coordinated Time). Write the
23864 ** current time and date as a Julian Day number into *prNow and
23865 ** return 0. Return 1 if the time and date cannot be found.
23867 static int os2CurrentTime( sqlite3_vfs *pVfs, double *prNow ){
23868 int rc;
23869 sqlite3_int64 i;
23870 rc = os2CurrentTimeInt64(pVfs, &i);
23871 if( !rc ){
23872 *prNow = i/86400000.0;
23874 return rc;
23878 ** The idea is that this function works like a combination of
23879 ** GetLastError() and FormatMessage() on windows (or errno and
23880 ** strerror_r() on unix). After an error is returned by an OS
23881 ** function, SQLite calls this function with zBuf pointing to
23882 ** a buffer of nBuf bytes. The OS layer should populate the
23883 ** buffer with a nul-terminated UTF-8 encoded error message
23884 ** describing the last IO error to have occurred within the calling
23885 ** thread.
23887 ** If the error message is too large for the supplied buffer,
23888 ** it should be truncated. The return value of xGetLastError
23889 ** is zero if the error message fits in the buffer, or non-zero
23890 ** otherwise (if the message was truncated). If non-zero is returned,
23891 ** then it is not necessary to include the nul-terminator character
23892 ** in the output buffer.
23894 ** Not supplying an error message will have no adverse effect
23895 ** on SQLite. It is fine to have an implementation that never
23896 ** returns an error message:
23898 ** int xGetLastError(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
23899 ** assert(zBuf[0]=='\0');
23900 ** return 0;
23901 ** }
23903 ** However if an error message is supplied, it will be incorporated
23904 ** by sqlite into the error message available to the user using
23905 ** sqlite3_errmsg(), possibly making IO errors easier to debug.
23907 static int os2GetLastError(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
23908 assert(zBuf[0]=='\0');
23909 return 0;
23913 ** Initialize and deinitialize the operating system interface.
23915 SQLITE_API int sqlite3_os_init(void){
23916 static sqlite3_vfs os2Vfs = {
23917 3, /* iVersion */
23918 sizeof(os2File), /* szOsFile */
23919 CCHMAXPATH, /* mxPathname */
23920 0, /* pNext */
23921 "os2", /* zName */
23922 0, /* pAppData */
23924 os2Open, /* xOpen */
23925 os2Delete, /* xDelete */
23926 os2Access, /* xAccess */
23927 os2FullPathname, /* xFullPathname */
23928 os2DlOpen, /* xDlOpen */
23929 os2DlError, /* xDlError */
23930 os2DlSym, /* xDlSym */
23931 os2DlClose, /* xDlClose */
23932 os2Randomness, /* xRandomness */
23933 os2Sleep, /* xSleep */
23934 os2CurrentTime, /* xCurrentTime */
23935 os2GetLastError, /* xGetLastError */
23936 os2CurrentTimeInt64, /* xCurrentTimeInt64 */
23937 0, /* xSetSystemCall */
23938 0, /* xGetSystemCall */
23939 0 /* xNextSystemCall */
23941 sqlite3_vfs_register(&os2Vfs, 1);
23942 initUconvObjects();
23943 /* sqlite3OSTrace = 1; */
23944 return SQLITE_OK;
23946 SQLITE_API int sqlite3_os_end(void){
23947 freeUconvObjects();
23948 return SQLITE_OK;
23951 #endif /* SQLITE_OS_OS2 */
23953 /************** End of os_os2.c **********************************************/
23954 /************** Begin file os_unix.c *****************************************/
23956 ** 2004 May 22
23958 ** The author disclaims copyright to this source code. In place of
23959 ** a legal notice, here is a blessing:
23961 ** May you do good and not evil.
23962 ** May you find forgiveness for yourself and forgive others.
23963 ** May you share freely, never taking more than you give.
23965 ******************************************************************************
23967 ** This file contains the VFS implementation for unix-like operating systems
23968 ** include Linux, MacOSX, *BSD, QNX, VxWorks, AIX, HPUX, and others.
23970 ** There are actually several different VFS implementations in this file.
23971 ** The differences are in the way that file locking is done. The default
23972 ** implementation uses Posix Advisory Locks. Alternative implementations
23973 ** use flock(), dot-files, various proprietary locking schemas, or simply
23974 ** skip locking all together.
23976 ** This source file is organized into divisions where the logic for various
23977 ** subfunctions is contained within the appropriate division. PLEASE
23978 ** KEEP THE STRUCTURE OF THIS FILE INTACT. New code should be placed
23979 ** in the correct division and should be clearly labeled.
23981 ** The layout of divisions is as follows:
23983 ** * General-purpose declarations and utility functions.
23984 ** * Unique file ID logic used by VxWorks.
23985 ** * Various locking primitive implementations (all except proxy locking):
23986 ** + for Posix Advisory Locks
23987 ** + for no-op locks
23988 ** + for dot-file locks
23989 ** + for flock() locking
23990 ** + for named semaphore locks (VxWorks only)
23991 ** + for AFP filesystem locks (MacOSX only)
23992 ** * sqlite3_file methods not associated with locking.
23993 ** * Definitions of sqlite3_io_methods objects for all locking
23994 ** methods plus "finder" functions for each locking method.
23995 ** * sqlite3_vfs method implementations.
23996 ** * Locking primitives for the proxy uber-locking-method. (MacOSX only)
23997 ** * Definitions of sqlite3_vfs objects for all locking methods
23998 ** plus implementations of sqlite3_os_init() and sqlite3_os_end().
24000 #if SQLITE_OS_UNIX /* This file is used on unix only */
24003 ** There are various methods for file locking used for concurrency
24004 ** control:
24006 ** 1. POSIX locking (the default),
24007 ** 2. No locking,
24008 ** 3. Dot-file locking,
24009 ** 4. flock() locking,
24010 ** 5. AFP locking (OSX only),
24011 ** 6. Named POSIX semaphores (VXWorks only),
24012 ** 7. proxy locking. (OSX only)
24014 ** Styles 4, 5, and 7 are only available of SQLITE_ENABLE_LOCKING_STYLE
24015 ** is defined to 1. The SQLITE_ENABLE_LOCKING_STYLE also enables automatic
24016 ** selection of the appropriate locking style based on the filesystem
24017 ** where the database is located.
24019 #if !defined(SQLITE_ENABLE_LOCKING_STYLE)
24020 # if defined(__APPLE__)
24021 # define SQLITE_ENABLE_LOCKING_STYLE 1
24022 # else
24023 # define SQLITE_ENABLE_LOCKING_STYLE 0
24024 # endif
24025 #endif
24028 ** Define the OS_VXWORKS pre-processor macro to 1 if building on
24029 ** vxworks, or 0 otherwise.
24031 #ifndef OS_VXWORKS
24032 # if defined(__RTP__) || defined(_WRS_KERNEL)
24033 # define OS_VXWORKS 1
24034 # else
24035 # define OS_VXWORKS 0
24036 # endif
24037 #endif
24040 ** These #defines should enable >2GB file support on Posix if the
24041 ** underlying operating system supports it. If the OS lacks
24042 ** large file support, these should be no-ops.
24044 ** Large file support can be disabled using the -DSQLITE_DISABLE_LFS switch
24045 ** on the compiler command line. This is necessary if you are compiling
24046 ** on a recent machine (ex: RedHat 7.2) but you want your code to work
24047 ** on an older machine (ex: RedHat 6.0). If you compile on RedHat 7.2
24048 ** without this option, LFS is enable. But LFS does not exist in the kernel
24049 ** in RedHat 6.0, so the code won't work. Hence, for maximum binary
24050 ** portability you should omit LFS.
24052 ** The previous paragraph was written in 2005. (This paragraph is written
24053 ** on 2008-11-28.) These days, all Linux kernels support large files, so
24054 ** you should probably leave LFS enabled. But some embedded platforms might
24055 ** lack LFS in which case the SQLITE_DISABLE_LFS macro might still be useful.
24057 #ifndef SQLITE_DISABLE_LFS
24058 # define _LARGE_FILE 1
24059 # ifndef _FILE_OFFSET_BITS
24060 # define _FILE_OFFSET_BITS 64
24061 # endif
24062 # define _LARGEFILE_SOURCE 1
24063 #endif
24066 ** standard include files.
24068 #include <sys/types.h>
24069 #include <sys/stat.h>
24070 #include <fcntl.h>
24071 #include <unistd.h>
24072 #include <sys/time.h>
24073 #include <errno.h>
24074 #ifndef SQLITE_OMIT_WAL
24075 #include <sys/mman.h>
24076 #endif
24078 #if SQLITE_ENABLE_LOCKING_STYLE
24079 # include <sys/ioctl.h>
24080 # if OS_VXWORKS
24081 # include <semaphore.h>
24082 # include <limits.h>
24083 # else
24084 # include <sys/file.h>
24085 # include <sys/param.h>
24086 # endif
24087 #endif /* SQLITE_ENABLE_LOCKING_STYLE */
24089 #if defined(__APPLE__) || (SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS)
24090 # include <sys/mount.h>
24091 #endif
24094 ** Allowed values of unixFile.fsFlags
24096 #define SQLITE_FSFLAGS_IS_MSDOS 0x1
24099 ** If we are to be thread-safe, include the pthreads header and define
24100 ** the SQLITE_UNIX_THREADS macro.
24102 #if SQLITE_THREADSAFE
24103 # define SQLITE_UNIX_THREADS 1
24104 #endif
24107 ** Default permissions when creating a new file
24109 #ifndef SQLITE_DEFAULT_FILE_PERMISSIONS
24110 # define SQLITE_DEFAULT_FILE_PERMISSIONS 0644
24111 #endif
24114 ** Default permissions when creating auto proxy dir
24116 #ifndef SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
24117 # define SQLITE_DEFAULT_PROXYDIR_PERMISSIONS 0755
24118 #endif
24121 ** Maximum supported path-length.
24123 #define MAX_PATHNAME 512
24126 ** Only set the lastErrno if the error code is a real error and not
24127 ** a normal expected return code of SQLITE_BUSY or SQLITE_OK
24129 #define IS_LOCK_ERROR(x) ((x != SQLITE_OK) && (x != SQLITE_BUSY))
24131 /* Forward references */
24132 typedef struct unixShm unixShm; /* Connection shared memory */
24133 typedef struct unixShmNode unixShmNode; /* Shared memory instance */
24134 typedef struct unixInodeInfo unixInodeInfo; /* An i-node */
24135 typedef struct UnixUnusedFd UnixUnusedFd; /* An unused file descriptor */
24138 ** Sometimes, after a file handle is closed by SQLite, the file descriptor
24139 ** cannot be closed immediately. In these cases, instances of the following
24140 ** structure are used to store the file descriptor while waiting for an
24141 ** opportunity to either close or reuse it.
24143 struct UnixUnusedFd {
24144 int fd; /* File descriptor to close */
24145 int flags; /* Flags this file descriptor was opened with */
24146 UnixUnusedFd *pNext; /* Next unused file descriptor on same file */
24150 ** The unixFile structure is subclass of sqlite3_file specific to the unix
24151 ** VFS implementations.
24153 typedef struct unixFile unixFile;
24154 struct unixFile {
24155 sqlite3_io_methods const *pMethod; /* Always the first entry */
24156 unixInodeInfo *pInode; /* Info about locks on this inode */
24157 int h; /* The file descriptor */
24158 unsigned char eFileLock; /* The type of lock held on this fd */
24159 unsigned char ctrlFlags; /* Behavioral bits. UNIXFILE_* flags */
24160 int lastErrno; /* The unix errno from last I/O error */
24161 void *lockingContext; /* Locking style specific state */
24162 UnixUnusedFd *pUnused; /* Pre-allocated UnixUnusedFd */
24163 const char *zPath; /* Name of the file */
24164 unixShm *pShm; /* Shared memory segment information */
24165 int szChunk; /* Configured by FCNTL_CHUNK_SIZE */
24166 #if SQLITE_ENABLE_LOCKING_STYLE
24167 int openFlags; /* The flags specified at open() */
24168 #endif
24169 #if SQLITE_ENABLE_LOCKING_STYLE || defined(__APPLE__)
24170 unsigned fsFlags; /* cached details from statfs() */
24171 #endif
24172 #if OS_VXWORKS
24173 int isDelete; /* Delete on close if true */
24174 struct vxworksFileId *pId; /* Unique file ID */
24175 #endif
24176 #ifndef NDEBUG
24177 /* The next group of variables are used to track whether or not the
24178 ** transaction counter in bytes 24-27 of database files are updated
24179 ** whenever any part of the database changes. An assertion fault will
24180 ** occur if a file is updated without also updating the transaction
24181 ** counter. This test is made to avoid new problems similar to the
24182 ** one described by ticket #3584.
24184 unsigned char transCntrChng; /* True if the transaction counter changed */
24185 unsigned char dbUpdate; /* True if any part of database file changed */
24186 unsigned char inNormalWrite; /* True if in a normal write operation */
24187 #endif
24188 #ifdef SQLITE_TEST
24189 /* In test mode, increase the size of this structure a bit so that
24190 ** it is larger than the struct CrashFile defined in test6.c.
24192 char aPadding[32];
24193 #endif
24197 ** Allowed values for the unixFile.ctrlFlags bitmask:
24199 #define UNIXFILE_EXCL 0x01 /* Connections from one process only */
24200 #define UNIXFILE_RDONLY 0x02 /* Connection is read only */
24201 #define UNIXFILE_DIRSYNC 0x04 /* Directory sync needed */
24204 ** Include code that is common to all os_*.c files
24206 /************** Include os_common.h in the middle of os_unix.c ***************/
24207 /************** Begin file os_common.h ***************************************/
24209 ** 2004 May 22
24211 ** The author disclaims copyright to this source code. In place of
24212 ** a legal notice, here is a blessing:
24214 ** May you do good and not evil.
24215 ** May you find forgiveness for yourself and forgive others.
24216 ** May you share freely, never taking more than you give.
24218 ******************************************************************************
24220 ** This file contains macros and a little bit of code that is common to
24221 ** all of the platform-specific files (os_*.c) and is #included into those
24222 ** files.
24224 ** This file should be #included by the os_*.c files only. It is not a
24225 ** general purpose header file.
24227 #ifndef _OS_COMMON_H_
24228 #define _OS_COMMON_H_
24231 ** At least two bugs have slipped in because we changed the MEMORY_DEBUG
24232 ** macro to SQLITE_DEBUG and some older makefiles have not yet made the
24233 ** switch. The following code should catch this problem at compile-time.
24235 #ifdef MEMORY_DEBUG
24236 # error "The MEMORY_DEBUG macro is obsolete. Use SQLITE_DEBUG instead."
24237 #endif
24239 #ifdef SQLITE_DEBUG
24240 SQLITE_PRIVATE int sqlite3OSTrace = 0;
24241 #define OSTRACE(X) if( sqlite3OSTrace ) sqlite3DebugPrintf X
24242 #else
24243 #define OSTRACE(X)
24244 #endif
24247 ** Macros for performance tracing. Normally turned off. Only works
24248 ** on i486 hardware.
24250 #ifdef SQLITE_PERFORMANCE_TRACE
24253 ** hwtime.h contains inline assembler code for implementing
24254 ** high-performance timing routines.
24256 /************** Include hwtime.h in the middle of os_common.h ****************/
24257 /************** Begin file hwtime.h ******************************************/
24259 ** 2008 May 27
24261 ** The author disclaims copyright to this source code. In place of
24262 ** a legal notice, here is a blessing:
24264 ** May you do good and not evil.
24265 ** May you find forgiveness for yourself and forgive others.
24266 ** May you share freely, never taking more than you give.
24268 ******************************************************************************
24270 ** This file contains inline asm code for retrieving "high-performance"
24271 ** counters for x86 class CPUs.
24273 #ifndef _HWTIME_H_
24274 #define _HWTIME_H_
24277 ** The following routine only works on pentium-class (or newer) processors.
24278 ** It uses the RDTSC opcode to read the cycle count value out of the
24279 ** processor and returns that value. This can be used for high-res
24280 ** profiling.
24282 #if (defined(__GNUC__) || defined(_MSC_VER)) && \
24283 (defined(i386) || defined(__i386__) || defined(_M_IX86))
24285 #if defined(__GNUC__)
24287 __inline__ sqlite_uint64 sqlite3Hwtime(void){
24288 unsigned int lo, hi;
24289 __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
24290 return (sqlite_uint64)hi << 32 | lo;
24293 #elif defined(_MSC_VER)
24295 __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
24296 __asm {
24297 rdtsc
24298 ret ; return value at EDX:EAX
24302 #endif
24304 #elif (defined(__GNUC__) && defined(__x86_64__))
24306 __inline__ sqlite_uint64 sqlite3Hwtime(void){
24307 unsigned long val;
24308 __asm__ __volatile__ ("rdtsc" : "=A" (val));
24309 return val;
24312 #elif (defined(__GNUC__) && defined(__ppc__))
24314 __inline__ sqlite_uint64 sqlite3Hwtime(void){
24315 unsigned long long retval;
24316 unsigned long junk;
24317 __asm__ __volatile__ ("\n\
24318 1: mftbu %1\n\
24319 mftb %L0\n\
24320 mftbu %0\n\
24321 cmpw %0,%1\n\
24322 bne 1b"
24323 : "=r" (retval), "=r" (junk));
24324 return retval;
24327 #else
24329 #error Need implementation of sqlite3Hwtime() for your platform.
24332 ** To compile without implementing sqlite3Hwtime() for your platform,
24333 ** you can remove the above #error and use the following
24334 ** stub function. You will lose timing support for many
24335 ** of the debugging and testing utilities, but it should at
24336 ** least compile and run.
24338 SQLITE_PRIVATE sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
24340 #endif
24342 #endif /* !defined(_HWTIME_H_) */
24344 /************** End of hwtime.h **********************************************/
24345 /************** Continuing where we left off in os_common.h ******************/
24347 static sqlite_uint64 g_start;
24348 static sqlite_uint64 g_elapsed;
24349 #define TIMER_START g_start=sqlite3Hwtime()
24350 #define TIMER_END g_elapsed=sqlite3Hwtime()-g_start
24351 #define TIMER_ELAPSED g_elapsed
24352 #else
24353 #define TIMER_START
24354 #define TIMER_END
24355 #define TIMER_ELAPSED ((sqlite_uint64)0)
24356 #endif
24359 ** If we compile with the SQLITE_TEST macro set, then the following block
24360 ** of code will give us the ability to simulate a disk I/O error. This
24361 ** is used for testing the I/O recovery logic.
24363 #ifdef SQLITE_TEST
24364 SQLITE_API int sqlite3_io_error_hit = 0; /* Total number of I/O Errors */
24365 SQLITE_API int sqlite3_io_error_hardhit = 0; /* Number of non-benign errors */
24366 SQLITE_API int sqlite3_io_error_pending = 0; /* Count down to first I/O error */
24367 SQLITE_API int sqlite3_io_error_persist = 0; /* True if I/O errors persist */
24368 SQLITE_API int sqlite3_io_error_benign = 0; /* True if errors are benign */
24369 SQLITE_API int sqlite3_diskfull_pending = 0;
24370 SQLITE_API int sqlite3_diskfull = 0;
24371 #define SimulateIOErrorBenign(X) sqlite3_io_error_benign=(X)
24372 #define SimulateIOError(CODE) \
24373 if( (sqlite3_io_error_persist && sqlite3_io_error_hit) \
24374 || sqlite3_io_error_pending-- == 1 ) \
24375 { local_ioerr(); CODE; }
24376 static void local_ioerr(){
24377 IOTRACE(("IOERR\n"));
24378 sqlite3_io_error_hit++;
24379 if( !sqlite3_io_error_benign ) sqlite3_io_error_hardhit++;
24381 #define SimulateDiskfullError(CODE) \
24382 if( sqlite3_diskfull_pending ){ \
24383 if( sqlite3_diskfull_pending == 1 ){ \
24384 local_ioerr(); \
24385 sqlite3_diskfull = 1; \
24386 sqlite3_io_error_hit = 1; \
24387 CODE; \
24388 }else{ \
24389 sqlite3_diskfull_pending--; \
24392 #else
24393 #define SimulateIOErrorBenign(X)
24394 #define SimulateIOError(A)
24395 #define SimulateDiskfullError(A)
24396 #endif
24399 ** When testing, keep a count of the number of open files.
24401 #ifdef SQLITE_TEST
24402 SQLITE_API int sqlite3_open_file_count = 0;
24403 #define OpenCounter(X) sqlite3_open_file_count+=(X)
24404 #else
24405 #define OpenCounter(X)
24406 #endif
24408 #endif /* !defined(_OS_COMMON_H_) */
24410 /************** End of os_common.h *******************************************/
24411 /************** Continuing where we left off in os_unix.c ********************/
24414 ** Define various macros that are missing from some systems.
24416 #ifndef O_LARGEFILE
24417 # define O_LARGEFILE 0
24418 #endif
24419 #ifdef SQLITE_DISABLE_LFS
24420 # undef O_LARGEFILE
24421 # define O_LARGEFILE 0
24422 #endif
24423 #ifndef O_NOFOLLOW
24424 # define O_NOFOLLOW 0
24425 #endif
24426 #ifndef O_BINARY
24427 # define O_BINARY 0
24428 #endif
24431 ** The threadid macro resolves to the thread-id or to 0. Used for
24432 ** testing and debugging only.
24434 #if SQLITE_THREADSAFE
24435 #define threadid pthread_self()
24436 #else
24437 #define threadid 0
24438 #endif
24440 /* Forward reference */
24441 static int openDirectory(const char*, int*);
24444 ** Many system calls are accessed through pointer-to-functions so that
24445 ** they may be overridden at runtime to facilitate fault injection during
24446 ** testing and sandboxing. The following array holds the names and pointers
24447 ** to all overrideable system calls.
24449 static struct unix_syscall {
24450 const char *zName; /* Name of the sytem call */
24451 sqlite3_syscall_ptr pCurrent; /* Current value of the system call */
24452 sqlite3_syscall_ptr pDefault; /* Default value */
24453 } aSyscall[] = {
24454 { "open", (sqlite3_syscall_ptr)open, 0 },
24455 #define osOpen ((int(*)(const char*,int,...))aSyscall[0].pCurrent)
24457 { "close", (sqlite3_syscall_ptr)close, 0 },
24458 #define osClose ((int(*)(int))aSyscall[1].pCurrent)
24460 { "access", (sqlite3_syscall_ptr)access, 0 },
24461 #define osAccess ((int(*)(const char*,int))aSyscall[2].pCurrent)
24463 { "getcwd", (sqlite3_syscall_ptr)getcwd, 0 },
24464 #define osGetcwd ((char*(*)(char*,size_t))aSyscall[3].pCurrent)
24466 { "stat", (sqlite3_syscall_ptr)stat, 0 },
24467 #define osStat ((int(*)(const char*,struct stat*))aSyscall[4].pCurrent)
24470 ** The DJGPP compiler environment looks mostly like Unix, but it
24471 ** lacks the fcntl() system call. So redefine fcntl() to be something
24472 ** that always succeeds. This means that locking does not occur under
24473 ** DJGPP. But it is DOS - what did you expect?
24475 #ifdef __DJGPP__
24476 { "fstat", 0, 0 },
24477 #define osFstat(a,b,c) 0
24478 #else
24479 { "fstat", (sqlite3_syscall_ptr)fstat, 0 },
24480 #define osFstat ((int(*)(int,struct stat*))aSyscall[5].pCurrent)
24481 #endif
24483 { "ftruncate", (sqlite3_syscall_ptr)ftruncate, 0 },
24484 #define osFtruncate ((int(*)(int,off_t))aSyscall[6].pCurrent)
24486 { "fcntl", (sqlite3_syscall_ptr)fcntl, 0 },
24487 #define osFcntl ((int(*)(int,int,...))aSyscall[7].pCurrent)
24489 { "read", (sqlite3_syscall_ptr)read, 0 },
24490 #define osRead ((ssize_t(*)(int,void*,size_t))aSyscall[8].pCurrent)
24492 #if defined(USE_PREAD) || defined(SQLITE_ENABLE_LOCKING_STYLE)
24493 { "pread", (sqlite3_syscall_ptr)pread, 0 },
24494 #else
24495 { "pread", (sqlite3_syscall_ptr)0, 0 },
24496 #endif
24497 #define osPread ((ssize_t(*)(int,void*,size_t,off_t))aSyscall[9].pCurrent)
24499 #if defined(USE_PREAD64)
24500 { "pread64", (sqlite3_syscall_ptr)pread64, 0 },
24501 #else
24502 { "pread64", (sqlite3_syscall_ptr)0, 0 },
24503 #endif
24504 #define osPread64 ((ssize_t(*)(int,void*,size_t,off_t))aSyscall[10].pCurrent)
24506 { "write", (sqlite3_syscall_ptr)write, 0 },
24507 #define osWrite ((ssize_t(*)(int,const void*,size_t))aSyscall[11].pCurrent)
24509 #if defined(USE_PREAD) || defined(SQLITE_ENABLE_LOCKING_STYLE)
24510 { "pwrite", (sqlite3_syscall_ptr)pwrite, 0 },
24511 #else
24512 { "pwrite", (sqlite3_syscall_ptr)0, 0 },
24513 #endif
24514 #define osPwrite ((ssize_t(*)(int,const void*,size_t,off_t))\
24515 aSyscall[12].pCurrent)
24517 #if defined(USE_PREAD64)
24518 { "pwrite64", (sqlite3_syscall_ptr)pwrite64, 0 },
24519 #else
24520 { "pwrite64", (sqlite3_syscall_ptr)0, 0 },
24521 #endif
24522 #define osPwrite64 ((ssize_t(*)(int,const void*,size_t,off_t))\
24523 aSyscall[13].pCurrent)
24525 #if SQLITE_ENABLE_LOCKING_STYLE
24526 { "fchmod", (sqlite3_syscall_ptr)fchmod, 0 },
24527 #else
24528 { "fchmod", (sqlite3_syscall_ptr)0, 0 },
24529 #endif
24530 #define osFchmod ((int(*)(int,mode_t))aSyscall[14].pCurrent)
24532 #if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
24533 { "fallocate", (sqlite3_syscall_ptr)posix_fallocate, 0 },
24534 #else
24535 { "fallocate", (sqlite3_syscall_ptr)0, 0 },
24536 #endif
24537 #define osFallocate ((int(*)(int,off_t,off_t))aSyscall[15].pCurrent)
24539 { "unlink", (sqlite3_syscall_ptr)unlink, 0 },
24540 #define osUnlink ((int(*)(const char*))aSyscall[16].pCurrent)
24542 { "openDirectory", (sqlite3_syscall_ptr)openDirectory, 0 },
24543 #define osOpenDirectory ((int(*)(const char*,int*))aSyscall[17].pCurrent)
24545 }; /* End of the overrideable system calls */
24548 ** This is the xSetSystemCall() method of sqlite3_vfs for all of the
24549 ** "unix" VFSes. Return SQLITE_OK opon successfully updating the
24550 ** system call pointer, or SQLITE_NOTFOUND if there is no configurable
24551 ** system call named zName.
24553 static int unixSetSystemCall(
24554 sqlite3_vfs *pNotUsed, /* The VFS pointer. Not used */
24555 const char *zName, /* Name of system call to override */
24556 sqlite3_syscall_ptr pNewFunc /* Pointer to new system call value */
24558 unsigned int i;
24559 int rc = SQLITE_NOTFOUND;
24561 UNUSED_PARAMETER(pNotUsed);
24562 if( zName==0 ){
24563 /* If no zName is given, restore all system calls to their default
24564 ** settings and return NULL
24566 rc = SQLITE_OK;
24567 for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
24568 if( aSyscall[i].pDefault ){
24569 aSyscall[i].pCurrent = aSyscall[i].pDefault;
24572 }else{
24573 /* If zName is specified, operate on only the one system call
24574 ** specified.
24576 for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
24577 if( strcmp(zName, aSyscall[i].zName)==0 ){
24578 if( aSyscall[i].pDefault==0 ){
24579 aSyscall[i].pDefault = aSyscall[i].pCurrent;
24581 rc = SQLITE_OK;
24582 if( pNewFunc==0 ) pNewFunc = aSyscall[i].pDefault;
24583 aSyscall[i].pCurrent = pNewFunc;
24584 break;
24588 return rc;
24592 ** Return the value of a system call. Return NULL if zName is not a
24593 ** recognized system call name. NULL is also returned if the system call
24594 ** is currently undefined.
24596 static sqlite3_syscall_ptr unixGetSystemCall(
24597 sqlite3_vfs *pNotUsed,
24598 const char *zName
24600 unsigned int i;
24602 UNUSED_PARAMETER(pNotUsed);
24603 for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
24604 if( strcmp(zName, aSyscall[i].zName)==0 ) return aSyscall[i].pCurrent;
24606 return 0;
24610 ** Return the name of the first system call after zName. If zName==NULL
24611 ** then return the name of the first system call. Return NULL if zName
24612 ** is the last system call or if zName is not the name of a valid
24613 ** system call.
24615 static const char *unixNextSystemCall(sqlite3_vfs *p, const char *zName){
24616 int i = -1;
24618 UNUSED_PARAMETER(p);
24619 if( zName ){
24620 for(i=0; i<ArraySize(aSyscall)-1; i++){
24621 if( strcmp(zName, aSyscall[i].zName)==0 ) break;
24624 for(i++; i<ArraySize(aSyscall); i++){
24625 if( aSyscall[i].pCurrent!=0 ) return aSyscall[i].zName;
24627 return 0;
24631 ** Retry open() calls that fail due to EINTR
24633 static int robust_open(const char *z, int f, int m){
24634 int rc;
24635 do{ rc = osOpen(z,f,m); }while( rc<0 && errno==EINTR );
24636 return rc;
24640 ** Helper functions to obtain and relinquish the global mutex. The
24641 ** global mutex is used to protect the unixInodeInfo and
24642 ** vxworksFileId objects used by this file, all of which may be
24643 ** shared by multiple threads.
24645 ** Function unixMutexHeld() is used to assert() that the global mutex
24646 ** is held when required. This function is only used as part of assert()
24647 ** statements. e.g.
24649 ** unixEnterMutex()
24650 ** assert( unixMutexHeld() );
24651 ** unixEnterLeave()
24653 static void unixEnterMutex(void){
24654 sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
24656 static void unixLeaveMutex(void){
24657 sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
24659 #ifdef SQLITE_DEBUG
24660 static int unixMutexHeld(void) {
24661 return sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
24663 #endif
24666 #ifdef SQLITE_DEBUG
24668 ** Helper function for printing out trace information from debugging
24669 ** binaries. This returns the string represetation of the supplied
24670 ** integer lock-type.
24672 static const char *azFileLock(int eFileLock){
24673 switch( eFileLock ){
24674 case NO_LOCK: return "NONE";
24675 case SHARED_LOCK: return "SHARED";
24676 case RESERVED_LOCK: return "RESERVED";
24677 case PENDING_LOCK: return "PENDING";
24678 case EXCLUSIVE_LOCK: return "EXCLUSIVE";
24680 return "ERROR";
24682 #endif
24684 #ifdef SQLITE_LOCK_TRACE
24686 ** Print out information about all locking operations.
24688 ** This routine is used for troubleshooting locks on multithreaded
24689 ** platforms. Enable by compiling with the -DSQLITE_LOCK_TRACE
24690 ** command-line option on the compiler. This code is normally
24691 ** turned off.
24693 static int lockTrace(int fd, int op, struct flock *p){
24694 char *zOpName, *zType;
24695 int s;
24696 int savedErrno;
24697 if( op==F_GETLK ){
24698 zOpName = "GETLK";
24699 }else if( op==F_SETLK ){
24700 zOpName = "SETLK";
24701 }else{
24702 s = osFcntl(fd, op, p);
24703 sqlite3DebugPrintf("fcntl unknown %d %d %d\n", fd, op, s);
24704 return s;
24706 if( p->l_type==F_RDLCK ){
24707 zType = "RDLCK";
24708 }else if( p->l_type==F_WRLCK ){
24709 zType = "WRLCK";
24710 }else if( p->l_type==F_UNLCK ){
24711 zType = "UNLCK";
24712 }else{
24713 assert( 0 );
24715 assert( p->l_whence==SEEK_SET );
24716 s = osFcntl(fd, op, p);
24717 savedErrno = errno;
24718 sqlite3DebugPrintf("fcntl %d %d %s %s %d %d %d %d\n",
24719 threadid, fd, zOpName, zType, (int)p->l_start, (int)p->l_len,
24720 (int)p->l_pid, s);
24721 if( s==(-1) && op==F_SETLK && (p->l_type==F_RDLCK || p->l_type==F_WRLCK) ){
24722 struct flock l2;
24723 l2 = *p;
24724 osFcntl(fd, F_GETLK, &l2);
24725 if( l2.l_type==F_RDLCK ){
24726 zType = "RDLCK";
24727 }else if( l2.l_type==F_WRLCK ){
24728 zType = "WRLCK";
24729 }else if( l2.l_type==F_UNLCK ){
24730 zType = "UNLCK";
24731 }else{
24732 assert( 0 );
24734 sqlite3DebugPrintf("fcntl-failure-reason: %s %d %d %d\n",
24735 zType, (int)l2.l_start, (int)l2.l_len, (int)l2.l_pid);
24737 errno = savedErrno;
24738 return s;
24740 #undef osFcntl
24741 #define osFcntl lockTrace
24742 #endif /* SQLITE_LOCK_TRACE */
24745 ** Retry ftruncate() calls that fail due to EINTR
24747 static int robust_ftruncate(int h, sqlite3_int64 sz){
24748 int rc;
24749 do{ rc = osFtruncate(h,sz); }while( rc<0 && errno==EINTR );
24750 return rc;
24754 ** This routine translates a standard POSIX errno code into something
24755 ** useful to the clients of the sqlite3 functions. Specifically, it is
24756 ** intended to translate a variety of "try again" errors into SQLITE_BUSY
24757 ** and a variety of "please close the file descriptor NOW" errors into
24758 ** SQLITE_IOERR
24760 ** Errors during initialization of locks, or file system support for locks,
24761 ** should handle ENOLCK, ENOTSUP, EOPNOTSUPP separately.
24763 static int sqliteErrorFromPosixError(int posixError, int sqliteIOErr) {
24764 switch (posixError) {
24765 #if 0
24766 /* At one point this code was not commented out. In theory, this branch
24767 ** should never be hit, as this function should only be called after
24768 ** a locking-related function (i.e. fcntl()) has returned non-zero with
24769 ** the value of errno as the first argument. Since a system call has failed,
24770 ** errno should be non-zero.
24772 ** Despite this, if errno really is zero, we still don't want to return
24773 ** SQLITE_OK. The system call failed, and *some* SQLite error should be
24774 ** propagated back to the caller. Commenting this branch out means errno==0
24775 ** will be handled by the "default:" case below.
24777 case 0:
24778 return SQLITE_OK;
24779 #endif
24781 case EAGAIN:
24782 case ETIMEDOUT:
24783 case EBUSY:
24784 case EINTR:
24785 case ENOLCK:
24786 /* random NFS retry error, unless during file system support
24787 * introspection, in which it actually means what it says */
24788 return SQLITE_BUSY;
24790 case EACCES:
24791 /* EACCES is like EAGAIN during locking operations, but not any other time*/
24792 if( (sqliteIOErr == SQLITE_IOERR_LOCK) ||
24793 (sqliteIOErr == SQLITE_IOERR_UNLOCK) ||
24794 (sqliteIOErr == SQLITE_IOERR_RDLOCK) ||
24795 (sqliteIOErr == SQLITE_IOERR_CHECKRESERVEDLOCK) ){
24796 return SQLITE_BUSY;
24798 /* else fall through */
24799 case EPERM:
24800 return SQLITE_PERM;
24802 /* EDEADLK is only possible if a call to fcntl(F_SETLKW) is made. And
24803 ** this module never makes such a call. And the code in SQLite itself
24804 ** asserts that SQLITE_IOERR_BLOCKED is never returned. For these reasons
24805 ** this case is also commented out. If the system does set errno to EDEADLK,
24806 ** the default SQLITE_IOERR_XXX code will be returned. */
24807 #if 0
24808 case EDEADLK:
24809 return SQLITE_IOERR_BLOCKED;
24810 #endif
24812 #if EOPNOTSUPP!=ENOTSUP
24813 case EOPNOTSUPP:
24814 /* something went terribly awry, unless during file system support
24815 * introspection, in which it actually means what it says */
24816 #endif
24817 #ifdef ENOTSUP
24818 case ENOTSUP:
24819 /* invalid fd, unless during file system support introspection, in which
24820 * it actually means what it says */
24821 #endif
24822 case EIO:
24823 case EBADF:
24824 case EINVAL:
24825 case ENOTCONN:
24826 case ENODEV:
24827 case ENXIO:
24828 case ENOENT:
24829 case ESTALE:
24830 case ENOSYS:
24831 /* these should force the client to close the file and reconnect */
24833 default:
24834 return sqliteIOErr;
24840 /******************************************************************************
24841 ****************** Begin Unique File ID Utility Used By VxWorks ***************
24843 ** On most versions of unix, we can get a unique ID for a file by concatenating
24844 ** the device number and the inode number. But this does not work on VxWorks.
24845 ** On VxWorks, a unique file id must be based on the canonical filename.
24847 ** A pointer to an instance of the following structure can be used as a
24848 ** unique file ID in VxWorks. Each instance of this structure contains
24849 ** a copy of the canonical filename. There is also a reference count.
24850 ** The structure is reclaimed when the number of pointers to it drops to
24851 ** zero.
24853 ** There are never very many files open at one time and lookups are not
24854 ** a performance-critical path, so it is sufficient to put these
24855 ** structures on a linked list.
24857 struct vxworksFileId {
24858 struct vxworksFileId *pNext; /* Next in a list of them all */
24859 int nRef; /* Number of references to this one */
24860 int nName; /* Length of the zCanonicalName[] string */
24861 char *zCanonicalName; /* Canonical filename */
24864 #if OS_VXWORKS
24866 ** All unique filenames are held on a linked list headed by this
24867 ** variable:
24869 static struct vxworksFileId *vxworksFileList = 0;
24872 ** Simplify a filename into its canonical form
24873 ** by making the following changes:
24875 ** * removing any trailing and duplicate /
24876 ** * convert /./ into just /
24877 ** * convert /A/../ where A is any simple name into just /
24879 ** Changes are made in-place. Return the new name length.
24881 ** The original filename is in z[0..n-1]. Return the number of
24882 ** characters in the simplified name.
24884 static int vxworksSimplifyName(char *z, int n){
24885 int i, j;
24886 while( n>1 && z[n-1]=='/' ){ n--; }
24887 for(i=j=0; i<n; i++){
24888 if( z[i]=='/' ){
24889 if( z[i+1]=='/' ) continue;
24890 if( z[i+1]=='.' && i+2<n && z[i+2]=='/' ){
24891 i += 1;
24892 continue;
24894 if( z[i+1]=='.' && i+3<n && z[i+2]=='.' && z[i+3]=='/' ){
24895 while( j>0 && z[j-1]!='/' ){ j--; }
24896 if( j>0 ){ j--; }
24897 i += 2;
24898 continue;
24901 z[j++] = z[i];
24903 z[j] = 0;
24904 return j;
24908 ** Find a unique file ID for the given absolute pathname. Return
24909 ** a pointer to the vxworksFileId object. This pointer is the unique
24910 ** file ID.
24912 ** The nRef field of the vxworksFileId object is incremented before
24913 ** the object is returned. A new vxworksFileId object is created
24914 ** and added to the global list if necessary.
24916 ** If a memory allocation error occurs, return NULL.
24918 static struct vxworksFileId *vxworksFindFileId(const char *zAbsoluteName){
24919 struct vxworksFileId *pNew; /* search key and new file ID */
24920 struct vxworksFileId *pCandidate; /* For looping over existing file IDs */
24921 int n; /* Length of zAbsoluteName string */
24923 assert( zAbsoluteName[0]=='/' );
24924 n = (int)strlen(zAbsoluteName);
24925 pNew = sqlite3_malloc( sizeof(*pNew) + (n+1) );
24926 if( pNew==0 ) return 0;
24927 pNew->zCanonicalName = (char*)&pNew[1];
24928 memcpy(pNew->zCanonicalName, zAbsoluteName, n+1);
24929 n = vxworksSimplifyName(pNew->zCanonicalName, n);
24931 /* Search for an existing entry that matching the canonical name.
24932 ** If found, increment the reference count and return a pointer to
24933 ** the existing file ID.
24935 unixEnterMutex();
24936 for(pCandidate=vxworksFileList; pCandidate; pCandidate=pCandidate->pNext){
24937 if( pCandidate->nName==n
24938 && memcmp(pCandidate->zCanonicalName, pNew->zCanonicalName, n)==0
24940 sqlite3_free(pNew);
24941 pCandidate->nRef++;
24942 unixLeaveMutex();
24943 return pCandidate;
24947 /* No match was found. We will make a new file ID */
24948 pNew->nRef = 1;
24949 pNew->nName = n;
24950 pNew->pNext = vxworksFileList;
24951 vxworksFileList = pNew;
24952 unixLeaveMutex();
24953 return pNew;
24957 ** Decrement the reference count on a vxworksFileId object. Free
24958 ** the object when the reference count reaches zero.
24960 static void vxworksReleaseFileId(struct vxworksFileId *pId){
24961 unixEnterMutex();
24962 assert( pId->nRef>0 );
24963 pId->nRef--;
24964 if( pId->nRef==0 ){
24965 struct vxworksFileId **pp;
24966 for(pp=&vxworksFileList; *pp && *pp!=pId; pp = &((*pp)->pNext)){}
24967 assert( *pp==pId );
24968 *pp = pId->pNext;
24969 sqlite3_free(pId);
24971 unixLeaveMutex();
24973 #endif /* OS_VXWORKS */
24974 /*************** End of Unique File ID Utility Used By VxWorks ****************
24975 ******************************************************************************/
24978 /******************************************************************************
24979 *************************** Posix Advisory Locking ****************************
24981 ** POSIX advisory locks are broken by design. ANSI STD 1003.1 (1996)
24982 ** section 6.5.2.2 lines 483 through 490 specify that when a process
24983 ** sets or clears a lock, that operation overrides any prior locks set
24984 ** by the same process. It does not explicitly say so, but this implies
24985 ** that it overrides locks set by the same process using a different
24986 ** file descriptor. Consider this test case:
24988 ** int fd1 = open("./file1", O_RDWR|O_CREAT, 0644);
24989 ** int fd2 = open("./file2", O_RDWR|O_CREAT, 0644);
24991 ** Suppose ./file1 and ./file2 are really the same file (because
24992 ** one is a hard or symbolic link to the other) then if you set
24993 ** an exclusive lock on fd1, then try to get an exclusive lock
24994 ** on fd2, it works. I would have expected the second lock to
24995 ** fail since there was already a lock on the file due to fd1.
24996 ** But not so. Since both locks came from the same process, the
24997 ** second overrides the first, even though they were on different
24998 ** file descriptors opened on different file names.
25000 ** This means that we cannot use POSIX locks to synchronize file access
25001 ** among competing threads of the same process. POSIX locks will work fine
25002 ** to synchronize access for threads in separate processes, but not
25003 ** threads within the same process.
25005 ** To work around the problem, SQLite has to manage file locks internally
25006 ** on its own. Whenever a new database is opened, we have to find the
25007 ** specific inode of the database file (the inode is determined by the
25008 ** st_dev and st_ino fields of the stat structure that fstat() fills in)
25009 ** and check for locks already existing on that inode. When locks are
25010 ** created or removed, we have to look at our own internal record of the
25011 ** locks to see if another thread has previously set a lock on that same
25012 ** inode.
25014 ** (Aside: The use of inode numbers as unique IDs does not work on VxWorks.
25015 ** For VxWorks, we have to use the alternative unique ID system based on
25016 ** canonical filename and implemented in the previous division.)
25018 ** The sqlite3_file structure for POSIX is no longer just an integer file
25019 ** descriptor. It is now a structure that holds the integer file
25020 ** descriptor and a pointer to a structure that describes the internal
25021 ** locks on the corresponding inode. There is one locking structure
25022 ** per inode, so if the same inode is opened twice, both unixFile structures
25023 ** point to the same locking structure. The locking structure keeps
25024 ** a reference count (so we will know when to delete it) and a "cnt"
25025 ** field that tells us its internal lock status. cnt==0 means the
25026 ** file is unlocked. cnt==-1 means the file has an exclusive lock.
25027 ** cnt>0 means there are cnt shared locks on the file.
25029 ** Any attempt to lock or unlock a file first checks the locking
25030 ** structure. The fcntl() system call is only invoked to set a
25031 ** POSIX lock if the internal lock structure transitions between
25032 ** a locked and an unlocked state.
25034 ** But wait: there are yet more problems with POSIX advisory locks.
25036 ** If you close a file descriptor that points to a file that has locks,
25037 ** all locks on that file that are owned by the current process are
25038 ** released. To work around this problem, each unixInodeInfo object
25039 ** maintains a count of the number of pending locks on tha inode.
25040 ** When an attempt is made to close an unixFile, if there are
25041 ** other unixFile open on the same inode that are holding locks, the call
25042 ** to close() the file descriptor is deferred until all of the locks clear.
25043 ** The unixInodeInfo structure keeps a list of file descriptors that need to
25044 ** be closed and that list is walked (and cleared) when the last lock
25045 ** clears.
25047 ** Yet another problem: LinuxThreads do not play well with posix locks.
25049 ** Many older versions of linux use the LinuxThreads library which is
25050 ** not posix compliant. Under LinuxThreads, a lock created by thread
25051 ** A cannot be modified or overridden by a different thread B.
25052 ** Only thread A can modify the lock. Locking behavior is correct
25053 ** if the appliation uses the newer Native Posix Thread Library (NPTL)
25054 ** on linux - with NPTL a lock created by thread A can override locks
25055 ** in thread B. But there is no way to know at compile-time which
25056 ** threading library is being used. So there is no way to know at
25057 ** compile-time whether or not thread A can override locks on thread B.
25058 ** One has to do a run-time check to discover the behavior of the
25059 ** current process.
25061 ** SQLite used to support LinuxThreads. But support for LinuxThreads
25062 ** was dropped beginning with version 3.7.0. SQLite will still work with
25063 ** LinuxThreads provided that (1) there is no more than one connection
25064 ** per database file in the same process and (2) database connections
25065 ** do not move across threads.
25069 ** An instance of the following structure serves as the key used
25070 ** to locate a particular unixInodeInfo object.
25072 struct unixFileId {
25073 dev_t dev; /* Device number */
25074 #if OS_VXWORKS
25075 struct vxworksFileId *pId; /* Unique file ID for vxworks. */
25076 #else
25077 ino_t ino; /* Inode number */
25078 #endif
25082 ** An instance of the following structure is allocated for each open
25083 ** inode. Or, on LinuxThreads, there is one of these structures for
25084 ** each inode opened by each thread.
25086 ** A single inode can have multiple file descriptors, so each unixFile
25087 ** structure contains a pointer to an instance of this object and this
25088 ** object keeps a count of the number of unixFile pointing to it.
25090 struct unixInodeInfo {
25091 struct unixFileId fileId; /* The lookup key */
25092 int nShared; /* Number of SHARED locks held */
25093 unsigned char eFileLock; /* One of SHARED_LOCK, RESERVED_LOCK etc. */
25094 unsigned char bProcessLock; /* An exclusive process lock is held */
25095 int nRef; /* Number of pointers to this structure */
25096 unixShmNode *pShmNode; /* Shared memory associated with this inode */
25097 int nLock; /* Number of outstanding file locks */
25098 UnixUnusedFd *pUnused; /* Unused file descriptors to close */
25099 unixInodeInfo *pNext; /* List of all unixInodeInfo objects */
25100 unixInodeInfo *pPrev; /* .... doubly linked */
25101 #if defined(SQLITE_ENABLE_LOCKING_STYLE)
25102 unsigned long long sharedByte; /* for AFP simulated shared lock */
25103 #endif
25104 #if OS_VXWORKS
25105 sem_t *pSem; /* Named POSIX semaphore */
25106 char aSemName[MAX_PATHNAME+2]; /* Name of that semaphore */
25107 #endif
25111 ** A lists of all unixInodeInfo objects.
25113 static unixInodeInfo *inodeList = 0;
25117 ** This function - unixLogError_x(), is only ever called via the macro
25118 ** unixLogError().
25120 ** It is invoked after an error occurs in an OS function and errno has been
25121 ** set. It logs a message using sqlite3_log() containing the current value of
25122 ** errno and, if possible, the human-readable equivalent from strerror() or
25123 ** strerror_r().
25125 ** The first argument passed to the macro should be the error code that
25126 ** will be returned to SQLite (e.g. SQLITE_IOERR_DELETE, SQLITE_CANTOPEN).
25127 ** The two subsequent arguments should be the name of the OS function that
25128 ** failed (e.g. "unlink", "open") and the the associated file-system path,
25129 ** if any.
25131 #define unixLogError(a,b,c) unixLogErrorAtLine(a,b,c,__LINE__)
25132 static int unixLogErrorAtLine(
25133 int errcode, /* SQLite error code */
25134 const char *zFunc, /* Name of OS function that failed */
25135 const char *zPath, /* File path associated with error */
25136 int iLine /* Source line number where error occurred */
25138 char *zErr; /* Message from strerror() or equivalent */
25139 int iErrno = errno; /* Saved syscall error number */
25141 /* If this is not a threadsafe build (SQLITE_THREADSAFE==0), then use
25142 ** the strerror() function to obtain the human-readable error message
25143 ** equivalent to errno. Otherwise, use strerror_r().
25145 #if SQLITE_THREADSAFE && defined(HAVE_STRERROR_R)
25146 char aErr[80];
25147 memset(aErr, 0, sizeof(aErr));
25148 zErr = aErr;
25150 /* If STRERROR_R_CHAR_P (set by autoconf scripts) or __USE_GNU is defined,
25151 ** assume that the system provides the the GNU version of strerror_r() that
25152 ** returns a pointer to a buffer containing the error message. That pointer
25153 ** may point to aErr[], or it may point to some static storage somewhere.
25154 ** Otherwise, assume that the system provides the POSIX version of
25155 ** strerror_r(), which always writes an error message into aErr[].
25157 ** If the code incorrectly assumes that it is the POSIX version that is
25158 ** available, the error message will often be an empty string. Not a
25159 ** huge problem. Incorrectly concluding that the GNU version is available
25160 ** could lead to a segfault though.
25162 #if defined(STRERROR_R_CHAR_P) || defined(__USE_GNU)
25163 zErr =
25164 # endif
25165 strerror_r(iErrno, aErr, sizeof(aErr)-1);
25167 #elif SQLITE_THREADSAFE
25168 /* This is a threadsafe build, but strerror_r() is not available. */
25169 zErr = "";
25170 #else
25171 /* Non-threadsafe build, use strerror(). */
25172 zErr = strerror(iErrno);
25173 #endif
25175 assert( errcode!=SQLITE_OK );
25176 if( zPath==0 ) zPath = "";
25177 sqlite3_log(errcode,
25178 "os_unix.c:%d: (%d) %s(%s) - %s",
25179 iLine, iErrno, zFunc, zPath, zErr
25182 return errcode;
25186 ** Close a file descriptor.
25188 ** We assume that close() almost always works, since it is only in a
25189 ** very sick application or on a very sick platform that it might fail.
25190 ** If it does fail, simply leak the file descriptor, but do log the
25191 ** error.
25193 ** Note that it is not safe to retry close() after EINTR since the
25194 ** file descriptor might have already been reused by another thread.
25195 ** So we don't even try to recover from an EINTR. Just log the error
25196 ** and move on.
25198 static void robust_close(unixFile *pFile, int h, int lineno){
25199 if( osClose(h) ){
25200 unixLogErrorAtLine(SQLITE_IOERR_CLOSE, "close",
25201 pFile ? pFile->zPath : 0, lineno);
25206 ** Close all file descriptors accumuated in the unixInodeInfo->pUnused list.
25208 static void closePendingFds(unixFile *pFile){
25209 unixInodeInfo *pInode = pFile->pInode;
25210 UnixUnusedFd *p;
25211 UnixUnusedFd *pNext;
25212 for(p=pInode->pUnused; p; p=pNext){
25213 pNext = p->pNext;
25214 robust_close(pFile, p->fd, __LINE__);
25215 sqlite3_free(p);
25217 pInode->pUnused = 0;
25221 ** Release a unixInodeInfo structure previously allocated by findInodeInfo().
25223 ** The mutex entered using the unixEnterMutex() function must be held
25224 ** when this function is called.
25226 static void releaseInodeInfo(unixFile *pFile){
25227 unixInodeInfo *pInode = pFile->pInode;
25228 assert( unixMutexHeld() );
25229 if( ALWAYS(pInode) ){
25230 pInode->nRef--;
25231 if( pInode->nRef==0 ){
25232 assert( pInode->pShmNode==0 );
25233 closePendingFds(pFile);
25234 if( pInode->pPrev ){
25235 assert( pInode->pPrev->pNext==pInode );
25236 pInode->pPrev->pNext = pInode->pNext;
25237 }else{
25238 assert( inodeList==pInode );
25239 inodeList = pInode->pNext;
25241 if( pInode->pNext ){
25242 assert( pInode->pNext->pPrev==pInode );
25243 pInode->pNext->pPrev = pInode->pPrev;
25245 sqlite3_free(pInode);
25251 ** Given a file descriptor, locate the unixInodeInfo object that
25252 ** describes that file descriptor. Create a new one if necessary. The
25253 ** return value might be uninitialized if an error occurs.
25255 ** The mutex entered using the unixEnterMutex() function must be held
25256 ** when this function is called.
25258 ** Return an appropriate error code.
25260 static int findInodeInfo(
25261 unixFile *pFile, /* Unix file with file desc used in the key */
25262 unixInodeInfo **ppInode /* Return the unixInodeInfo object here */
25264 int rc; /* System call return code */
25265 int fd; /* The file descriptor for pFile */
25266 struct unixFileId fileId; /* Lookup key for the unixInodeInfo */
25267 struct stat statbuf; /* Low-level file information */
25268 unixInodeInfo *pInode = 0; /* Candidate unixInodeInfo object */
25270 assert( unixMutexHeld() );
25272 /* Get low-level information about the file that we can used to
25273 ** create a unique name for the file.
25275 fd = pFile->h;
25276 rc = osFstat(fd, &statbuf);
25277 if( rc!=0 ){
25278 pFile->lastErrno = errno;
25279 #ifdef EOVERFLOW
25280 if( pFile->lastErrno==EOVERFLOW ) return SQLITE_NOLFS;
25281 #endif
25282 return SQLITE_IOERR;
25285 #ifdef __APPLE__
25286 /* On OS X on an msdos filesystem, the inode number is reported
25287 ** incorrectly for zero-size files. See ticket #3260. To work
25288 ** around this problem (we consider it a bug in OS X, not SQLite)
25289 ** we always increase the file size to 1 by writing a single byte
25290 ** prior to accessing the inode number. The one byte written is
25291 ** an ASCII 'S' character which also happens to be the first byte
25292 ** in the header of every SQLite database. In this way, if there
25293 ** is a race condition such that another thread has already populated
25294 ** the first page of the database, no damage is done.
25296 if( statbuf.st_size==0 && (pFile->fsFlags & SQLITE_FSFLAGS_IS_MSDOS)!=0 ){
25297 do{ rc = osWrite(fd, "S", 1); }while( rc<0 && errno==EINTR );
25298 if( rc!=1 ){
25299 pFile->lastErrno = errno;
25300 return SQLITE_IOERR;
25302 rc = osFstat(fd, &statbuf);
25303 if( rc!=0 ){
25304 pFile->lastErrno = errno;
25305 return SQLITE_IOERR;
25308 #endif
25310 memset(&fileId, 0, sizeof(fileId));
25311 fileId.dev = statbuf.st_dev;
25312 #if OS_VXWORKS
25313 fileId.pId = pFile->pId;
25314 #else
25315 fileId.ino = statbuf.st_ino;
25316 #endif
25317 pInode = inodeList;
25318 while( pInode && memcmp(&fileId, &pInode->fileId, sizeof(fileId)) ){
25319 pInode = pInode->pNext;
25321 if( pInode==0 ){
25322 pInode = sqlite3_malloc( sizeof(*pInode) );
25323 if( pInode==0 ){
25324 return SQLITE_NOMEM;
25326 memset(pInode, 0, sizeof(*pInode));
25327 memcpy(&pInode->fileId, &fileId, sizeof(fileId));
25328 pInode->nRef = 1;
25329 pInode->pNext = inodeList;
25330 pInode->pPrev = 0;
25331 if( inodeList ) inodeList->pPrev = pInode;
25332 inodeList = pInode;
25333 }else{
25334 pInode->nRef++;
25336 *ppInode = pInode;
25337 return SQLITE_OK;
25342 ** This routine checks if there is a RESERVED lock held on the specified
25343 ** file by this or any other process. If such a lock is held, set *pResOut
25344 ** to a non-zero value otherwise *pResOut is set to zero. The return value
25345 ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
25347 static int unixCheckReservedLock(sqlite3_file *id, int *pResOut){
25348 int rc = SQLITE_OK;
25349 int reserved = 0;
25350 unixFile *pFile = (unixFile*)id;
25352 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
25354 assert( pFile );
25355 unixEnterMutex(); /* Because pFile->pInode is shared across threads */
25357 /* Check if a thread in this process holds such a lock */
25358 if( pFile->pInode->eFileLock>SHARED_LOCK ){
25359 reserved = 1;
25362 /* Otherwise see if some other process holds it.
25364 #ifndef __DJGPP__
25365 if( !reserved && !pFile->pInode->bProcessLock ){
25366 struct flock lock;
25367 lock.l_whence = SEEK_SET;
25368 lock.l_start = RESERVED_BYTE;
25369 lock.l_len = 1;
25370 lock.l_type = F_WRLCK;
25371 if( osFcntl(pFile->h, F_GETLK, &lock) ){
25372 rc = SQLITE_IOERR_CHECKRESERVEDLOCK;
25373 pFile->lastErrno = errno;
25374 } else if( lock.l_type!=F_UNLCK ){
25375 reserved = 1;
25378 #endif
25380 unixLeaveMutex();
25381 OSTRACE(("TEST WR-LOCK %d %d %d (unix)\n", pFile->h, rc, reserved));
25383 *pResOut = reserved;
25384 return rc;
25388 ** Attempt to set a system-lock on the file pFile. The lock is
25389 ** described by pLock.
25391 ** If the pFile was opened read/write from unix-excl, then the only lock
25392 ** ever obtained is an exclusive lock, and it is obtained exactly once
25393 ** the first time any lock is attempted. All subsequent system locking
25394 ** operations become no-ops. Locking operations still happen internally,
25395 ** in order to coordinate access between separate database connections
25396 ** within this process, but all of that is handled in memory and the
25397 ** operating system does not participate.
25399 ** This function is a pass-through to fcntl(F_SETLK) if pFile is using
25400 ** any VFS other than "unix-excl" or if pFile is opened on "unix-excl"
25401 ** and is read-only.
25403 ** Zero is returned if the call completes successfully, or -1 if a call
25404 ** to fcntl() fails. In this case, errno is set appropriately (by fcntl()).
25406 static int unixFileLock(unixFile *pFile, struct flock *pLock){
25407 int rc;
25408 unixInodeInfo *pInode = pFile->pInode;
25409 assert( unixMutexHeld() );
25410 assert( pInode!=0 );
25411 if( ((pFile->ctrlFlags & UNIXFILE_EXCL)!=0 || pInode->bProcessLock)
25412 && ((pFile->ctrlFlags & UNIXFILE_RDONLY)==0)
25414 if( pInode->bProcessLock==0 ){
25415 struct flock lock;
25416 assert( pInode->nLock==0 );
25417 lock.l_whence = SEEK_SET;
25418 lock.l_start = SHARED_FIRST;
25419 lock.l_len = SHARED_SIZE;
25420 lock.l_type = F_WRLCK;
25421 rc = osFcntl(pFile->h, F_SETLK, &lock);
25422 if( rc<0 ) return rc;
25423 pInode->bProcessLock = 1;
25424 pInode->nLock++;
25425 }else{
25426 rc = 0;
25428 }else{
25429 rc = osFcntl(pFile->h, F_SETLK, pLock);
25431 return rc;
25435 ** Lock the file with the lock specified by parameter eFileLock - one
25436 ** of the following:
25438 ** (1) SHARED_LOCK
25439 ** (2) RESERVED_LOCK
25440 ** (3) PENDING_LOCK
25441 ** (4) EXCLUSIVE_LOCK
25443 ** Sometimes when requesting one lock state, additional lock states
25444 ** are inserted in between. The locking might fail on one of the later
25445 ** transitions leaving the lock state different from what it started but
25446 ** still short of its goal. The following chart shows the allowed
25447 ** transitions and the inserted intermediate states:
25449 ** UNLOCKED -> SHARED
25450 ** SHARED -> RESERVED
25451 ** SHARED -> (PENDING) -> EXCLUSIVE
25452 ** RESERVED -> (PENDING) -> EXCLUSIVE
25453 ** PENDING -> EXCLUSIVE
25455 ** This routine will only increase a lock. Use the sqlite3OsUnlock()
25456 ** routine to lower a locking level.
25458 static int unixLock(sqlite3_file *id, int eFileLock){
25459 /* The following describes the implementation of the various locks and
25460 ** lock transitions in terms of the POSIX advisory shared and exclusive
25461 ** lock primitives (called read-locks and write-locks below, to avoid
25462 ** confusion with SQLite lock names). The algorithms are complicated
25463 ** slightly in order to be compatible with windows systems simultaneously
25464 ** accessing the same database file, in case that is ever required.
25466 ** Symbols defined in os.h indentify the 'pending byte' and the 'reserved
25467 ** byte', each single bytes at well known offsets, and the 'shared byte
25468 ** range', a range of 510 bytes at a well known offset.
25470 ** To obtain a SHARED lock, a read-lock is obtained on the 'pending
25471 ** byte'. If this is successful, a random byte from the 'shared byte
25472 ** range' is read-locked and the lock on the 'pending byte' released.
25474 ** A process may only obtain a RESERVED lock after it has a SHARED lock.
25475 ** A RESERVED lock is implemented by grabbing a write-lock on the
25476 ** 'reserved byte'.
25478 ** A process may only obtain a PENDING lock after it has obtained a
25479 ** SHARED lock. A PENDING lock is implemented by obtaining a write-lock
25480 ** on the 'pending byte'. This ensures that no new SHARED locks can be
25481 ** obtained, but existing SHARED locks are allowed to persist. A process
25482 ** does not have to obtain a RESERVED lock on the way to a PENDING lock.
25483 ** This property is used by the algorithm for rolling back a journal file
25484 ** after a crash.
25486 ** An EXCLUSIVE lock, obtained after a PENDING lock is held, is
25487 ** implemented by obtaining a write-lock on the entire 'shared byte
25488 ** range'. Since all other locks require a read-lock on one of the bytes
25489 ** within this range, this ensures that no other locks are held on the
25490 ** database.
25492 ** The reason a single byte cannot be used instead of the 'shared byte
25493 ** range' is that some versions of windows do not support read-locks. By
25494 ** locking a random byte from a range, concurrent SHARED locks may exist
25495 ** even if the locking primitive used is always a write-lock.
25497 int rc = SQLITE_OK;
25498 unixFile *pFile = (unixFile*)id;
25499 unixInodeInfo *pInode = pFile->pInode;
25500 struct flock lock;
25501 int tErrno = 0;
25503 assert( pFile );
25504 OSTRACE(("LOCK %d %s was %s(%s,%d) pid=%d (unix)\n", pFile->h,
25505 azFileLock(eFileLock), azFileLock(pFile->eFileLock),
25506 azFileLock(pInode->eFileLock), pInode->nShared , getpid()));
25508 /* If there is already a lock of this type or more restrictive on the
25509 ** unixFile, do nothing. Don't use the end_lock: exit path, as
25510 ** unixEnterMutex() hasn't been called yet.
25512 if( pFile->eFileLock>=eFileLock ){
25513 OSTRACE(("LOCK %d %s ok (already held) (unix)\n", pFile->h,
25514 azFileLock(eFileLock)));
25515 return SQLITE_OK;
25518 /* Make sure the locking sequence is correct.
25519 ** (1) We never move from unlocked to anything higher than shared lock.
25520 ** (2) SQLite never explicitly requests a pendig lock.
25521 ** (3) A shared lock is always held when a reserve lock is requested.
25523 assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
25524 assert( eFileLock!=PENDING_LOCK );
25525 assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
25527 /* This mutex is needed because pFile->pInode is shared across threads
25529 unixEnterMutex();
25530 pInode = pFile->pInode;
25532 /* If some thread using this PID has a lock via a different unixFile*
25533 ** handle that precludes the requested lock, return BUSY.
25535 if( (pFile->eFileLock!=pInode->eFileLock &&
25536 (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
25538 rc = SQLITE_BUSY;
25539 goto end_lock;
25542 /* If a SHARED lock is requested, and some thread using this PID already
25543 ** has a SHARED or RESERVED lock, then increment reference counts and
25544 ** return SQLITE_OK.
25546 if( eFileLock==SHARED_LOCK &&
25547 (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
25548 assert( eFileLock==SHARED_LOCK );
25549 assert( pFile->eFileLock==0 );
25550 assert( pInode->nShared>0 );
25551 pFile->eFileLock = SHARED_LOCK;
25552 pInode->nShared++;
25553 pInode->nLock++;
25554 goto end_lock;
25558 /* A PENDING lock is needed before acquiring a SHARED lock and before
25559 ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
25560 ** be released.
25562 lock.l_len = 1L;
25563 lock.l_whence = SEEK_SET;
25564 if( eFileLock==SHARED_LOCK
25565 || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
25567 lock.l_type = (eFileLock==SHARED_LOCK?F_RDLCK:F_WRLCK);
25568 lock.l_start = PENDING_BYTE;
25569 if( unixFileLock(pFile, &lock) ){
25570 tErrno = errno;
25571 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
25572 if( rc!=SQLITE_BUSY ){
25573 pFile->lastErrno = tErrno;
25575 goto end_lock;
25580 /* If control gets to this point, then actually go ahead and make
25581 ** operating system calls for the specified lock.
25583 if( eFileLock==SHARED_LOCK ){
25584 assert( pInode->nShared==0 );
25585 assert( pInode->eFileLock==0 );
25586 assert( rc==SQLITE_OK );
25588 /* Now get the read-lock */
25589 lock.l_start = SHARED_FIRST;
25590 lock.l_len = SHARED_SIZE;
25591 if( unixFileLock(pFile, &lock) ){
25592 tErrno = errno;
25593 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
25596 /* Drop the temporary PENDING lock */
25597 lock.l_start = PENDING_BYTE;
25598 lock.l_len = 1L;
25599 lock.l_type = F_UNLCK;
25600 if( unixFileLock(pFile, &lock) && rc==SQLITE_OK ){
25601 /* This could happen with a network mount */
25602 tErrno = errno;
25603 rc = SQLITE_IOERR_UNLOCK;
25606 if( rc ){
25607 if( rc!=SQLITE_BUSY ){
25608 pFile->lastErrno = tErrno;
25610 goto end_lock;
25611 }else{
25612 pFile->eFileLock = SHARED_LOCK;
25613 pInode->nLock++;
25614 pInode->nShared = 1;
25616 }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
25617 /* We are trying for an exclusive lock but another thread in this
25618 ** same process is still holding a shared lock. */
25619 rc = SQLITE_BUSY;
25620 }else{
25621 /* The request was for a RESERVED or EXCLUSIVE lock. It is
25622 ** assumed that there is a SHARED or greater lock on the file
25623 ** already.
25625 assert( 0!=pFile->eFileLock );
25626 lock.l_type = F_WRLCK;
25628 assert( eFileLock==RESERVED_LOCK || eFileLock==EXCLUSIVE_LOCK );
25629 if( eFileLock==RESERVED_LOCK ){
25630 lock.l_start = RESERVED_BYTE;
25631 lock.l_len = 1L;
25632 }else{
25633 lock.l_start = SHARED_FIRST;
25634 lock.l_len = SHARED_SIZE;
25637 if( unixFileLock(pFile, &lock) ){
25638 tErrno = errno;
25639 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
25640 if( rc!=SQLITE_BUSY ){
25641 pFile->lastErrno = tErrno;
25647 #ifndef NDEBUG
25648 /* Set up the transaction-counter change checking flags when
25649 ** transitioning from a SHARED to a RESERVED lock. The change
25650 ** from SHARED to RESERVED marks the beginning of a normal
25651 ** write operation (not a hot journal rollback).
25653 if( rc==SQLITE_OK
25654 && pFile->eFileLock<=SHARED_LOCK
25655 && eFileLock==RESERVED_LOCK
25657 pFile->transCntrChng = 0;
25658 pFile->dbUpdate = 0;
25659 pFile->inNormalWrite = 1;
25661 #endif
25664 if( rc==SQLITE_OK ){
25665 pFile->eFileLock = eFileLock;
25666 pInode->eFileLock = eFileLock;
25667 }else if( eFileLock==EXCLUSIVE_LOCK ){
25668 pFile->eFileLock = PENDING_LOCK;
25669 pInode->eFileLock = PENDING_LOCK;
25672 end_lock:
25673 unixLeaveMutex();
25674 OSTRACE(("LOCK %d %s %s (unix)\n", pFile->h, azFileLock(eFileLock),
25675 rc==SQLITE_OK ? "ok" : "failed"));
25676 return rc;
25680 ** Add the file descriptor used by file handle pFile to the corresponding
25681 ** pUnused list.
25683 static void setPendingFd(unixFile *pFile){
25684 unixInodeInfo *pInode = pFile->pInode;
25685 UnixUnusedFd *p = pFile->pUnused;
25686 p->pNext = pInode->pUnused;
25687 pInode->pUnused = p;
25688 pFile->h = -1;
25689 pFile->pUnused = 0;
25693 ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
25694 ** must be either NO_LOCK or SHARED_LOCK.
25696 ** If the locking level of the file descriptor is already at or below
25697 ** the requested locking level, this routine is a no-op.
25699 ** If handleNFSUnlock is true, then on downgrading an EXCLUSIVE_LOCK to SHARED
25700 ** the byte range is divided into 2 parts and the first part is unlocked then
25701 ** set to a read lock, then the other part is simply unlocked. This works
25702 ** around a bug in BSD NFS lockd (also seen on MacOSX 10.3+) that fails to
25703 ** remove the write lock on a region when a read lock is set.
25705 static int posixUnlock(sqlite3_file *id, int eFileLock, int handleNFSUnlock){
25706 unixFile *pFile = (unixFile*)id;
25707 unixInodeInfo *pInode;
25708 struct flock lock;
25709 int rc = SQLITE_OK;
25710 int h;
25712 assert( pFile );
25713 OSTRACE(("UNLOCK %d %d was %d(%d,%d) pid=%d (unix)\n", pFile->h, eFileLock,
25714 pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
25715 getpid()));
25717 assert( eFileLock<=SHARED_LOCK );
25718 if( pFile->eFileLock<=eFileLock ){
25719 return SQLITE_OK;
25721 unixEnterMutex();
25722 h = pFile->h;
25723 pInode = pFile->pInode;
25724 assert( pInode->nShared!=0 );
25725 if( pFile->eFileLock>SHARED_LOCK ){
25726 assert( pInode->eFileLock==pFile->eFileLock );
25727 SimulateIOErrorBenign(1);
25728 SimulateIOError( h=(-1) )
25729 SimulateIOErrorBenign(0);
25731 #ifndef NDEBUG
25732 /* When reducing a lock such that other processes can start
25733 ** reading the database file again, make sure that the
25734 ** transaction counter was updated if any part of the database
25735 ** file changed. If the transaction counter is not updated,
25736 ** other connections to the same file might not realize that
25737 ** the file has changed and hence might not know to flush their
25738 ** cache. The use of a stale cache can lead to database corruption.
25740 #if 0
25741 assert( pFile->inNormalWrite==0
25742 || pFile->dbUpdate==0
25743 || pFile->transCntrChng==1 );
25744 #endif
25745 pFile->inNormalWrite = 0;
25746 #endif
25748 /* downgrading to a shared lock on NFS involves clearing the write lock
25749 ** before establishing the readlock - to avoid a race condition we downgrade
25750 ** the lock in 2 blocks, so that part of the range will be covered by a
25751 ** write lock until the rest is covered by a read lock:
25752 ** 1: [WWWWW]
25753 ** 2: [....W]
25754 ** 3: [RRRRW]
25755 ** 4: [RRRR.]
25757 if( eFileLock==SHARED_LOCK ){
25759 #if !defined(__APPLE__) || !SQLITE_ENABLE_LOCKING_STYLE
25760 (void)handleNFSUnlock;
25761 assert( handleNFSUnlock==0 );
25762 #endif
25763 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
25764 if( handleNFSUnlock ){
25765 int tErrno; /* Error code from system call errors */
25766 off_t divSize = SHARED_SIZE - 1;
25768 lock.l_type = F_UNLCK;
25769 lock.l_whence = SEEK_SET;
25770 lock.l_start = SHARED_FIRST;
25771 lock.l_len = divSize;
25772 if( unixFileLock(pFile, &lock)==(-1) ){
25773 tErrno = errno;
25774 rc = SQLITE_IOERR_UNLOCK;
25775 if( IS_LOCK_ERROR(rc) ){
25776 pFile->lastErrno = tErrno;
25778 goto end_unlock;
25780 lock.l_type = F_RDLCK;
25781 lock.l_whence = SEEK_SET;
25782 lock.l_start = SHARED_FIRST;
25783 lock.l_len = divSize;
25784 if( unixFileLock(pFile, &lock)==(-1) ){
25785 tErrno = errno;
25786 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_RDLOCK);
25787 if( IS_LOCK_ERROR(rc) ){
25788 pFile->lastErrno = tErrno;
25790 goto end_unlock;
25792 lock.l_type = F_UNLCK;
25793 lock.l_whence = SEEK_SET;
25794 lock.l_start = SHARED_FIRST+divSize;
25795 lock.l_len = SHARED_SIZE-divSize;
25796 if( unixFileLock(pFile, &lock)==(-1) ){
25797 tErrno = errno;
25798 rc = SQLITE_IOERR_UNLOCK;
25799 if( IS_LOCK_ERROR(rc) ){
25800 pFile->lastErrno = tErrno;
25802 goto end_unlock;
25804 }else
25805 #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
25807 lock.l_type = F_RDLCK;
25808 lock.l_whence = SEEK_SET;
25809 lock.l_start = SHARED_FIRST;
25810 lock.l_len = SHARED_SIZE;
25811 if( unixFileLock(pFile, &lock) ){
25812 /* In theory, the call to unixFileLock() cannot fail because another
25813 ** process is holding an incompatible lock. If it does, this
25814 ** indicates that the other process is not following the locking
25815 ** protocol. If this happens, return SQLITE_IOERR_RDLOCK. Returning
25816 ** SQLITE_BUSY would confuse the upper layer (in practice it causes
25817 ** an assert to fail). */
25818 rc = SQLITE_IOERR_RDLOCK;
25819 pFile->lastErrno = errno;
25820 goto end_unlock;
25824 lock.l_type = F_UNLCK;
25825 lock.l_whence = SEEK_SET;
25826 lock.l_start = PENDING_BYTE;
25827 lock.l_len = 2L; assert( PENDING_BYTE+1==RESERVED_BYTE );
25828 if( unixFileLock(pFile, &lock)==0 ){
25829 pInode->eFileLock = SHARED_LOCK;
25830 }else{
25831 rc = SQLITE_IOERR_UNLOCK;
25832 pFile->lastErrno = errno;
25833 goto end_unlock;
25836 if( eFileLock==NO_LOCK ){
25837 /* Decrement the shared lock counter. Release the lock using an
25838 ** OS call only when all threads in this same process have released
25839 ** the lock.
25841 pInode->nShared--;
25842 if( pInode->nShared==0 ){
25843 lock.l_type = F_UNLCK;
25844 lock.l_whence = SEEK_SET;
25845 lock.l_start = lock.l_len = 0L;
25846 SimulateIOErrorBenign(1);
25847 SimulateIOError( h=(-1) )
25848 SimulateIOErrorBenign(0);
25849 if( unixFileLock(pFile, &lock)==0 ){
25850 pInode->eFileLock = NO_LOCK;
25851 }else{
25852 rc = SQLITE_IOERR_UNLOCK;
25853 pFile->lastErrno = errno;
25854 pInode->eFileLock = NO_LOCK;
25855 pFile->eFileLock = NO_LOCK;
25859 /* Decrement the count of locks against this same file. When the
25860 ** count reaches zero, close any other file descriptors whose close
25861 ** was deferred because of outstanding locks.
25863 pInode->nLock--;
25864 assert( pInode->nLock>=0 );
25865 if( pInode->nLock==0 ){
25866 closePendingFds(pFile);
25870 end_unlock:
25871 unixLeaveMutex();
25872 if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock;
25873 return rc;
25877 ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
25878 ** must be either NO_LOCK or SHARED_LOCK.
25880 ** If the locking level of the file descriptor is already at or below
25881 ** the requested locking level, this routine is a no-op.
25883 static int unixUnlock(sqlite3_file *id, int eFileLock){
25884 return posixUnlock(id, eFileLock, 0);
25888 ** This function performs the parts of the "close file" operation
25889 ** common to all locking schemes. It closes the directory and file
25890 ** handles, if they are valid, and sets all fields of the unixFile
25891 ** structure to 0.
25893 ** It is *not* necessary to hold the mutex when this routine is called,
25894 ** even on VxWorks. A mutex will be acquired on VxWorks by the
25895 ** vxworksReleaseFileId() routine.
25897 static int closeUnixFile(sqlite3_file *id){
25898 unixFile *pFile = (unixFile*)id;
25899 if( pFile->h>=0 ){
25900 robust_close(pFile, pFile->h, __LINE__);
25901 pFile->h = -1;
25903 #if OS_VXWORKS
25904 if( pFile->pId ){
25905 if( pFile->isDelete ){
25906 osUnlink(pFile->pId->zCanonicalName);
25908 vxworksReleaseFileId(pFile->pId);
25909 pFile->pId = 0;
25911 #endif
25912 OSTRACE(("CLOSE %-3d\n", pFile->h));
25913 OpenCounter(-1);
25914 sqlite3_free(pFile->pUnused);
25915 memset(pFile, 0, sizeof(unixFile));
25916 return SQLITE_OK;
25920 ** Close a file.
25922 static int unixClose(sqlite3_file *id){
25923 int rc = SQLITE_OK;
25924 unixFile *pFile = (unixFile *)id;
25925 unixUnlock(id, NO_LOCK);
25926 unixEnterMutex();
25928 /* unixFile.pInode is always valid here. Otherwise, a different close
25929 ** routine (e.g. nolockClose()) would be called instead.
25931 assert( pFile->pInode->nLock>0 || pFile->pInode->bProcessLock==0 );
25932 if( ALWAYS(pFile->pInode) && pFile->pInode->nLock ){
25933 /* If there are outstanding locks, do not actually close the file just
25934 ** yet because that would clear those locks. Instead, add the file
25935 ** descriptor to pInode->pUnused list. It will be automatically closed
25936 ** when the last lock is cleared.
25938 setPendingFd(pFile);
25940 releaseInodeInfo(pFile);
25941 rc = closeUnixFile(id);
25942 unixLeaveMutex();
25943 return rc;
25946 /************** End of the posix advisory lock implementation *****************
25947 ******************************************************************************/
25949 /******************************************************************************
25950 ****************************** No-op Locking **********************************
25952 ** Of the various locking implementations available, this is by far the
25953 ** simplest: locking is ignored. No attempt is made to lock the database
25954 ** file for reading or writing.
25956 ** This locking mode is appropriate for use on read-only databases
25957 ** (ex: databases that are burned into CD-ROM, for example.) It can
25958 ** also be used if the application employs some external mechanism to
25959 ** prevent simultaneous access of the same database by two or more
25960 ** database connections. But there is a serious risk of database
25961 ** corruption if this locking mode is used in situations where multiple
25962 ** database connections are accessing the same database file at the same
25963 ** time and one or more of those connections are writing.
25966 static int nolockCheckReservedLock(sqlite3_file *NotUsed, int *pResOut){
25967 UNUSED_PARAMETER(NotUsed);
25968 *pResOut = 0;
25969 return SQLITE_OK;
25971 static int nolockLock(sqlite3_file *NotUsed, int NotUsed2){
25972 UNUSED_PARAMETER2(NotUsed, NotUsed2);
25973 return SQLITE_OK;
25975 static int nolockUnlock(sqlite3_file *NotUsed, int NotUsed2){
25976 UNUSED_PARAMETER2(NotUsed, NotUsed2);
25977 return SQLITE_OK;
25981 ** Close the file.
25983 static int nolockClose(sqlite3_file *id) {
25984 return closeUnixFile(id);
25987 /******************* End of the no-op lock implementation *********************
25988 ******************************************************************************/
25990 /******************************************************************************
25991 ************************* Begin dot-file Locking ******************************
25993 ** The dotfile locking implementation uses the existance of separate lock
25994 ** files in order to control access to the database. This works on just
25995 ** about every filesystem imaginable. But there are serious downsides:
25997 ** (1) There is zero concurrency. A single reader blocks all other
25998 ** connections from reading or writing the database.
26000 ** (2) An application crash or power loss can leave stale lock files
26001 ** sitting around that need to be cleared manually.
26003 ** Nevertheless, a dotlock is an appropriate locking mode for use if no
26004 ** other locking strategy is available.
26006 ** Dotfile locking works by creating a file in the same directory as the
26007 ** database and with the same name but with a ".lock" extension added.
26008 ** The existance of a lock file implies an EXCLUSIVE lock. All other lock
26009 ** types (SHARED, RESERVED, PENDING) are mapped into EXCLUSIVE.
26013 ** The file suffix added to the data base filename in order to create the
26014 ** lock file.
26016 #define DOTLOCK_SUFFIX ".lock"
26019 ** This routine checks if there is a RESERVED lock held on the specified
26020 ** file by this or any other process. If such a lock is held, set *pResOut
26021 ** to a non-zero value otherwise *pResOut is set to zero. The return value
26022 ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
26024 ** In dotfile locking, either a lock exists or it does not. So in this
26025 ** variation of CheckReservedLock(), *pResOut is set to true if any lock
26026 ** is held on the file and false if the file is unlocked.
26028 static int dotlockCheckReservedLock(sqlite3_file *id, int *pResOut) {
26029 int rc = SQLITE_OK;
26030 int reserved = 0;
26031 unixFile *pFile = (unixFile*)id;
26033 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
26035 assert( pFile );
26037 /* Check if a thread in this process holds such a lock */
26038 if( pFile->eFileLock>SHARED_LOCK ){
26039 /* Either this connection or some other connection in the same process
26040 ** holds a lock on the file. No need to check further. */
26041 reserved = 1;
26042 }else{
26043 /* The lock is held if and only if the lockfile exists */
26044 const char *zLockFile = (const char*)pFile->lockingContext;
26045 reserved = osAccess(zLockFile, 0)==0;
26047 OSTRACE(("TEST WR-LOCK %d %d %d (dotlock)\n", pFile->h, rc, reserved));
26048 *pResOut = reserved;
26049 return rc;
26053 ** Lock the file with the lock specified by parameter eFileLock - one
26054 ** of the following:
26056 ** (1) SHARED_LOCK
26057 ** (2) RESERVED_LOCK
26058 ** (3) PENDING_LOCK
26059 ** (4) EXCLUSIVE_LOCK
26061 ** Sometimes when requesting one lock state, additional lock states
26062 ** are inserted in between. The locking might fail on one of the later
26063 ** transitions leaving the lock state different from what it started but
26064 ** still short of its goal. The following chart shows the allowed
26065 ** transitions and the inserted intermediate states:
26067 ** UNLOCKED -> SHARED
26068 ** SHARED -> RESERVED
26069 ** SHARED -> (PENDING) -> EXCLUSIVE
26070 ** RESERVED -> (PENDING) -> EXCLUSIVE
26071 ** PENDING -> EXCLUSIVE
26073 ** This routine will only increase a lock. Use the sqlite3OsUnlock()
26074 ** routine to lower a locking level.
26076 ** With dotfile locking, we really only support state (4): EXCLUSIVE.
26077 ** But we track the other locking levels internally.
26079 static int dotlockLock(sqlite3_file *id, int eFileLock) {
26080 unixFile *pFile = (unixFile*)id;
26081 int fd;
26082 char *zLockFile = (char *)pFile->lockingContext;
26083 int rc = SQLITE_OK;
26086 /* If we have any lock, then the lock file already exists. All we have
26087 ** to do is adjust our internal record of the lock level.
26089 if( pFile->eFileLock > NO_LOCK ){
26090 pFile->eFileLock = eFileLock;
26091 #if !OS_VXWORKS
26092 /* Always update the timestamp on the old file */
26093 utimes(zLockFile, NULL);
26094 #endif
26095 return SQLITE_OK;
26098 /* grab an exclusive lock */
26099 fd = robust_open(zLockFile,O_RDONLY|O_CREAT|O_EXCL,0600);
26100 if( fd<0 ){
26101 /* failed to open/create the file, someone else may have stolen the lock */
26102 int tErrno = errno;
26103 if( EEXIST == tErrno ){
26104 rc = SQLITE_BUSY;
26105 } else {
26106 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
26107 if( IS_LOCK_ERROR(rc) ){
26108 pFile->lastErrno = tErrno;
26111 return rc;
26113 robust_close(pFile, fd, __LINE__);
26115 /* got it, set the type and return ok */
26116 pFile->eFileLock = eFileLock;
26117 return rc;
26121 ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
26122 ** must be either NO_LOCK or SHARED_LOCK.
26124 ** If the locking level of the file descriptor is already at or below
26125 ** the requested locking level, this routine is a no-op.
26127 ** When the locking level reaches NO_LOCK, delete the lock file.
26129 static int dotlockUnlock(sqlite3_file *id, int eFileLock) {
26130 unixFile *pFile = (unixFile*)id;
26131 char *zLockFile = (char *)pFile->lockingContext;
26133 assert( pFile );
26134 OSTRACE(("UNLOCK %d %d was %d pid=%d (dotlock)\n", pFile->h, eFileLock,
26135 pFile->eFileLock, getpid()));
26136 assert( eFileLock<=SHARED_LOCK );
26138 /* no-op if possible */
26139 if( pFile->eFileLock==eFileLock ){
26140 return SQLITE_OK;
26143 /* To downgrade to shared, simply update our internal notion of the
26144 ** lock state. No need to mess with the file on disk.
26146 if( eFileLock==SHARED_LOCK ){
26147 pFile->eFileLock = SHARED_LOCK;
26148 return SQLITE_OK;
26151 /* To fully unlock the database, delete the lock file */
26152 assert( eFileLock==NO_LOCK );
26153 if( osUnlink(zLockFile) ){
26154 int rc = 0;
26155 int tErrno = errno;
26156 if( ENOENT != tErrno ){
26157 rc = SQLITE_IOERR_UNLOCK;
26159 if( IS_LOCK_ERROR(rc) ){
26160 pFile->lastErrno = tErrno;
26162 return rc;
26164 pFile->eFileLock = NO_LOCK;
26165 return SQLITE_OK;
26169 ** Close a file. Make sure the lock has been released before closing.
26171 static int dotlockClose(sqlite3_file *id) {
26172 int rc;
26173 if( id ){
26174 unixFile *pFile = (unixFile*)id;
26175 dotlockUnlock(id, NO_LOCK);
26176 sqlite3_free(pFile->lockingContext);
26178 rc = closeUnixFile(id);
26179 return rc;
26181 /****************** End of the dot-file lock implementation *******************
26182 ******************************************************************************/
26184 /******************************************************************************
26185 ************************** Begin flock Locking ********************************
26187 ** Use the flock() system call to do file locking.
26189 ** flock() locking is like dot-file locking in that the various
26190 ** fine-grain locking levels supported by SQLite are collapsed into
26191 ** a single exclusive lock. In other words, SHARED, RESERVED, and
26192 ** PENDING locks are the same thing as an EXCLUSIVE lock. SQLite
26193 ** still works when you do this, but concurrency is reduced since
26194 ** only a single process can be reading the database at a time.
26196 ** Omit this section if SQLITE_ENABLE_LOCKING_STYLE is turned off or if
26197 ** compiling for VXWORKS.
26199 #if SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS
26202 ** Retry flock() calls that fail with EINTR
26204 #ifdef EINTR
26205 static int robust_flock(int fd, int op){
26206 int rc;
26207 do{ rc = flock(fd,op); }while( rc<0 && errno==EINTR );
26208 return rc;
26210 #else
26211 # define robust_flock(a,b) flock(a,b)
26212 #endif
26216 ** This routine checks if there is a RESERVED lock held on the specified
26217 ** file by this or any other process. If such a lock is held, set *pResOut
26218 ** to a non-zero value otherwise *pResOut is set to zero. The return value
26219 ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
26221 static int flockCheckReservedLock(sqlite3_file *id, int *pResOut){
26222 int rc = SQLITE_OK;
26223 int reserved = 0;
26224 unixFile *pFile = (unixFile*)id;
26226 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
26228 assert( pFile );
26230 /* Check if a thread in this process holds such a lock */
26231 if( pFile->eFileLock>SHARED_LOCK ){
26232 reserved = 1;
26235 /* Otherwise see if some other process holds it. */
26236 if( !reserved ){
26237 /* attempt to get the lock */
26238 int lrc = robust_flock(pFile->h, LOCK_EX | LOCK_NB);
26239 if( !lrc ){
26240 /* got the lock, unlock it */
26241 lrc = robust_flock(pFile->h, LOCK_UN);
26242 if ( lrc ) {
26243 int tErrno = errno;
26244 /* unlock failed with an error */
26245 lrc = SQLITE_IOERR_UNLOCK;
26246 if( IS_LOCK_ERROR(lrc) ){
26247 pFile->lastErrno = tErrno;
26248 rc = lrc;
26251 } else {
26252 int tErrno = errno;
26253 reserved = 1;
26254 /* someone else might have it reserved */
26255 lrc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
26256 if( IS_LOCK_ERROR(lrc) ){
26257 pFile->lastErrno = tErrno;
26258 rc = lrc;
26262 OSTRACE(("TEST WR-LOCK %d %d %d (flock)\n", pFile->h, rc, reserved));
26264 #ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
26265 if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
26266 rc = SQLITE_OK;
26267 reserved=1;
26269 #endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
26270 *pResOut = reserved;
26271 return rc;
26275 ** Lock the file with the lock specified by parameter eFileLock - one
26276 ** of the following:
26278 ** (1) SHARED_LOCK
26279 ** (2) RESERVED_LOCK
26280 ** (3) PENDING_LOCK
26281 ** (4) EXCLUSIVE_LOCK
26283 ** Sometimes when requesting one lock state, additional lock states
26284 ** are inserted in between. The locking might fail on one of the later
26285 ** transitions leaving the lock state different from what it started but
26286 ** still short of its goal. The following chart shows the allowed
26287 ** transitions and the inserted intermediate states:
26289 ** UNLOCKED -> SHARED
26290 ** SHARED -> RESERVED
26291 ** SHARED -> (PENDING) -> EXCLUSIVE
26292 ** RESERVED -> (PENDING) -> EXCLUSIVE
26293 ** PENDING -> EXCLUSIVE
26295 ** flock() only really support EXCLUSIVE locks. We track intermediate
26296 ** lock states in the sqlite3_file structure, but all locks SHARED or
26297 ** above are really EXCLUSIVE locks and exclude all other processes from
26298 ** access the file.
26300 ** This routine will only increase a lock. Use the sqlite3OsUnlock()
26301 ** routine to lower a locking level.
26303 static int flockLock(sqlite3_file *id, int eFileLock) {
26304 int rc = SQLITE_OK;
26305 unixFile *pFile = (unixFile*)id;
26307 assert( pFile );
26309 /* if we already have a lock, it is exclusive.
26310 ** Just adjust level and punt on outta here. */
26311 if (pFile->eFileLock > NO_LOCK) {
26312 pFile->eFileLock = eFileLock;
26313 return SQLITE_OK;
26316 /* grab an exclusive lock */
26318 if (robust_flock(pFile->h, LOCK_EX | LOCK_NB)) {
26319 int tErrno = errno;
26320 /* didn't get, must be busy */
26321 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
26322 if( IS_LOCK_ERROR(rc) ){
26323 pFile->lastErrno = tErrno;
26325 } else {
26326 /* got it, set the type and return ok */
26327 pFile->eFileLock = eFileLock;
26329 OSTRACE(("LOCK %d %s %s (flock)\n", pFile->h, azFileLock(eFileLock),
26330 rc==SQLITE_OK ? "ok" : "failed"));
26331 #ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
26332 if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
26333 rc = SQLITE_BUSY;
26335 #endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
26336 return rc;
26341 ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
26342 ** must be either NO_LOCK or SHARED_LOCK.
26344 ** If the locking level of the file descriptor is already at or below
26345 ** the requested locking level, this routine is a no-op.
26347 static int flockUnlock(sqlite3_file *id, int eFileLock) {
26348 unixFile *pFile = (unixFile*)id;
26350 assert( pFile );
26351 OSTRACE(("UNLOCK %d %d was %d pid=%d (flock)\n", pFile->h, eFileLock,
26352 pFile->eFileLock, getpid()));
26353 assert( eFileLock<=SHARED_LOCK );
26355 /* no-op if possible */
26356 if( pFile->eFileLock==eFileLock ){
26357 return SQLITE_OK;
26360 /* shared can just be set because we always have an exclusive */
26361 if (eFileLock==SHARED_LOCK) {
26362 pFile->eFileLock = eFileLock;
26363 return SQLITE_OK;
26366 /* no, really, unlock. */
26367 if( robust_flock(pFile->h, LOCK_UN) ){
26368 #ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
26369 return SQLITE_OK;
26370 #endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
26371 return SQLITE_IOERR_UNLOCK;
26372 }else{
26373 pFile->eFileLock = NO_LOCK;
26374 return SQLITE_OK;
26379 ** Close a file.
26381 static int flockClose(sqlite3_file *id) {
26382 if( id ){
26383 flockUnlock(id, NO_LOCK);
26385 return closeUnixFile(id);
26388 #endif /* SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORK */
26390 /******************* End of the flock lock implementation *********************
26391 ******************************************************************************/
26393 /******************************************************************************
26394 ************************ Begin Named Semaphore Locking ************************
26396 ** Named semaphore locking is only supported on VxWorks.
26398 ** Semaphore locking is like dot-lock and flock in that it really only
26399 ** supports EXCLUSIVE locking. Only a single process can read or write
26400 ** the database file at a time. This reduces potential concurrency, but
26401 ** makes the lock implementation much easier.
26403 #if OS_VXWORKS
26406 ** This routine checks if there is a RESERVED lock held on the specified
26407 ** file by this or any other process. If such a lock is held, set *pResOut
26408 ** to a non-zero value otherwise *pResOut is set to zero. The return value
26409 ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
26411 static int semCheckReservedLock(sqlite3_file *id, int *pResOut) {
26412 int rc = SQLITE_OK;
26413 int reserved = 0;
26414 unixFile *pFile = (unixFile*)id;
26416 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
26418 assert( pFile );
26420 /* Check if a thread in this process holds such a lock */
26421 if( pFile->eFileLock>SHARED_LOCK ){
26422 reserved = 1;
26425 /* Otherwise see if some other process holds it. */
26426 if( !reserved ){
26427 sem_t *pSem = pFile->pInode->pSem;
26428 struct stat statBuf;
26430 if( sem_trywait(pSem)==-1 ){
26431 int tErrno = errno;
26432 if( EAGAIN != tErrno ){
26433 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_CHECKRESERVEDLOCK);
26434 pFile->lastErrno = tErrno;
26435 } else {
26436 /* someone else has the lock when we are in NO_LOCK */
26437 reserved = (pFile->eFileLock < SHARED_LOCK);
26439 }else{
26440 /* we could have it if we want it */
26441 sem_post(pSem);
26444 OSTRACE(("TEST WR-LOCK %d %d %d (sem)\n", pFile->h, rc, reserved));
26446 *pResOut = reserved;
26447 return rc;
26451 ** Lock the file with the lock specified by parameter eFileLock - one
26452 ** of the following:
26454 ** (1) SHARED_LOCK
26455 ** (2) RESERVED_LOCK
26456 ** (3) PENDING_LOCK
26457 ** (4) EXCLUSIVE_LOCK
26459 ** Sometimes when requesting one lock state, additional lock states
26460 ** are inserted in between. The locking might fail on one of the later
26461 ** transitions leaving the lock state different from what it started but
26462 ** still short of its goal. The following chart shows the allowed
26463 ** transitions and the inserted intermediate states:
26465 ** UNLOCKED -> SHARED
26466 ** SHARED -> RESERVED
26467 ** SHARED -> (PENDING) -> EXCLUSIVE
26468 ** RESERVED -> (PENDING) -> EXCLUSIVE
26469 ** PENDING -> EXCLUSIVE
26471 ** Semaphore locks only really support EXCLUSIVE locks. We track intermediate
26472 ** lock states in the sqlite3_file structure, but all locks SHARED or
26473 ** above are really EXCLUSIVE locks and exclude all other processes from
26474 ** access the file.
26476 ** This routine will only increase a lock. Use the sqlite3OsUnlock()
26477 ** routine to lower a locking level.
26479 static int semLock(sqlite3_file *id, int eFileLock) {
26480 unixFile *pFile = (unixFile*)id;
26481 int fd;
26482 sem_t *pSem = pFile->pInode->pSem;
26483 int rc = SQLITE_OK;
26485 /* if we already have a lock, it is exclusive.
26486 ** Just adjust level and punt on outta here. */
26487 if (pFile->eFileLock > NO_LOCK) {
26488 pFile->eFileLock = eFileLock;
26489 rc = SQLITE_OK;
26490 goto sem_end_lock;
26493 /* lock semaphore now but bail out when already locked. */
26494 if( sem_trywait(pSem)==-1 ){
26495 rc = SQLITE_BUSY;
26496 goto sem_end_lock;
26499 /* got it, set the type and return ok */
26500 pFile->eFileLock = eFileLock;
26502 sem_end_lock:
26503 return rc;
26507 ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
26508 ** must be either NO_LOCK or SHARED_LOCK.
26510 ** If the locking level of the file descriptor is already at or below
26511 ** the requested locking level, this routine is a no-op.
26513 static int semUnlock(sqlite3_file *id, int eFileLock) {
26514 unixFile *pFile = (unixFile*)id;
26515 sem_t *pSem = pFile->pInode->pSem;
26517 assert( pFile );
26518 assert( pSem );
26519 OSTRACE(("UNLOCK %d %d was %d pid=%d (sem)\n", pFile->h, eFileLock,
26520 pFile->eFileLock, getpid()));
26521 assert( eFileLock<=SHARED_LOCK );
26523 /* no-op if possible */
26524 if( pFile->eFileLock==eFileLock ){
26525 return SQLITE_OK;
26528 /* shared can just be set because we always have an exclusive */
26529 if (eFileLock==SHARED_LOCK) {
26530 pFile->eFileLock = eFileLock;
26531 return SQLITE_OK;
26534 /* no, really unlock. */
26535 if ( sem_post(pSem)==-1 ) {
26536 int rc, tErrno = errno;
26537 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
26538 if( IS_LOCK_ERROR(rc) ){
26539 pFile->lastErrno = tErrno;
26541 return rc;
26543 pFile->eFileLock = NO_LOCK;
26544 return SQLITE_OK;
26548 ** Close a file.
26550 static int semClose(sqlite3_file *id) {
26551 if( id ){
26552 unixFile *pFile = (unixFile*)id;
26553 semUnlock(id, NO_LOCK);
26554 assert( pFile );
26555 unixEnterMutex();
26556 releaseInodeInfo(pFile);
26557 unixLeaveMutex();
26558 closeUnixFile(id);
26560 return SQLITE_OK;
26563 #endif /* OS_VXWORKS */
26565 ** Named semaphore locking is only available on VxWorks.
26567 *************** End of the named semaphore lock implementation ****************
26568 ******************************************************************************/
26571 /******************************************************************************
26572 *************************** Begin AFP Locking *********************************
26574 ** AFP is the Apple Filing Protocol. AFP is a network filesystem found
26575 ** on Apple Macintosh computers - both OS9 and OSX.
26577 ** Third-party implementations of AFP are available. But this code here
26578 ** only works on OSX.
26581 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
26583 ** The afpLockingContext structure contains all afp lock specific state
26585 typedef struct afpLockingContext afpLockingContext;
26586 struct afpLockingContext {
26587 int reserved;
26588 const char *dbPath; /* Name of the open file */
26591 struct ByteRangeLockPB2
26593 unsigned long long offset; /* offset to first byte to lock */
26594 unsigned long long length; /* nbr of bytes to lock */
26595 unsigned long long retRangeStart; /* nbr of 1st byte locked if successful */
26596 unsigned char unLockFlag; /* 1 = unlock, 0 = lock */
26597 unsigned char startEndFlag; /* 1=rel to end of fork, 0=rel to start */
26598 int fd; /* file desc to assoc this lock with */
26601 #define afpfsByteRangeLock2FSCTL _IOWR('z', 23, struct ByteRangeLockPB2)
26604 ** This is a utility for setting or clearing a bit-range lock on an
26605 ** AFP filesystem.
26607 ** Return SQLITE_OK on success, SQLITE_BUSY on failure.
26609 static int afpSetLock(
26610 const char *path, /* Name of the file to be locked or unlocked */
26611 unixFile *pFile, /* Open file descriptor on path */
26612 unsigned long long offset, /* First byte to be locked */
26613 unsigned long long length, /* Number of bytes to lock */
26614 int setLockFlag /* True to set lock. False to clear lock */
26616 struct ByteRangeLockPB2 pb;
26617 int err;
26619 pb.unLockFlag = setLockFlag ? 0 : 1;
26620 pb.startEndFlag = 0;
26621 pb.offset = offset;
26622 pb.length = length;
26623 pb.fd = pFile->h;
26625 OSTRACE(("AFPSETLOCK [%s] for %d%s in range %llx:%llx\n",
26626 (setLockFlag?"ON":"OFF"), pFile->h, (pb.fd==-1?"[testval-1]":""),
26627 offset, length));
26628 err = fsctl(path, afpfsByteRangeLock2FSCTL, &pb, 0);
26629 if ( err==-1 ) {
26630 int rc;
26631 int tErrno = errno;
26632 OSTRACE(("AFPSETLOCK failed to fsctl() '%s' %d %s\n",
26633 path, tErrno, strerror(tErrno)));
26634 #ifdef SQLITE_IGNORE_AFP_LOCK_ERRORS
26635 rc = SQLITE_BUSY;
26636 #else
26637 rc = sqliteErrorFromPosixError(tErrno,
26638 setLockFlag ? SQLITE_IOERR_LOCK : SQLITE_IOERR_UNLOCK);
26639 #endif /* SQLITE_IGNORE_AFP_LOCK_ERRORS */
26640 if( IS_LOCK_ERROR(rc) ){
26641 pFile->lastErrno = tErrno;
26643 return rc;
26644 } else {
26645 return SQLITE_OK;
26650 ** This routine checks if there is a RESERVED lock held on the specified
26651 ** file by this or any other process. If such a lock is held, set *pResOut
26652 ** to a non-zero value otherwise *pResOut is set to zero. The return value
26653 ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
26655 static int afpCheckReservedLock(sqlite3_file *id, int *pResOut){
26656 int rc = SQLITE_OK;
26657 int reserved = 0;
26658 unixFile *pFile = (unixFile*)id;
26660 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
26662 assert( pFile );
26663 afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
26664 if( context->reserved ){
26665 *pResOut = 1;
26666 return SQLITE_OK;
26668 unixEnterMutex(); /* Because pFile->pInode is shared across threads */
26670 /* Check if a thread in this process holds such a lock */
26671 if( pFile->pInode->eFileLock>SHARED_LOCK ){
26672 reserved = 1;
26675 /* Otherwise see if some other process holds it.
26677 if( !reserved ){
26678 /* lock the RESERVED byte */
26679 int lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
26680 if( SQLITE_OK==lrc ){
26681 /* if we succeeded in taking the reserved lock, unlock it to restore
26682 ** the original state */
26683 lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
26684 } else {
26685 /* if we failed to get the lock then someone else must have it */
26686 reserved = 1;
26688 if( IS_LOCK_ERROR(lrc) ){
26689 rc=lrc;
26693 unixLeaveMutex();
26694 OSTRACE(("TEST WR-LOCK %d %d %d (afp)\n", pFile->h, rc, reserved));
26696 *pResOut = reserved;
26697 return rc;
26701 ** Lock the file with the lock specified by parameter eFileLock - one
26702 ** of the following:
26704 ** (1) SHARED_LOCK
26705 ** (2) RESERVED_LOCK
26706 ** (3) PENDING_LOCK
26707 ** (4) EXCLUSIVE_LOCK
26709 ** Sometimes when requesting one lock state, additional lock states
26710 ** are inserted in between. The locking might fail on one of the later
26711 ** transitions leaving the lock state different from what it started but
26712 ** still short of its goal. The following chart shows the allowed
26713 ** transitions and the inserted intermediate states:
26715 ** UNLOCKED -> SHARED
26716 ** SHARED -> RESERVED
26717 ** SHARED -> (PENDING) -> EXCLUSIVE
26718 ** RESERVED -> (PENDING) -> EXCLUSIVE
26719 ** PENDING -> EXCLUSIVE
26721 ** This routine will only increase a lock. Use the sqlite3OsUnlock()
26722 ** routine to lower a locking level.
26724 static int afpLock(sqlite3_file *id, int eFileLock){
26725 int rc = SQLITE_OK;
26726 unixFile *pFile = (unixFile*)id;
26727 unixInodeInfo *pInode = pFile->pInode;
26728 afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
26730 assert( pFile );
26731 OSTRACE(("LOCK %d %s was %s(%s,%d) pid=%d (afp)\n", pFile->h,
26732 azFileLock(eFileLock), azFileLock(pFile->eFileLock),
26733 azFileLock(pInode->eFileLock), pInode->nShared , getpid()));
26735 /* If there is already a lock of this type or more restrictive on the
26736 ** unixFile, do nothing. Don't use the afp_end_lock: exit path, as
26737 ** unixEnterMutex() hasn't been called yet.
26739 if( pFile->eFileLock>=eFileLock ){
26740 OSTRACE(("LOCK %d %s ok (already held) (afp)\n", pFile->h,
26741 azFileLock(eFileLock)));
26742 return SQLITE_OK;
26745 /* Make sure the locking sequence is correct
26746 ** (1) We never move from unlocked to anything higher than shared lock.
26747 ** (2) SQLite never explicitly requests a pendig lock.
26748 ** (3) A shared lock is always held when a reserve lock is requested.
26750 assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
26751 assert( eFileLock!=PENDING_LOCK );
26752 assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
26754 /* This mutex is needed because pFile->pInode is shared across threads
26756 unixEnterMutex();
26757 pInode = pFile->pInode;
26759 /* If some thread using this PID has a lock via a different unixFile*
26760 ** handle that precludes the requested lock, return BUSY.
26762 if( (pFile->eFileLock!=pInode->eFileLock &&
26763 (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
26765 rc = SQLITE_BUSY;
26766 goto afp_end_lock;
26769 /* If a SHARED lock is requested, and some thread using this PID already
26770 ** has a SHARED or RESERVED lock, then increment reference counts and
26771 ** return SQLITE_OK.
26773 if( eFileLock==SHARED_LOCK &&
26774 (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
26775 assert( eFileLock==SHARED_LOCK );
26776 assert( pFile->eFileLock==0 );
26777 assert( pInode->nShared>0 );
26778 pFile->eFileLock = SHARED_LOCK;
26779 pInode->nShared++;
26780 pInode->nLock++;
26781 goto afp_end_lock;
26784 /* A PENDING lock is needed before acquiring a SHARED lock and before
26785 ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
26786 ** be released.
26788 if( eFileLock==SHARED_LOCK
26789 || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
26791 int failed;
26792 failed = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 1);
26793 if (failed) {
26794 rc = failed;
26795 goto afp_end_lock;
26799 /* If control gets to this point, then actually go ahead and make
26800 ** operating system calls for the specified lock.
26802 if( eFileLock==SHARED_LOCK ){
26803 int lrc1, lrc2, lrc1Errno;
26804 long lk, mask;
26806 assert( pInode->nShared==0 );
26807 assert( pInode->eFileLock==0 );
26809 mask = (sizeof(long)==8) ? LARGEST_INT64 : 0x7fffffff;
26810 /* Now get the read-lock SHARED_LOCK */
26811 /* note that the quality of the randomness doesn't matter that much */
26812 lk = random();
26813 pInode->sharedByte = (lk & mask)%(SHARED_SIZE - 1);
26814 lrc1 = afpSetLock(context->dbPath, pFile,
26815 SHARED_FIRST+pInode->sharedByte, 1, 1);
26816 if( IS_LOCK_ERROR(lrc1) ){
26817 lrc1Errno = pFile->lastErrno;
26819 /* Drop the temporary PENDING lock */
26820 lrc2 = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
26822 if( IS_LOCK_ERROR(lrc1) ) {
26823 pFile->lastErrno = lrc1Errno;
26824 rc = lrc1;
26825 goto afp_end_lock;
26826 } else if( IS_LOCK_ERROR(lrc2) ){
26827 rc = lrc2;
26828 goto afp_end_lock;
26829 } else if( lrc1 != SQLITE_OK ) {
26830 rc = lrc1;
26831 } else {
26832 pFile->eFileLock = SHARED_LOCK;
26833 pInode->nLock++;
26834 pInode->nShared = 1;
26836 }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
26837 /* We are trying for an exclusive lock but another thread in this
26838 ** same process is still holding a shared lock. */
26839 rc = SQLITE_BUSY;
26840 }else{
26841 /* The request was for a RESERVED or EXCLUSIVE lock. It is
26842 ** assumed that there is a SHARED or greater lock on the file
26843 ** already.
26845 int failed = 0;
26846 assert( 0!=pFile->eFileLock );
26847 if (eFileLock >= RESERVED_LOCK && pFile->eFileLock < RESERVED_LOCK) {
26848 /* Acquire a RESERVED lock */
26849 failed = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
26850 if( !failed ){
26851 context->reserved = 1;
26854 if (!failed && eFileLock == EXCLUSIVE_LOCK) {
26855 /* Acquire an EXCLUSIVE lock */
26857 /* Remove the shared lock before trying the range. we'll need to
26858 ** reestablish the shared lock if we can't get the afpUnlock
26860 if( !(failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST +
26861 pInode->sharedByte, 1, 0)) ){
26862 int failed2 = SQLITE_OK;
26863 /* now attemmpt to get the exclusive lock range */
26864 failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST,
26865 SHARED_SIZE, 1);
26866 if( failed && (failed2 = afpSetLock(context->dbPath, pFile,
26867 SHARED_FIRST + pInode->sharedByte, 1, 1)) ){
26868 /* Can't reestablish the shared lock. Sqlite can't deal, this is
26869 ** a critical I/O error
26871 rc = ((failed & SQLITE_IOERR) == SQLITE_IOERR) ? failed2 :
26872 SQLITE_IOERR_LOCK;
26873 goto afp_end_lock;
26875 }else{
26876 rc = failed;
26879 if( failed ){
26880 rc = failed;
26884 if( rc==SQLITE_OK ){
26885 pFile->eFileLock = eFileLock;
26886 pInode->eFileLock = eFileLock;
26887 }else if( eFileLock==EXCLUSIVE_LOCK ){
26888 pFile->eFileLock = PENDING_LOCK;
26889 pInode->eFileLock = PENDING_LOCK;
26892 afp_end_lock:
26893 unixLeaveMutex();
26894 OSTRACE(("LOCK %d %s %s (afp)\n", pFile->h, azFileLock(eFileLock),
26895 rc==SQLITE_OK ? "ok" : "failed"));
26896 return rc;
26900 ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
26901 ** must be either NO_LOCK or SHARED_LOCK.
26903 ** If the locking level of the file descriptor is already at or below
26904 ** the requested locking level, this routine is a no-op.
26906 static int afpUnlock(sqlite3_file *id, int eFileLock) {
26907 int rc = SQLITE_OK;
26908 unixFile *pFile = (unixFile*)id;
26909 unixInodeInfo *pInode;
26910 afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
26911 int skipShared = 0;
26912 #ifdef SQLITE_TEST
26913 int h = pFile->h;
26914 #endif
26916 assert( pFile );
26917 OSTRACE(("UNLOCK %d %d was %d(%d,%d) pid=%d (afp)\n", pFile->h, eFileLock,
26918 pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
26919 getpid()));
26921 assert( eFileLock<=SHARED_LOCK );
26922 if( pFile->eFileLock<=eFileLock ){
26923 return SQLITE_OK;
26925 unixEnterMutex();
26926 pInode = pFile->pInode;
26927 assert( pInode->nShared!=0 );
26928 if( pFile->eFileLock>SHARED_LOCK ){
26929 assert( pInode->eFileLock==pFile->eFileLock );
26930 SimulateIOErrorBenign(1);
26931 SimulateIOError( h=(-1) )
26932 SimulateIOErrorBenign(0);
26934 #ifndef NDEBUG
26935 /* When reducing a lock such that other processes can start
26936 ** reading the database file again, make sure that the
26937 ** transaction counter was updated if any part of the database
26938 ** file changed. If the transaction counter is not updated,
26939 ** other connections to the same file might not realize that
26940 ** the file has changed and hence might not know to flush their
26941 ** cache. The use of a stale cache can lead to database corruption.
26943 assert( pFile->inNormalWrite==0
26944 || pFile->dbUpdate==0
26945 || pFile->transCntrChng==1 );
26946 pFile->inNormalWrite = 0;
26947 #endif
26949 if( pFile->eFileLock==EXCLUSIVE_LOCK ){
26950 rc = afpSetLock(context->dbPath, pFile, SHARED_FIRST, SHARED_SIZE, 0);
26951 if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1) ){
26952 /* only re-establish the shared lock if necessary */
26953 int sharedLockByte = SHARED_FIRST+pInode->sharedByte;
26954 rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 1);
26955 } else {
26956 skipShared = 1;
26959 if( rc==SQLITE_OK && pFile->eFileLock>=PENDING_LOCK ){
26960 rc = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
26962 if( rc==SQLITE_OK && pFile->eFileLock>=RESERVED_LOCK && context->reserved ){
26963 rc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
26964 if( !rc ){
26965 context->reserved = 0;
26968 if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1)){
26969 pInode->eFileLock = SHARED_LOCK;
26972 if( rc==SQLITE_OK && eFileLock==NO_LOCK ){
26974 /* Decrement the shared lock counter. Release the lock using an
26975 ** OS call only when all threads in this same process have released
26976 ** the lock.
26978 unsigned long long sharedLockByte = SHARED_FIRST+pInode->sharedByte;
26979 pInode->nShared--;
26980 if( pInode->nShared==0 ){
26981 SimulateIOErrorBenign(1);
26982 SimulateIOError( h=(-1) )
26983 SimulateIOErrorBenign(0);
26984 if( !skipShared ){
26985 rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 0);
26987 if( !rc ){
26988 pInode->eFileLock = NO_LOCK;
26989 pFile->eFileLock = NO_LOCK;
26992 if( rc==SQLITE_OK ){
26993 pInode->nLock--;
26994 assert( pInode->nLock>=0 );
26995 if( pInode->nLock==0 ){
26996 closePendingFds(pFile);
27001 unixLeaveMutex();
27002 if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock;
27003 return rc;
27007 ** Close a file & cleanup AFP specific locking context
27009 static int afpClose(sqlite3_file *id) {
27010 int rc = SQLITE_OK;
27011 if( id ){
27012 unixFile *pFile = (unixFile*)id;
27013 afpUnlock(id, NO_LOCK);
27014 unixEnterMutex();
27015 if( pFile->pInode && pFile->pInode->nLock ){
27016 /* If there are outstanding locks, do not actually close the file just
27017 ** yet because that would clear those locks. Instead, add the file
27018 ** descriptor to pInode->aPending. It will be automatically closed when
27019 ** the last lock is cleared.
27021 setPendingFd(pFile);
27023 releaseInodeInfo(pFile);
27024 sqlite3_free(pFile->lockingContext);
27025 rc = closeUnixFile(id);
27026 unixLeaveMutex();
27028 return rc;
27031 #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
27033 ** The code above is the AFP lock implementation. The code is specific
27034 ** to MacOSX and does not work on other unix platforms. No alternative
27035 ** is available. If you don't compile for a mac, then the "unix-afp"
27036 ** VFS is not available.
27038 ********************* End of the AFP lock implementation **********************
27039 ******************************************************************************/
27041 /******************************************************************************
27042 *************************** Begin NFS Locking ********************************/
27044 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
27046 ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
27047 ** must be either NO_LOCK or SHARED_LOCK.
27049 ** If the locking level of the file descriptor is already at or below
27050 ** the requested locking level, this routine is a no-op.
27052 static int nfsUnlock(sqlite3_file *id, int eFileLock){
27053 return posixUnlock(id, eFileLock, 1);
27056 #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
27058 ** The code above is the NFS lock implementation. The code is specific
27059 ** to MacOSX and does not work on other unix platforms. No alternative
27060 ** is available.
27062 ********************* End of the NFS lock implementation **********************
27063 ******************************************************************************/
27065 /******************************************************************************
27066 **************** Non-locking sqlite3_file methods *****************************
27068 ** The next division contains implementations for all methods of the
27069 ** sqlite3_file object other than the locking methods. The locking
27070 ** methods were defined in divisions above (one locking method per
27071 ** division). Those methods that are common to all locking modes
27072 ** are gather together into this division.
27076 ** Seek to the offset passed as the second argument, then read cnt
27077 ** bytes into pBuf. Return the number of bytes actually read.
27079 ** NB: If you define USE_PREAD or USE_PREAD64, then it might also
27080 ** be necessary to define _XOPEN_SOURCE to be 500. This varies from
27081 ** one system to another. Since SQLite does not define USE_PREAD
27082 ** any any form by default, we will not attempt to define _XOPEN_SOURCE.
27083 ** See tickets #2741 and #2681.
27085 ** To avoid stomping the errno value on a failed read the lastErrno value
27086 ** is set before returning.
27088 static int seekAndRead(unixFile *id, sqlite3_int64 offset, void *pBuf, int cnt){
27089 int got;
27090 #if (!defined(USE_PREAD) && !defined(USE_PREAD64))
27091 i64 newOffset;
27092 #endif
27093 TIMER_START;
27094 #if defined(USE_PREAD)
27095 do{ got = osPread(id->h, pBuf, cnt, offset); }while( got<0 && errno==EINTR );
27096 SimulateIOError( got = -1 );
27097 #elif defined(USE_PREAD64)
27098 do{ got = osPread64(id->h, pBuf, cnt, offset); }while( got<0 && errno==EINTR);
27099 SimulateIOError( got = -1 );
27100 #else
27101 newOffset = lseek(id->h, offset, SEEK_SET);
27102 SimulateIOError( newOffset-- );
27103 if( newOffset!=offset ){
27104 if( newOffset == -1 ){
27105 ((unixFile*)id)->lastErrno = errno;
27106 }else{
27107 ((unixFile*)id)->lastErrno = 0;
27109 return -1;
27111 do{ got = osRead(id->h, pBuf, cnt); }while( got<0 && errno==EINTR );
27112 #endif
27113 TIMER_END;
27114 if( got<0 ){
27115 ((unixFile*)id)->lastErrno = errno;
27117 OSTRACE(("READ %-3d %5d %7lld %llu\n", id->h, got, offset, TIMER_ELAPSED));
27118 return got;
27122 ** Read data from a file into a buffer. Return SQLITE_OK if all
27123 ** bytes were read successfully and SQLITE_IOERR if anything goes
27124 ** wrong.
27126 static int unixRead(
27127 sqlite3_file *id,
27128 void *pBuf,
27129 int amt,
27130 sqlite3_int64 offset
27132 unixFile *pFile = (unixFile *)id;
27133 int got;
27134 assert( id );
27136 /* If this is a database file (not a journal, master-journal or temp
27137 ** file), the bytes in the locking range should never be read or written. */
27138 #if 0
27139 assert( pFile->pUnused==0
27140 || offset>=PENDING_BYTE+512
27141 || offset+amt<=PENDING_BYTE
27143 #endif
27145 got = seekAndRead(pFile, offset, pBuf, amt);
27146 if( got==amt ){
27147 return SQLITE_OK;
27148 }else if( got<0 ){
27149 /* lastErrno set by seekAndRead */
27150 return SQLITE_IOERR_READ;
27151 }else{
27152 pFile->lastErrno = 0; /* not a system error */
27153 /* Unread parts of the buffer must be zero-filled */
27154 memset(&((char*)pBuf)[got], 0, amt-got);
27155 return SQLITE_IOERR_SHORT_READ;
27160 ** Seek to the offset in id->offset then read cnt bytes into pBuf.
27161 ** Return the number of bytes actually read. Update the offset.
27163 ** To avoid stomping the errno value on a failed write the lastErrno value
27164 ** is set before returning.
27166 static int seekAndWrite(unixFile *id, i64 offset, const void *pBuf, int cnt){
27167 int got;
27168 #if (!defined(USE_PREAD) && !defined(USE_PREAD64))
27169 i64 newOffset;
27170 #endif
27171 TIMER_START;
27172 #if defined(USE_PREAD)
27173 do{ got = osPwrite(id->h, pBuf, cnt, offset); }while( got<0 && errno==EINTR );
27174 #elif defined(USE_PREAD64)
27175 do{ got = osPwrite64(id->h, pBuf, cnt, offset);}while( got<0 && errno==EINTR);
27176 #else
27177 newOffset = lseek(id->h, offset, SEEK_SET);
27178 SimulateIOError( newOffset-- );
27179 if( newOffset!=offset ){
27180 if( newOffset == -1 ){
27181 ((unixFile*)id)->lastErrno = errno;
27182 }else{
27183 ((unixFile*)id)->lastErrno = 0;
27185 return -1;
27187 do{ got = osWrite(id->h, pBuf, cnt); }while( got<0 && errno==EINTR );
27188 #endif
27189 TIMER_END;
27190 if( got<0 ){
27191 ((unixFile*)id)->lastErrno = errno;
27194 OSTRACE(("WRITE %-3d %5d %7lld %llu\n", id->h, got, offset, TIMER_ELAPSED));
27195 return got;
27200 ** Write data from a buffer into a file. Return SQLITE_OK on success
27201 ** or some other error code on failure.
27203 static int unixWrite(
27204 sqlite3_file *id,
27205 const void *pBuf,
27206 int amt,
27207 sqlite3_int64 offset
27209 unixFile *pFile = (unixFile*)id;
27210 int wrote = 0;
27211 assert( id );
27212 assert( amt>0 );
27214 /* If this is a database file (not a journal, master-journal or temp
27215 ** file), the bytes in the locking range should never be read or written. */
27216 #if 0
27217 assert( pFile->pUnused==0
27218 || offset>=PENDING_BYTE+512
27219 || offset+amt<=PENDING_BYTE
27221 #endif
27223 #ifndef NDEBUG
27224 /* If we are doing a normal write to a database file (as opposed to
27225 ** doing a hot-journal rollback or a write to some file other than a
27226 ** normal database file) then record the fact that the database
27227 ** has changed. If the transaction counter is modified, record that
27228 ** fact too.
27230 if( pFile->inNormalWrite ){
27231 pFile->dbUpdate = 1; /* The database has been modified */
27232 if( offset<=24 && offset+amt>=27 ){
27233 int rc;
27234 char oldCntr[4];
27235 SimulateIOErrorBenign(1);
27236 rc = seekAndRead(pFile, 24, oldCntr, 4);
27237 SimulateIOErrorBenign(0);
27238 if( rc!=4 || memcmp(oldCntr, &((char*)pBuf)[24-offset], 4)!=0 ){
27239 pFile->transCntrChng = 1; /* The transaction counter has changed */
27243 #endif
27245 while( amt>0 && (wrote = seekAndWrite(pFile, offset, pBuf, amt))>0 ){
27246 amt -= wrote;
27247 offset += wrote;
27248 pBuf = &((char*)pBuf)[wrote];
27250 SimulateIOError(( wrote=(-1), amt=1 ));
27251 SimulateDiskfullError(( wrote=0, amt=1 ));
27253 if( amt>0 ){
27254 if( wrote<0 ){
27255 /* lastErrno set by seekAndWrite */
27256 return SQLITE_IOERR_WRITE;
27257 }else{
27258 pFile->lastErrno = 0; /* not a system error */
27259 return SQLITE_FULL;
27263 return SQLITE_OK;
27266 #ifdef SQLITE_TEST
27268 ** Count the number of fullsyncs and normal syncs. This is used to test
27269 ** that syncs and fullsyncs are occurring at the right times.
27271 SQLITE_API int sqlite3_sync_count = 0;
27272 SQLITE_API int sqlite3_fullsync_count = 0;
27273 #endif
27276 ** We do not trust systems to provide a working fdatasync(). Some do.
27277 ** Others do no. To be safe, we will stick with the (slower) fsync().
27278 ** If you know that your system does support fdatasync() correctly,
27279 ** then simply compile with -Dfdatasync=fdatasync
27281 #if !defined(fdatasync) && !defined(__linux__)
27282 # define fdatasync fsync
27283 #endif
27286 ** Define HAVE_FULLFSYNC to 0 or 1 depending on whether or not
27287 ** the F_FULLFSYNC macro is defined. F_FULLFSYNC is currently
27288 ** only available on Mac OS X. But that could change.
27290 #ifdef F_FULLFSYNC
27291 # define HAVE_FULLFSYNC 1
27292 #else
27293 # define HAVE_FULLFSYNC 0
27294 #endif
27298 ** The fsync() system call does not work as advertised on many
27299 ** unix systems. The following procedure is an attempt to make
27300 ** it work better.
27302 ** The SQLITE_NO_SYNC macro disables all fsync()s. This is useful
27303 ** for testing when we want to run through the test suite quickly.
27304 ** You are strongly advised *not* to deploy with SQLITE_NO_SYNC
27305 ** enabled, however, since with SQLITE_NO_SYNC enabled, an OS crash
27306 ** or power failure will likely corrupt the database file.
27308 ** SQLite sets the dataOnly flag if the size of the file is unchanged.
27309 ** The idea behind dataOnly is that it should only write the file content
27310 ** to disk, not the inode. We only set dataOnly if the file size is
27311 ** unchanged since the file size is part of the inode. However,
27312 ** Ted Ts'o tells us that fdatasync() will also write the inode if the
27313 ** file size has changed. The only real difference between fdatasync()
27314 ** and fsync(), Ted tells us, is that fdatasync() will not flush the
27315 ** inode if the mtime or owner or other inode attributes have changed.
27316 ** We only care about the file size, not the other file attributes, so
27317 ** as far as SQLite is concerned, an fdatasync() is always adequate.
27318 ** So, we always use fdatasync() if it is available, regardless of
27319 ** the value of the dataOnly flag.
27321 static int full_fsync(int fd, int fullSync, int dataOnly){
27322 int rc;
27324 /* The following "ifdef/elif/else/" block has the same structure as
27325 ** the one below. It is replicated here solely to avoid cluttering
27326 ** up the real code with the UNUSED_PARAMETER() macros.
27328 #ifdef SQLITE_NO_SYNC
27329 UNUSED_PARAMETER(fd);
27330 UNUSED_PARAMETER(fullSync);
27331 UNUSED_PARAMETER(dataOnly);
27332 #elif HAVE_FULLFSYNC
27333 UNUSED_PARAMETER(dataOnly);
27334 #else
27335 UNUSED_PARAMETER(fullSync);
27336 UNUSED_PARAMETER(dataOnly);
27337 #endif
27339 /* Record the number of times that we do a normal fsync() and
27340 ** FULLSYNC. This is used during testing to verify that this procedure
27341 ** gets called with the correct arguments.
27343 #ifdef SQLITE_TEST
27344 if( fullSync ) sqlite3_fullsync_count++;
27345 sqlite3_sync_count++;
27346 #endif
27348 /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
27349 ** no-op
27351 #ifdef SQLITE_NO_SYNC
27352 rc = SQLITE_OK;
27353 #elif HAVE_FULLFSYNC
27354 if( fullSync ){
27355 rc = osFcntl(fd, F_FULLFSYNC, 0);
27356 }else{
27357 rc = 1;
27359 /* If the FULLFSYNC failed, fall back to attempting an fsync().
27360 ** It shouldn't be possible for fullfsync to fail on the local
27361 ** file system (on OSX), so failure indicates that FULLFSYNC
27362 ** isn't supported for this file system. So, attempt an fsync
27363 ** and (for now) ignore the overhead of a superfluous fcntl call.
27364 ** It'd be better to detect fullfsync support once and avoid
27365 ** the fcntl call every time sync is called.
27367 if( rc ) rc = fsync(fd);
27369 #elif defined(__APPLE__)
27370 /* fdatasync() on HFS+ doesn't yet flush the file size if it changed correctly
27371 ** so currently we default to the macro that redefines fdatasync to fsync
27373 rc = fsync(fd);
27374 #else
27375 rc = fdatasync(fd);
27376 #if OS_VXWORKS
27377 if( rc==-1 && errno==ENOTSUP ){
27378 rc = fsync(fd);
27380 #endif /* OS_VXWORKS */
27381 #endif /* ifdef SQLITE_NO_SYNC elif HAVE_FULLFSYNC */
27383 if( OS_VXWORKS && rc!= -1 ){
27384 rc = 0;
27386 return rc;
27390 ** Open a file descriptor to the directory containing file zFilename.
27391 ** If successful, *pFd is set to the opened file descriptor and
27392 ** SQLITE_OK is returned. If an error occurs, either SQLITE_NOMEM
27393 ** or SQLITE_CANTOPEN is returned and *pFd is set to an undefined
27394 ** value.
27396 ** The directory file descriptor is used for only one thing - to
27397 ** fsync() a directory to make sure file creation and deletion events
27398 ** are flushed to disk. Such fsyncs are not needed on newer
27399 ** journaling filesystems, but are required on older filesystems.
27401 ** This routine can be overridden using the xSetSysCall interface.
27402 ** The ability to override this routine was added in support of the
27403 ** chromium sandbox. Opening a directory is a security risk (we are
27404 ** told) so making it overrideable allows the chromium sandbox to
27405 ** replace this routine with a harmless no-op. To make this routine
27406 ** a no-op, replace it with a stub that returns SQLITE_OK but leaves
27407 ** *pFd set to a negative number.
27409 ** If SQLITE_OK is returned, the caller is responsible for closing
27410 ** the file descriptor *pFd using close().
27412 static int openDirectory(const char *zFilename, int *pFd){
27413 int ii;
27414 int fd = -1;
27415 char zDirname[MAX_PATHNAME+1];
27417 sqlite3_snprintf(MAX_PATHNAME, zDirname, "%s", zFilename);
27418 for(ii=(int)strlen(zDirname); ii>1 && zDirname[ii]!='/'; ii--);
27419 if( ii>0 ){
27420 zDirname[ii] = '\0';
27421 fd = robust_open(zDirname, O_RDONLY|O_BINARY, 0);
27422 if( fd>=0 ){
27423 #ifdef FD_CLOEXEC
27424 osFcntl(fd, F_SETFD, osFcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
27425 #endif
27426 OSTRACE(("OPENDIR %-3d %s\n", fd, zDirname));
27429 *pFd = fd;
27430 return (fd>=0?SQLITE_OK:unixLogError(SQLITE_CANTOPEN_BKPT, "open", zDirname));
27434 ** Make sure all writes to a particular file are committed to disk.
27436 ** If dataOnly==0 then both the file itself and its metadata (file
27437 ** size, access time, etc) are synced. If dataOnly!=0 then only the
27438 ** file data is synced.
27440 ** Under Unix, also make sure that the directory entry for the file
27441 ** has been created by fsync-ing the directory that contains the file.
27442 ** If we do not do this and we encounter a power failure, the directory
27443 ** entry for the journal might not exist after we reboot. The next
27444 ** SQLite to access the file will not know that the journal exists (because
27445 ** the directory entry for the journal was never created) and the transaction
27446 ** will not roll back - possibly leading to database corruption.
27448 static int unixSync(sqlite3_file *id, int flags){
27449 int rc;
27450 unixFile *pFile = (unixFile*)id;
27452 int isDataOnly = (flags&SQLITE_SYNC_DATAONLY);
27453 int isFullsync = (flags&0x0F)==SQLITE_SYNC_FULL;
27455 /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */
27456 assert((flags&0x0F)==SQLITE_SYNC_NORMAL
27457 || (flags&0x0F)==SQLITE_SYNC_FULL
27460 /* Unix cannot, but some systems may return SQLITE_FULL from here. This
27461 ** line is to test that doing so does not cause any problems.
27463 SimulateDiskfullError( return SQLITE_FULL );
27465 assert( pFile );
27466 OSTRACE(("SYNC %-3d\n", pFile->h));
27467 rc = full_fsync(pFile->h, isFullsync, isDataOnly);
27468 SimulateIOError( rc=1 );
27469 if( rc ){
27470 pFile->lastErrno = errno;
27471 return unixLogError(SQLITE_IOERR_FSYNC, "full_fsync", pFile->zPath);
27474 /* Also fsync the directory containing the file if the DIRSYNC flag
27475 ** is set. This is a one-time occurrance. Many systems (examples: AIX)
27476 ** are unable to fsync a directory, so ignore errors on the fsync.
27478 if( pFile->ctrlFlags & UNIXFILE_DIRSYNC ){
27479 int dirfd;
27480 OSTRACE(("DIRSYNC %s (have_fullfsync=%d fullsync=%d)\n", pFile->zPath,
27481 HAVE_FULLFSYNC, isFullsync));
27482 rc = osOpenDirectory(pFile->zPath, &dirfd);
27483 if( rc==SQLITE_OK && dirfd>=0 ){
27484 full_fsync(dirfd, 0, 0);
27485 robust_close(pFile, dirfd, __LINE__);
27486 }else if( rc==SQLITE_CANTOPEN ){
27487 rc = SQLITE_OK;
27489 pFile->ctrlFlags &= ~UNIXFILE_DIRSYNC;
27491 return rc;
27495 ** Truncate an open file to a specified size
27497 static int unixTruncate(sqlite3_file *id, i64 nByte){
27498 unixFile *pFile = (unixFile *)id;
27499 int rc;
27500 assert( pFile );
27501 SimulateIOError( return SQLITE_IOERR_TRUNCATE );
27503 /* If the user has configured a chunk-size for this file, truncate the
27504 ** file so that it consists of an integer number of chunks (i.e. the
27505 ** actual file size after the operation may be larger than the requested
27506 ** size).
27508 if( pFile->szChunk ){
27509 nByte = ((nByte + pFile->szChunk - 1)/pFile->szChunk) * pFile->szChunk;
27512 rc = robust_ftruncate(pFile->h, (off_t)nByte);
27513 if( rc ){
27514 pFile->lastErrno = errno;
27515 return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
27516 }else{
27517 #ifndef NDEBUG
27518 /* If we are doing a normal write to a database file (as opposed to
27519 ** doing a hot-journal rollback or a write to some file other than a
27520 ** normal database file) and we truncate the file to zero length,
27521 ** that effectively updates the change counter. This might happen
27522 ** when restoring a database using the backup API from a zero-length
27523 ** source.
27525 if( pFile->inNormalWrite && nByte==0 ){
27526 pFile->transCntrChng = 1;
27528 #endif
27530 return SQLITE_OK;
27535 ** Determine the current size of a file in bytes
27537 static int unixFileSize(sqlite3_file *id, i64 *pSize){
27538 int rc;
27539 struct stat buf;
27540 assert( id );
27541 rc = osFstat(((unixFile*)id)->h, &buf);
27542 SimulateIOError( rc=1 );
27543 if( rc!=0 ){
27544 ((unixFile*)id)->lastErrno = errno;
27545 return SQLITE_IOERR_FSTAT;
27547 *pSize = buf.st_size;
27549 /* When opening a zero-size database, the findInodeInfo() procedure
27550 ** writes a single byte into that file in order to work around a bug
27551 ** in the OS-X msdos filesystem. In order to avoid problems with upper
27552 ** layers, we need to report this file size as zero even though it is
27553 ** really 1. Ticket #3260.
27555 if( *pSize==1 ) *pSize = 0;
27558 return SQLITE_OK;
27561 #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
27563 ** Handler for proxy-locking file-control verbs. Defined below in the
27564 ** proxying locking division.
27566 static int proxyFileControl(sqlite3_file*,int,void*);
27567 #endif
27570 ** This function is called to handle the SQLITE_FCNTL_SIZE_HINT
27571 ** file-control operation.
27573 ** If the user has configured a chunk-size for this file, it could be
27574 ** that the file needs to be extended at this point. Otherwise, the
27575 ** SQLITE_FCNTL_SIZE_HINT operation is a no-op for Unix.
27577 static int fcntlSizeHint(unixFile *pFile, i64 nByte){
27578 if( pFile->szChunk ){
27579 i64 nSize; /* Required file size */
27580 struct stat buf; /* Used to hold return values of fstat() */
27582 if( osFstat(pFile->h, &buf) ) return SQLITE_IOERR_FSTAT;
27584 nSize = ((nByte+pFile->szChunk-1) / pFile->szChunk) * pFile->szChunk;
27585 if( nSize>(i64)buf.st_size ){
27587 #if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
27588 /* The code below is handling the return value of osFallocate()
27589 ** correctly. posix_fallocate() is defined to "returns zero on success,
27590 ** or an error number on failure". See the manpage for details. */
27591 int err;
27593 err = osFallocate(pFile->h, buf.st_size, nSize-buf.st_size);
27594 }while( err==EINTR );
27595 if( err ) return SQLITE_IOERR_WRITE;
27596 #else
27597 /* If the OS does not have posix_fallocate(), fake it. First use
27598 ** ftruncate() to set the file size, then write a single byte to
27599 ** the last byte in each block within the extended region. This
27600 ** is the same technique used by glibc to implement posix_fallocate()
27601 ** on systems that do not have a real fallocate() system call.
27603 int nBlk = buf.st_blksize; /* File-system block size */
27604 i64 iWrite; /* Next offset to write to */
27606 if( robust_ftruncate(pFile->h, nSize) ){
27607 pFile->lastErrno = errno;
27608 return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
27610 iWrite = ((buf.st_size + 2*nBlk - 1)/nBlk)*nBlk-1;
27611 while( iWrite<nSize ){
27612 int nWrite = seekAndWrite(pFile, iWrite, "", 1);
27613 if( nWrite!=1 ) return SQLITE_IOERR_WRITE;
27614 iWrite += nBlk;
27616 #endif
27620 return SQLITE_OK;
27624 ** Information and control of an open file handle.
27626 static int unixFileControl(sqlite3_file *id, int op, void *pArg){
27627 switch( op ){
27628 case SQLITE_FCNTL_LOCKSTATE: {
27629 *(int*)pArg = ((unixFile*)id)->eFileLock;
27630 return SQLITE_OK;
27632 case SQLITE_LAST_ERRNO: {
27633 *(int*)pArg = ((unixFile*)id)->lastErrno;
27634 return SQLITE_OK;
27636 case SQLITE_FCNTL_CHUNK_SIZE: {
27637 ((unixFile*)id)->szChunk = *(int *)pArg;
27638 return SQLITE_OK;
27640 case SQLITE_FCNTL_SIZE_HINT: {
27641 return fcntlSizeHint((unixFile *)id, *(i64 *)pArg);
27643 #ifndef NDEBUG
27644 /* The pager calls this method to signal that it has done
27645 ** a rollback and that the database is therefore unchanged and
27646 ** it hence it is OK for the transaction change counter to be
27647 ** unchanged.
27649 case SQLITE_FCNTL_DB_UNCHANGED: {
27650 ((unixFile*)id)->dbUpdate = 0;
27651 return SQLITE_OK;
27653 #endif
27654 #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
27655 case SQLITE_SET_LOCKPROXYFILE:
27656 case SQLITE_GET_LOCKPROXYFILE: {
27657 return proxyFileControl(id,op,pArg);
27659 #endif /* SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__) */
27660 case SQLITE_FCNTL_SYNC_OMITTED: {
27661 return SQLITE_OK; /* A no-op */
27664 return SQLITE_NOTFOUND;
27668 ** Return the sector size in bytes of the underlying block device for
27669 ** the specified file. This is almost always 512 bytes, but may be
27670 ** larger for some devices.
27672 ** SQLite code assumes this function cannot fail. It also assumes that
27673 ** if two files are created in the same file-system directory (i.e.
27674 ** a database and its journal file) that the sector size will be the
27675 ** same for both.
27677 static int unixSectorSize(sqlite3_file *NotUsed){
27678 UNUSED_PARAMETER(NotUsed);
27679 return SQLITE_DEFAULT_SECTOR_SIZE;
27683 ** Return the device characteristics for the file. This is always 0 for unix.
27685 static int unixDeviceCharacteristics(sqlite3_file *NotUsed){
27686 UNUSED_PARAMETER(NotUsed);
27687 return 0;
27690 #ifndef SQLITE_OMIT_WAL
27694 ** Object used to represent an shared memory buffer.
27696 ** When multiple threads all reference the same wal-index, each thread
27697 ** has its own unixShm object, but they all point to a single instance
27698 ** of this unixShmNode object. In other words, each wal-index is opened
27699 ** only once per process.
27701 ** Each unixShmNode object is connected to a single unixInodeInfo object.
27702 ** We could coalesce this object into unixInodeInfo, but that would mean
27703 ** every open file that does not use shared memory (in other words, most
27704 ** open files) would have to carry around this extra information. So
27705 ** the unixInodeInfo object contains a pointer to this unixShmNode object
27706 ** and the unixShmNode object is created only when needed.
27708 ** unixMutexHeld() must be true when creating or destroying
27709 ** this object or while reading or writing the following fields:
27711 ** nRef
27713 ** The following fields are read-only after the object is created:
27715 ** fid
27716 ** zFilename
27718 ** Either unixShmNode.mutex must be held or unixShmNode.nRef==0 and
27719 ** unixMutexHeld() is true when reading or writing any other field
27720 ** in this structure.
27722 struct unixShmNode {
27723 unixInodeInfo *pInode; /* unixInodeInfo that owns this SHM node */
27724 sqlite3_mutex *mutex; /* Mutex to access this object */
27725 char *zFilename; /* Name of the mmapped file */
27726 int h; /* Open file descriptor */
27727 int szRegion; /* Size of shared-memory regions */
27728 int nRegion; /* Size of array apRegion */
27729 char **apRegion; /* Array of mapped shared-memory regions */
27730 int nRef; /* Number of unixShm objects pointing to this */
27731 unixShm *pFirst; /* All unixShm objects pointing to this */
27732 #ifdef SQLITE_DEBUG
27733 u8 exclMask; /* Mask of exclusive locks held */
27734 u8 sharedMask; /* Mask of shared locks held */
27735 u8 nextShmId; /* Next available unixShm.id value */
27736 #endif
27740 ** Structure used internally by this VFS to record the state of an
27741 ** open shared memory connection.
27743 ** The following fields are initialized when this object is created and
27744 ** are read-only thereafter:
27746 ** unixShm.pFile
27747 ** unixShm.id
27749 ** All other fields are read/write. The unixShm.pFile->mutex must be held
27750 ** while accessing any read/write fields.
27752 struct unixShm {
27753 unixShmNode *pShmNode; /* The underlying unixShmNode object */
27754 unixShm *pNext; /* Next unixShm with the same unixShmNode */
27755 u8 hasMutex; /* True if holding the unixShmNode mutex */
27756 u16 sharedMask; /* Mask of shared locks held */
27757 u16 exclMask; /* Mask of exclusive locks held */
27758 #ifdef SQLITE_DEBUG
27759 u8 id; /* Id of this connection within its unixShmNode */
27760 #endif
27764 ** Constants used for locking
27766 #define UNIX_SHM_BASE ((22+SQLITE_SHM_NLOCK)*4) /* first lock byte */
27767 #define UNIX_SHM_DMS (UNIX_SHM_BASE+SQLITE_SHM_NLOCK) /* deadman switch */
27770 ** Apply posix advisory locks for all bytes from ofst through ofst+n-1.
27772 ** Locks block if the mask is exactly UNIX_SHM_C and are non-blocking
27773 ** otherwise.
27775 static int unixShmSystemLock(
27776 unixShmNode *pShmNode, /* Apply locks to this open shared-memory segment */
27777 int lockType, /* F_UNLCK, F_RDLCK, or F_WRLCK */
27778 int ofst, /* First byte of the locking range */
27779 int n /* Number of bytes to lock */
27781 struct flock f; /* The posix advisory locking structure */
27782 int rc = SQLITE_OK; /* Result code form fcntl() */
27784 /* Access to the unixShmNode object is serialized by the caller */
27785 assert( sqlite3_mutex_held(pShmNode->mutex) || pShmNode->nRef==0 );
27787 /* Shared locks never span more than one byte */
27788 assert( n==1 || lockType!=F_RDLCK );
27790 /* Locks are within range */
27791 assert( n>=1 && n<SQLITE_SHM_NLOCK );
27793 if( pShmNode->h>=0 ){
27794 /* Initialize the locking parameters */
27795 memset(&f, 0, sizeof(f));
27796 f.l_type = lockType;
27797 f.l_whence = SEEK_SET;
27798 f.l_start = ofst;
27799 f.l_len = n;
27801 rc = osFcntl(pShmNode->h, F_SETLK, &f);
27802 rc = (rc!=(-1)) ? SQLITE_OK : SQLITE_BUSY;
27805 /* Update the global lock state and do debug tracing */
27806 #ifdef SQLITE_DEBUG
27807 { u16 mask;
27808 OSTRACE(("SHM-LOCK "));
27809 mask = (1<<(ofst+n)) - (1<<ofst);
27810 if( rc==SQLITE_OK ){
27811 if( lockType==F_UNLCK ){
27812 OSTRACE(("unlock %d ok", ofst));
27813 pShmNode->exclMask &= ~mask;
27814 pShmNode->sharedMask &= ~mask;
27815 }else if( lockType==F_RDLCK ){
27816 OSTRACE(("read-lock %d ok", ofst));
27817 pShmNode->exclMask &= ~mask;
27818 pShmNode->sharedMask |= mask;
27819 }else{
27820 assert( lockType==F_WRLCK );
27821 OSTRACE(("write-lock %d ok", ofst));
27822 pShmNode->exclMask |= mask;
27823 pShmNode->sharedMask &= ~mask;
27825 }else{
27826 if( lockType==F_UNLCK ){
27827 OSTRACE(("unlock %d failed", ofst));
27828 }else if( lockType==F_RDLCK ){
27829 OSTRACE(("read-lock failed"));
27830 }else{
27831 assert( lockType==F_WRLCK );
27832 OSTRACE(("write-lock %d failed", ofst));
27835 OSTRACE((" - afterwards %03x,%03x\n",
27836 pShmNode->sharedMask, pShmNode->exclMask));
27838 #endif
27840 return rc;
27845 ** Purge the unixShmNodeList list of all entries with unixShmNode.nRef==0.
27847 ** This is not a VFS shared-memory method; it is a utility function called
27848 ** by VFS shared-memory methods.
27850 static void unixShmPurge(unixFile *pFd){
27851 unixShmNode *p = pFd->pInode->pShmNode;
27852 assert( unixMutexHeld() );
27853 if( p && p->nRef==0 ){
27854 int i;
27855 assert( p->pInode==pFd->pInode );
27856 if( p->mutex ) sqlite3_mutex_free(p->mutex);
27857 for(i=0; i<p->nRegion; i++){
27858 if( p->h>=0 ){
27859 munmap(p->apRegion[i], p->szRegion);
27860 }else{
27861 sqlite3_free(p->apRegion[i]);
27864 sqlite3_free(p->apRegion);
27865 if( p->h>=0 ){
27866 robust_close(pFd, p->h, __LINE__);
27867 p->h = -1;
27869 p->pInode->pShmNode = 0;
27870 sqlite3_free(p);
27875 ** Open a shared-memory area associated with open database file pDbFd.
27876 ** This particular implementation uses mmapped files.
27878 ** The file used to implement shared-memory is in the same directory
27879 ** as the open database file and has the same name as the open database
27880 ** file with the "-shm" suffix added. For example, if the database file
27881 ** is "/home/user1/config.db" then the file that is created and mmapped
27882 ** for shared memory will be called "/home/user1/config.db-shm".
27884 ** Another approach to is to use files in /dev/shm or /dev/tmp or an
27885 ** some other tmpfs mount. But if a file in a different directory
27886 ** from the database file is used, then differing access permissions
27887 ** or a chroot() might cause two different processes on the same
27888 ** database to end up using different files for shared memory -
27889 ** meaning that their memory would not really be shared - resulting
27890 ** in database corruption. Nevertheless, this tmpfs file usage
27891 ** can be enabled at compile-time using -DSQLITE_SHM_DIRECTORY="/dev/shm"
27892 ** or the equivalent. The use of the SQLITE_SHM_DIRECTORY compile-time
27893 ** option results in an incompatible build of SQLite; builds of SQLite
27894 ** that with differing SQLITE_SHM_DIRECTORY settings attempt to use the
27895 ** same database file at the same time, database corruption will likely
27896 ** result. The SQLITE_SHM_DIRECTORY compile-time option is considered
27897 ** "unsupported" and may go away in a future SQLite release.
27899 ** When opening a new shared-memory file, if no other instances of that
27900 ** file are currently open, in this process or in other processes, then
27901 ** the file must be truncated to zero length or have its header cleared.
27903 ** If the original database file (pDbFd) is using the "unix-excl" VFS
27904 ** that means that an exclusive lock is held on the database file and
27905 ** that no other processes are able to read or write the database. In
27906 ** that case, we do not really need shared memory. No shared memory
27907 ** file is created. The shared memory will be simulated with heap memory.
27909 static int unixOpenSharedMemory(unixFile *pDbFd){
27910 struct unixShm *p = 0; /* The connection to be opened */
27911 struct unixShmNode *pShmNode; /* The underlying mmapped file */
27912 int rc; /* Result code */
27913 unixInodeInfo *pInode; /* The inode of fd */
27914 char *zShmFilename; /* Name of the file used for SHM */
27915 int nShmFilename; /* Size of the SHM filename in bytes */
27917 /* Allocate space for the new unixShm object. */
27918 p = sqlite3_malloc( sizeof(*p) );
27919 if( p==0 ) return SQLITE_NOMEM;
27920 memset(p, 0, sizeof(*p));
27921 assert( pDbFd->pShm==0 );
27923 /* Check to see if a unixShmNode object already exists. Reuse an existing
27924 ** one if present. Create a new one if necessary.
27926 unixEnterMutex();
27927 pInode = pDbFd->pInode;
27928 pShmNode = pInode->pShmNode;
27929 if( pShmNode==0 ){
27930 struct stat sStat; /* fstat() info for database file */
27932 /* Call fstat() to figure out the permissions on the database file. If
27933 ** a new *-shm file is created, an attempt will be made to create it
27934 ** with the same permissions. The actual permissions the file is created
27935 ** with are subject to the current umask setting.
27937 if( osFstat(pDbFd->h, &sStat) && pInode->bProcessLock==0 ){
27938 rc = SQLITE_IOERR_FSTAT;
27939 goto shm_open_err;
27942 #ifdef SQLITE_SHM_DIRECTORY
27943 nShmFilename = sizeof(SQLITE_SHM_DIRECTORY) + 30;
27944 #else
27945 nShmFilename = 5 + (int)strlen(pDbFd->zPath);
27946 #endif
27947 pShmNode = sqlite3_malloc( sizeof(*pShmNode) + nShmFilename );
27948 if( pShmNode==0 ){
27949 rc = SQLITE_NOMEM;
27950 goto shm_open_err;
27952 memset(pShmNode, 0, sizeof(*pShmNode));
27953 zShmFilename = pShmNode->zFilename = (char*)&pShmNode[1];
27954 #ifdef SQLITE_SHM_DIRECTORY
27955 sqlite3_snprintf(nShmFilename, zShmFilename,
27956 SQLITE_SHM_DIRECTORY "/sqlite-shm-%x-%x",
27957 (u32)sStat.st_ino, (u32)sStat.st_dev);
27958 #else
27959 sqlite3_snprintf(nShmFilename, zShmFilename, "%s-shm", pDbFd->zPath);
27960 #endif
27961 pShmNode->h = -1;
27962 pDbFd->pInode->pShmNode = pShmNode;
27963 pShmNode->pInode = pDbFd->pInode;
27964 pShmNode->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
27965 if( pShmNode->mutex==0 ){
27966 rc = SQLITE_NOMEM;
27967 goto shm_open_err;
27970 if( pInode->bProcessLock==0 ){
27971 pShmNode->h = robust_open(zShmFilename, O_RDWR|O_CREAT,
27972 (sStat.st_mode & 0777));
27973 if( pShmNode->h<0 ){
27974 rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zShmFilename);
27975 goto shm_open_err;
27978 /* Check to see if another process is holding the dead-man switch.
27979 ** If not, truncate the file to zero length.
27981 rc = SQLITE_OK;
27982 if( unixShmSystemLock(pShmNode, F_WRLCK, UNIX_SHM_DMS, 1)==SQLITE_OK ){
27983 if( robust_ftruncate(pShmNode->h, 0) ){
27984 rc = unixLogError(SQLITE_IOERR_SHMOPEN, "ftruncate", zShmFilename);
27987 if( rc==SQLITE_OK ){
27988 rc = unixShmSystemLock(pShmNode, F_RDLCK, UNIX_SHM_DMS, 1);
27990 if( rc ) goto shm_open_err;
27994 /* Make the new connection a child of the unixShmNode */
27995 p->pShmNode = pShmNode;
27996 #ifdef SQLITE_DEBUG
27997 p->id = pShmNode->nextShmId++;
27998 #endif
27999 pShmNode->nRef++;
28000 pDbFd->pShm = p;
28001 unixLeaveMutex();
28003 /* The reference count on pShmNode has already been incremented under
28004 ** the cover of the unixEnterMutex() mutex and the pointer from the
28005 ** new (struct unixShm) object to the pShmNode has been set. All that is
28006 ** left to do is to link the new object into the linked list starting
28007 ** at pShmNode->pFirst. This must be done while holding the pShmNode->mutex
28008 ** mutex.
28010 sqlite3_mutex_enter(pShmNode->mutex);
28011 p->pNext = pShmNode->pFirst;
28012 pShmNode->pFirst = p;
28013 sqlite3_mutex_leave(pShmNode->mutex);
28014 return SQLITE_OK;
28016 /* Jump here on any error */
28017 shm_open_err:
28018 unixShmPurge(pDbFd); /* This call frees pShmNode if required */
28019 sqlite3_free(p);
28020 unixLeaveMutex();
28021 return rc;
28025 ** This function is called to obtain a pointer to region iRegion of the
28026 ** shared-memory associated with the database file fd. Shared-memory regions
28027 ** are numbered starting from zero. Each shared-memory region is szRegion
28028 ** bytes in size.
28030 ** If an error occurs, an error code is returned and *pp is set to NULL.
28032 ** Otherwise, if the bExtend parameter is 0 and the requested shared-memory
28033 ** region has not been allocated (by any client, including one running in a
28034 ** separate process), then *pp is set to NULL and SQLITE_OK returned. If
28035 ** bExtend is non-zero and the requested shared-memory region has not yet
28036 ** been allocated, it is allocated by this function.
28038 ** If the shared-memory region has already been allocated or is allocated by
28039 ** this call as described above, then it is mapped into this processes
28040 ** address space (if it is not already), *pp is set to point to the mapped
28041 ** memory and SQLITE_OK returned.
28043 static int unixShmMap(
28044 sqlite3_file *fd, /* Handle open on database file */
28045 int iRegion, /* Region to retrieve */
28046 int szRegion, /* Size of regions */
28047 int bExtend, /* True to extend file if necessary */
28048 void volatile **pp /* OUT: Mapped memory */
28050 unixFile *pDbFd = (unixFile*)fd;
28051 unixShm *p;
28052 unixShmNode *pShmNode;
28053 int rc = SQLITE_OK;
28055 /* If the shared-memory file has not yet been opened, open it now. */
28056 if( pDbFd->pShm==0 ){
28057 rc = unixOpenSharedMemory(pDbFd);
28058 if( rc!=SQLITE_OK ) return rc;
28061 p = pDbFd->pShm;
28062 pShmNode = p->pShmNode;
28063 sqlite3_mutex_enter(pShmNode->mutex);
28064 assert( szRegion==pShmNode->szRegion || pShmNode->nRegion==0 );
28065 assert( pShmNode->pInode==pDbFd->pInode );
28066 assert( pShmNode->h>=0 || pDbFd->pInode->bProcessLock==1 );
28067 assert( pShmNode->h<0 || pDbFd->pInode->bProcessLock==0 );
28069 if( pShmNode->nRegion<=iRegion ){
28070 char **apNew; /* New apRegion[] array */
28071 int nByte = (iRegion+1)*szRegion; /* Minimum required file size */
28072 struct stat sStat; /* Used by fstat() */
28074 pShmNode->szRegion = szRegion;
28076 if( pShmNode->h>=0 ){
28077 /* The requested region is not mapped into this processes address space.
28078 ** Check to see if it has been allocated (i.e. if the wal-index file is
28079 ** large enough to contain the requested region).
28081 if( osFstat(pShmNode->h, &sStat) ){
28082 rc = SQLITE_IOERR_SHMSIZE;
28083 goto shmpage_out;
28086 if( sStat.st_size<nByte ){
28087 /* The requested memory region does not exist. If bExtend is set to
28088 ** false, exit early. *pp will be set to NULL and SQLITE_OK returned.
28090 ** Alternatively, if bExtend is true, use ftruncate() to allocate
28091 ** the requested memory region.
28093 if( !bExtend ) goto shmpage_out;
28094 if( robust_ftruncate(pShmNode->h, nByte) ){
28095 rc = unixLogError(SQLITE_IOERR_SHMSIZE, "ftruncate",
28096 pShmNode->zFilename);
28097 goto shmpage_out;
28102 /* Map the requested memory region into this processes address space. */
28103 apNew = (char **)sqlite3_realloc(
28104 pShmNode->apRegion, (iRegion+1)*sizeof(char *)
28106 if( !apNew ){
28107 rc = SQLITE_IOERR_NOMEM;
28108 goto shmpage_out;
28110 pShmNode->apRegion = apNew;
28111 while(pShmNode->nRegion<=iRegion){
28112 void *pMem;
28113 if( pShmNode->h>=0 ){
28114 pMem = mmap(0, szRegion, PROT_READ|PROT_WRITE,
28115 MAP_SHARED, pShmNode->h, pShmNode->nRegion*szRegion
28117 if( pMem==MAP_FAILED ){
28118 rc = SQLITE_IOERR;
28119 goto shmpage_out;
28121 }else{
28122 pMem = sqlite3_malloc(szRegion);
28123 if( pMem==0 ){
28124 rc = SQLITE_NOMEM;
28125 goto shmpage_out;
28127 memset(pMem, 0, szRegion);
28129 pShmNode->apRegion[pShmNode->nRegion] = pMem;
28130 pShmNode->nRegion++;
28134 shmpage_out:
28135 if( pShmNode->nRegion>iRegion ){
28136 *pp = pShmNode->apRegion[iRegion];
28137 }else{
28138 *pp = 0;
28140 sqlite3_mutex_leave(pShmNode->mutex);
28141 return rc;
28145 ** Change the lock state for a shared-memory segment.
28147 ** Note that the relationship between SHAREd and EXCLUSIVE locks is a little
28148 ** different here than in posix. In xShmLock(), one can go from unlocked
28149 ** to shared and back or from unlocked to exclusive and back. But one may
28150 ** not go from shared to exclusive or from exclusive to shared.
28152 static int unixShmLock(
28153 sqlite3_file *fd, /* Database file holding the shared memory */
28154 int ofst, /* First lock to acquire or release */
28155 int n, /* Number of locks to acquire or release */
28156 int flags /* What to do with the lock */
28158 unixFile *pDbFd = (unixFile*)fd; /* Connection holding shared memory */
28159 unixShm *p = pDbFd->pShm; /* The shared memory being locked */
28160 unixShm *pX; /* For looping over all siblings */
28161 unixShmNode *pShmNode = p->pShmNode; /* The underlying file iNode */
28162 int rc = SQLITE_OK; /* Result code */
28163 u16 mask; /* Mask of locks to take or release */
28165 assert( pShmNode==pDbFd->pInode->pShmNode );
28166 assert( pShmNode->pInode==pDbFd->pInode );
28167 assert( ofst>=0 && ofst+n<=SQLITE_SHM_NLOCK );
28168 assert( n>=1 );
28169 assert( flags==(SQLITE_SHM_LOCK | SQLITE_SHM_SHARED)
28170 || flags==(SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE)
28171 || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED)
28172 || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE) );
28173 assert( n==1 || (flags & SQLITE_SHM_EXCLUSIVE)!=0 );
28174 assert( pShmNode->h>=0 || pDbFd->pInode->bProcessLock==1 );
28175 assert( pShmNode->h<0 || pDbFd->pInode->bProcessLock==0 );
28177 mask = (1<<(ofst+n)) - (1<<ofst);
28178 assert( n>1 || mask==(1<<ofst) );
28179 sqlite3_mutex_enter(pShmNode->mutex);
28180 if( flags & SQLITE_SHM_UNLOCK ){
28181 u16 allMask = 0; /* Mask of locks held by siblings */
28183 /* See if any siblings hold this same lock */
28184 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
28185 if( pX==p ) continue;
28186 assert( (pX->exclMask & (p->exclMask|p->sharedMask))==0 );
28187 allMask |= pX->sharedMask;
28190 /* Unlock the system-level locks */
28191 if( (mask & allMask)==0 ){
28192 rc = unixShmSystemLock(pShmNode, F_UNLCK, ofst+UNIX_SHM_BASE, n);
28193 }else{
28194 rc = SQLITE_OK;
28197 /* Undo the local locks */
28198 if( rc==SQLITE_OK ){
28199 p->exclMask &= ~mask;
28200 p->sharedMask &= ~mask;
28202 }else if( flags & SQLITE_SHM_SHARED ){
28203 u16 allShared = 0; /* Union of locks held by connections other than "p" */
28205 /* Find out which shared locks are already held by sibling connections.
28206 ** If any sibling already holds an exclusive lock, go ahead and return
28207 ** SQLITE_BUSY.
28209 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
28210 if( (pX->exclMask & mask)!=0 ){
28211 rc = SQLITE_BUSY;
28212 break;
28214 allShared |= pX->sharedMask;
28217 /* Get shared locks at the system level, if necessary */
28218 if( rc==SQLITE_OK ){
28219 if( (allShared & mask)==0 ){
28220 rc = unixShmSystemLock(pShmNode, F_RDLCK, ofst+UNIX_SHM_BASE, n);
28221 }else{
28222 rc = SQLITE_OK;
28226 /* Get the local shared locks */
28227 if( rc==SQLITE_OK ){
28228 p->sharedMask |= mask;
28230 }else{
28231 /* Make sure no sibling connections hold locks that will block this
28232 ** lock. If any do, return SQLITE_BUSY right away.
28234 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
28235 if( (pX->exclMask & mask)!=0 || (pX->sharedMask & mask)!=0 ){
28236 rc = SQLITE_BUSY;
28237 break;
28241 /* Get the exclusive locks at the system level. Then if successful
28242 ** also mark the local connection as being locked.
28244 if( rc==SQLITE_OK ){
28245 rc = unixShmSystemLock(pShmNode, F_WRLCK, ofst+UNIX_SHM_BASE, n);
28246 if( rc==SQLITE_OK ){
28247 assert( (p->sharedMask & mask)==0 );
28248 p->exclMask |= mask;
28252 sqlite3_mutex_leave(pShmNode->mutex);
28253 OSTRACE(("SHM-LOCK shmid-%d, pid-%d got %03x,%03x\n",
28254 p->id, getpid(), p->sharedMask, p->exclMask));
28255 return rc;
28259 ** Implement a memory barrier or memory fence on shared memory.
28261 ** All loads and stores begun before the barrier must complete before
28262 ** any load or store begun after the barrier.
28264 static void unixShmBarrier(
28265 sqlite3_file *fd /* Database file holding the shared memory */
28267 UNUSED_PARAMETER(fd);
28268 unixEnterMutex();
28269 unixLeaveMutex();
28273 ** Close a connection to shared-memory. Delete the underlying
28274 ** storage if deleteFlag is true.
28276 ** If there is no shared memory associated with the connection then this
28277 ** routine is a harmless no-op.
28279 static int unixShmUnmap(
28280 sqlite3_file *fd, /* The underlying database file */
28281 int deleteFlag /* Delete shared-memory if true */
28283 unixShm *p; /* The connection to be closed */
28284 unixShmNode *pShmNode; /* The underlying shared-memory file */
28285 unixShm **pp; /* For looping over sibling connections */
28286 unixFile *pDbFd; /* The underlying database file */
28288 pDbFd = (unixFile*)fd;
28289 p = pDbFd->pShm;
28290 if( p==0 ) return SQLITE_OK;
28291 pShmNode = p->pShmNode;
28293 assert( pShmNode==pDbFd->pInode->pShmNode );
28294 assert( pShmNode->pInode==pDbFd->pInode );
28296 /* Remove connection p from the set of connections associated
28297 ** with pShmNode */
28298 sqlite3_mutex_enter(pShmNode->mutex);
28299 for(pp=&pShmNode->pFirst; (*pp)!=p; pp = &(*pp)->pNext){}
28300 *pp = p->pNext;
28302 /* Free the connection p */
28303 sqlite3_free(p);
28304 pDbFd->pShm = 0;
28305 sqlite3_mutex_leave(pShmNode->mutex);
28307 /* If pShmNode->nRef has reached 0, then close the underlying
28308 ** shared-memory file, too */
28309 unixEnterMutex();
28310 assert( pShmNode->nRef>0 );
28311 pShmNode->nRef--;
28312 if( pShmNode->nRef==0 ){
28313 if( deleteFlag && pShmNode->h>=0 ) osUnlink(pShmNode->zFilename);
28314 unixShmPurge(pDbFd);
28316 unixLeaveMutex();
28318 return SQLITE_OK;
28322 #else
28323 # define unixShmMap 0
28324 # define unixShmLock 0
28325 # define unixShmBarrier 0
28326 # define unixShmUnmap 0
28327 #endif /* #ifndef SQLITE_OMIT_WAL */
28330 ** Here ends the implementation of all sqlite3_file methods.
28332 ********************** End sqlite3_file Methods *******************************
28333 ******************************************************************************/
28336 ** This division contains definitions of sqlite3_io_methods objects that
28337 ** implement various file locking strategies. It also contains definitions
28338 ** of "finder" functions. A finder-function is used to locate the appropriate
28339 ** sqlite3_io_methods object for a particular database file. The pAppData
28340 ** field of the sqlite3_vfs VFS objects are initialized to be pointers to
28341 ** the correct finder-function for that VFS.
28343 ** Most finder functions return a pointer to a fixed sqlite3_io_methods
28344 ** object. The only interesting finder-function is autolockIoFinder, which
28345 ** looks at the filesystem type and tries to guess the best locking
28346 ** strategy from that.
28348 ** For finder-funtion F, two objects are created:
28350 ** (1) The real finder-function named "FImpt()".
28352 ** (2) A constant pointer to this function named just "F".
28355 ** A pointer to the F pointer is used as the pAppData value for VFS
28356 ** objects. We have to do this instead of letting pAppData point
28357 ** directly at the finder-function since C90 rules prevent a void*
28358 ** from be cast into a function pointer.
28361 ** Each instance of this macro generates two objects:
28363 ** * A constant sqlite3_io_methods object call METHOD that has locking
28364 ** methods CLOSE, LOCK, UNLOCK, CKRESLOCK.
28366 ** * An I/O method finder function called FINDER that returns a pointer
28367 ** to the METHOD object in the previous bullet.
28369 #define IOMETHODS(FINDER, METHOD, VERSION, CLOSE, LOCK, UNLOCK, CKLOCK) \
28370 static const sqlite3_io_methods METHOD = { \
28371 VERSION, /* iVersion */ \
28372 CLOSE, /* xClose */ \
28373 unixRead, /* xRead */ \
28374 unixWrite, /* xWrite */ \
28375 unixTruncate, /* xTruncate */ \
28376 unixSync, /* xSync */ \
28377 unixFileSize, /* xFileSize */ \
28378 LOCK, /* xLock */ \
28379 UNLOCK, /* xUnlock */ \
28380 CKLOCK, /* xCheckReservedLock */ \
28381 unixFileControl, /* xFileControl */ \
28382 unixSectorSize, /* xSectorSize */ \
28383 unixDeviceCharacteristics, /* xDeviceCapabilities */ \
28384 unixShmMap, /* xShmMap */ \
28385 unixShmLock, /* xShmLock */ \
28386 unixShmBarrier, /* xShmBarrier */ \
28387 unixShmUnmap /* xShmUnmap */ \
28388 }; \
28389 static const sqlite3_io_methods *FINDER##Impl(const char *z, unixFile *p){ \
28390 UNUSED_PARAMETER(z); UNUSED_PARAMETER(p); \
28391 return &METHOD; \
28393 static const sqlite3_io_methods *(*const FINDER)(const char*,unixFile *p) \
28394 = FINDER##Impl;
28397 ** Here are all of the sqlite3_io_methods objects for each of the
28398 ** locking strategies. Functions that return pointers to these methods
28399 ** are also created.
28401 IOMETHODS(
28402 posixIoFinder, /* Finder function name */
28403 posixIoMethods, /* sqlite3_io_methods object name */
28404 2, /* shared memory is enabled */
28405 unixClose, /* xClose method */
28406 unixLock, /* xLock method */
28407 unixUnlock, /* xUnlock method */
28408 unixCheckReservedLock /* xCheckReservedLock method */
28410 IOMETHODS(
28411 nolockIoFinder, /* Finder function name */
28412 nolockIoMethods, /* sqlite3_io_methods object name */
28413 1, /* shared memory is disabled */
28414 nolockClose, /* xClose method */
28415 nolockLock, /* xLock method */
28416 nolockUnlock, /* xUnlock method */
28417 nolockCheckReservedLock /* xCheckReservedLock method */
28419 IOMETHODS(
28420 dotlockIoFinder, /* Finder function name */
28421 dotlockIoMethods, /* sqlite3_io_methods object name */
28422 1, /* shared memory is disabled */
28423 dotlockClose, /* xClose method */
28424 dotlockLock, /* xLock method */
28425 dotlockUnlock, /* xUnlock method */
28426 dotlockCheckReservedLock /* xCheckReservedLock method */
28429 #if SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS
28430 IOMETHODS(
28431 flockIoFinder, /* Finder function name */
28432 flockIoMethods, /* sqlite3_io_methods object name */
28433 1, /* shared memory is disabled */
28434 flockClose, /* xClose method */
28435 flockLock, /* xLock method */
28436 flockUnlock, /* xUnlock method */
28437 flockCheckReservedLock /* xCheckReservedLock method */
28439 #endif
28441 #if OS_VXWORKS
28442 IOMETHODS(
28443 semIoFinder, /* Finder function name */
28444 semIoMethods, /* sqlite3_io_methods object name */
28445 1, /* shared memory is disabled */
28446 semClose, /* xClose method */
28447 semLock, /* xLock method */
28448 semUnlock, /* xUnlock method */
28449 semCheckReservedLock /* xCheckReservedLock method */
28451 #endif
28453 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
28454 IOMETHODS(
28455 afpIoFinder, /* Finder function name */
28456 afpIoMethods, /* sqlite3_io_methods object name */
28457 1, /* shared memory is disabled */
28458 afpClose, /* xClose method */
28459 afpLock, /* xLock method */
28460 afpUnlock, /* xUnlock method */
28461 afpCheckReservedLock /* xCheckReservedLock method */
28463 #endif
28466 ** The proxy locking method is a "super-method" in the sense that it
28467 ** opens secondary file descriptors for the conch and lock files and
28468 ** it uses proxy, dot-file, AFP, and flock() locking methods on those
28469 ** secondary files. For this reason, the division that implements
28470 ** proxy locking is located much further down in the file. But we need
28471 ** to go ahead and define the sqlite3_io_methods and finder function
28472 ** for proxy locking here. So we forward declare the I/O methods.
28474 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
28475 static int proxyClose(sqlite3_file*);
28476 static int proxyLock(sqlite3_file*, int);
28477 static int proxyUnlock(sqlite3_file*, int);
28478 static int proxyCheckReservedLock(sqlite3_file*, int*);
28479 IOMETHODS(
28480 proxyIoFinder, /* Finder function name */
28481 proxyIoMethods, /* sqlite3_io_methods object name */
28482 1, /* shared memory is disabled */
28483 proxyClose, /* xClose method */
28484 proxyLock, /* xLock method */
28485 proxyUnlock, /* xUnlock method */
28486 proxyCheckReservedLock /* xCheckReservedLock method */
28488 #endif
28490 /* nfs lockd on OSX 10.3+ doesn't clear write locks when a read lock is set */
28491 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
28492 IOMETHODS(
28493 nfsIoFinder, /* Finder function name */
28494 nfsIoMethods, /* sqlite3_io_methods object name */
28495 1, /* shared memory is disabled */
28496 unixClose, /* xClose method */
28497 unixLock, /* xLock method */
28498 nfsUnlock, /* xUnlock method */
28499 unixCheckReservedLock /* xCheckReservedLock method */
28501 #endif
28503 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
28505 ** This "finder" function attempts to determine the best locking strategy
28506 ** for the database file "filePath". It then returns the sqlite3_io_methods
28507 ** object that implements that strategy.
28509 ** This is for MacOSX only.
28511 static const sqlite3_io_methods *autolockIoFinderImpl(
28512 const char *filePath, /* name of the database file */
28513 unixFile *pNew /* open file object for the database file */
28515 static const struct Mapping {
28516 const char *zFilesystem; /* Filesystem type name */
28517 const sqlite3_io_methods *pMethods; /* Appropriate locking method */
28518 } aMap[] = {
28519 { "hfs", &posixIoMethods },
28520 { "ufs", &posixIoMethods },
28521 { "afpfs", &afpIoMethods },
28522 { "smbfs", &afpIoMethods },
28523 { "webdav", &nolockIoMethods },
28524 { 0, 0 }
28526 int i;
28527 struct statfs fsInfo;
28528 struct flock lockInfo;
28530 if( !filePath ){
28531 /* If filePath==NULL that means we are dealing with a transient file
28532 ** that does not need to be locked. */
28533 return &nolockIoMethods;
28535 if( statfs(filePath, &fsInfo) != -1 ){
28536 if( fsInfo.f_flags & MNT_RDONLY ){
28537 return &nolockIoMethods;
28539 for(i=0; aMap[i].zFilesystem; i++){
28540 if( strcmp(fsInfo.f_fstypename, aMap[i].zFilesystem)==0 ){
28541 return aMap[i].pMethods;
28546 /* Default case. Handles, amongst others, "nfs".
28547 ** Test byte-range lock using fcntl(). If the call succeeds,
28548 ** assume that the file-system supports POSIX style locks.
28550 lockInfo.l_len = 1;
28551 lockInfo.l_start = 0;
28552 lockInfo.l_whence = SEEK_SET;
28553 lockInfo.l_type = F_RDLCK;
28554 if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
28555 if( strcmp(fsInfo.f_fstypename, "nfs")==0 ){
28556 return &nfsIoMethods;
28557 } else {
28558 return &posixIoMethods;
28560 }else{
28561 return &dotlockIoMethods;
28564 static const sqlite3_io_methods
28565 *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
28567 #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
28569 #if OS_VXWORKS && SQLITE_ENABLE_LOCKING_STYLE
28571 ** This "finder" function attempts to determine the best locking strategy
28572 ** for the database file "filePath". It then returns the sqlite3_io_methods
28573 ** object that implements that strategy.
28575 ** This is for VXWorks only.
28577 static const sqlite3_io_methods *autolockIoFinderImpl(
28578 const char *filePath, /* name of the database file */
28579 unixFile *pNew /* the open file object */
28581 struct flock lockInfo;
28583 if( !filePath ){
28584 /* If filePath==NULL that means we are dealing with a transient file
28585 ** that does not need to be locked. */
28586 return &nolockIoMethods;
28589 /* Test if fcntl() is supported and use POSIX style locks.
28590 ** Otherwise fall back to the named semaphore method.
28592 lockInfo.l_len = 1;
28593 lockInfo.l_start = 0;
28594 lockInfo.l_whence = SEEK_SET;
28595 lockInfo.l_type = F_RDLCK;
28596 if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
28597 return &posixIoMethods;
28598 }else{
28599 return &semIoMethods;
28602 static const sqlite3_io_methods
28603 *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
28605 #endif /* OS_VXWORKS && SQLITE_ENABLE_LOCKING_STYLE */
28608 ** An abstract type for a pointer to a IO method finder function:
28610 typedef const sqlite3_io_methods *(*finder_type)(const char*,unixFile*);
28613 /****************************************************************************
28614 **************************** sqlite3_vfs methods ****************************
28616 ** This division contains the implementation of methods on the
28617 ** sqlite3_vfs object.
28621 ** Initializes a unixFile structure with zeros.
28623 void initUnixFile(sqlite3_file* file) {
28624 memset(file, 0, sizeof(unixFile));
28628 ** Initialize the contents of the unixFile structure pointed to by pId.
28630 int fillInUnixFile(
28631 sqlite3_vfs *pVfs, /* Pointer to vfs object */
28632 int h, /* Open file descriptor of file being opened */
28633 int syncDir, /* True to sync directory on first sync */
28634 sqlite3_file *pId, /* Write to the unixFile structure here */
28635 const char *zFilename, /* Name of the file being opened */
28636 int noLock, /* Omit locking if true */
28637 int isDelete, /* Delete on close if true */
28638 int isReadOnly /* True if the file is opened read-only */
28640 const sqlite3_io_methods *pLockingStyle;
28641 unixFile *pNew = (unixFile *)pId;
28642 int rc = SQLITE_OK;
28644 assert( pNew->pInode==NULL );
28646 /* Parameter isDelete is only used on vxworks. Express this explicitly
28647 ** here to prevent compiler warnings about unused parameters.
28649 UNUSED_PARAMETER(isDelete);
28651 /* Usually the path zFilename should not be a relative pathname. The
28652 ** exception is when opening the proxy "conch" file in builds that
28653 ** include the special Apple locking styles.
28655 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
28656 assert( zFilename==0 || zFilename[0]=='/'
28657 || pVfs->pAppData==(void*)&autolockIoFinder );
28658 #else
28659 assert( zFilename==0 || zFilename[0]=='/' );
28660 #endif
28662 OSTRACE(("OPEN %-3d %s\n", h, zFilename));
28663 pNew->h = h;
28664 pNew->zPath = zFilename;
28665 if( strcmp(pVfs->zName,"unix-excl")==0 ){
28666 pNew->ctrlFlags = UNIXFILE_EXCL;
28667 }else{
28668 pNew->ctrlFlags = 0;
28670 if( isReadOnly ){
28671 pNew->ctrlFlags |= UNIXFILE_RDONLY;
28673 if( syncDir ){
28674 pNew->ctrlFlags |= UNIXFILE_DIRSYNC;
28677 #if OS_VXWORKS
28678 pNew->pId = vxworksFindFileId(zFilename);
28679 if( pNew->pId==0 ){
28680 noLock = 1;
28681 rc = SQLITE_NOMEM;
28683 #endif
28685 if( noLock ){
28686 pLockingStyle = &nolockIoMethods;
28687 }else{
28688 pLockingStyle = (**(finder_type*)pVfs->pAppData)(zFilename, pNew);
28689 #if SQLITE_ENABLE_LOCKING_STYLE
28690 /* Cache zFilename in the locking context (AFP and dotlock override) for
28691 ** proxyLock activation is possible (remote proxy is based on db name)
28692 ** zFilename remains valid until file is closed, to support */
28693 pNew->lockingContext = (void*)zFilename;
28694 #endif
28697 if( pLockingStyle == &posixIoMethods
28698 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
28699 || pLockingStyle == &nfsIoMethods
28700 #endif
28702 unixEnterMutex();
28703 rc = findInodeInfo(pNew, &pNew->pInode);
28704 if( rc!=SQLITE_OK ){
28705 /* If an error occured in findInodeInfo(), close the file descriptor
28706 ** immediately, before releasing the mutex. findInodeInfo() may fail
28707 ** in two scenarios:
28709 ** (a) A call to fstat() failed.
28710 ** (b) A malloc failed.
28712 ** Scenario (b) may only occur if the process is holding no other
28713 ** file descriptors open on the same file. If there were other file
28714 ** descriptors on this file, then no malloc would be required by
28715 ** findInodeInfo(). If this is the case, it is quite safe to close
28716 ** handle h - as it is guaranteed that no posix locks will be released
28717 ** by doing so.
28719 ** If scenario (a) caused the error then things are not so safe. The
28720 ** implicit assumption here is that if fstat() fails, things are in
28721 ** such bad shape that dropping a lock or two doesn't matter much.
28723 robust_close(pNew, h, __LINE__);
28724 h = -1;
28726 unixLeaveMutex();
28729 #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
28730 else if( pLockingStyle == &afpIoMethods ){
28731 /* AFP locking uses the file path so it needs to be included in
28732 ** the afpLockingContext.
28734 afpLockingContext *pCtx;
28735 pNew->lockingContext = pCtx = sqlite3_malloc( sizeof(*pCtx) );
28736 if( pCtx==0 ){
28737 rc = SQLITE_NOMEM;
28738 }else{
28739 /* NB: zFilename exists and remains valid until the file is closed
28740 ** according to requirement F11141. So we do not need to make a
28741 ** copy of the filename. */
28742 pCtx->dbPath = zFilename;
28743 pCtx->reserved = 0;
28744 srandomdev();
28745 unixEnterMutex();
28746 rc = findInodeInfo(pNew, &pNew->pInode);
28747 if( rc!=SQLITE_OK ){
28748 sqlite3_free(pNew->lockingContext);
28749 robust_close(pNew, h, __LINE__);
28750 h = -1;
28752 unixLeaveMutex();
28755 #endif
28757 else if( pLockingStyle == &dotlockIoMethods ){
28758 /* Dotfile locking uses the file path so it needs to be included in
28759 ** the dotlockLockingContext
28761 char *zLockFile;
28762 int nFilename;
28763 nFilename = (int)strlen(zFilename) + 6;
28764 zLockFile = (char *)sqlite3_malloc(nFilename);
28765 if( zLockFile==0 ){
28766 rc = SQLITE_NOMEM;
28767 }else{
28768 sqlite3_snprintf(nFilename, zLockFile, "%s" DOTLOCK_SUFFIX, zFilename);
28770 pNew->lockingContext = zLockFile;
28773 #if OS_VXWORKS
28774 else if( pLockingStyle == &semIoMethods ){
28775 /* Named semaphore locking uses the file path so it needs to be
28776 ** included in the semLockingContext
28778 unixEnterMutex();
28779 rc = findInodeInfo(pNew, &pNew->pInode);
28780 if( (rc==SQLITE_OK) && (pNew->pInode->pSem==NULL) ){
28781 char *zSemName = pNew->pInode->aSemName;
28782 int n;
28783 sqlite3_snprintf(MAX_PATHNAME, zSemName, "/%s.sem",
28784 pNew->pId->zCanonicalName);
28785 for( n=1; zSemName[n]; n++ )
28786 if( zSemName[n]=='/' ) zSemName[n] = '_';
28787 pNew->pInode->pSem = sem_open(zSemName, O_CREAT, 0666, 1);
28788 if( pNew->pInode->pSem == SEM_FAILED ){
28789 rc = SQLITE_NOMEM;
28790 pNew->pInode->aSemName[0] = '\0';
28793 unixLeaveMutex();
28795 #endif
28797 pNew->lastErrno = 0;
28798 #if OS_VXWORKS
28799 if( rc!=SQLITE_OK ){
28800 if( h>=0 ) robust_close(pNew, h, __LINE__);
28801 h = -1;
28802 osUnlink(zFilename);
28803 isDelete = 0;
28805 pNew->isDelete = isDelete;
28806 #endif
28807 if( rc!=SQLITE_OK ){
28808 if( h>=0 ) robust_close(pNew, h, __LINE__);
28809 }else{
28810 pNew->pMethod = pLockingStyle;
28811 OpenCounter(+1);
28813 return rc;
28817 ** Return the name of a directory in which to put temporary files.
28818 ** If no suitable temporary file directory can be found, return NULL.
28820 static const char *unixTempFileDir(void){
28821 static const char *azDirs[] = {
28824 "/var/tmp",
28825 "/usr/tmp",
28826 "/tmp",
28827 0 /* List terminator */
28829 unsigned int i;
28830 struct stat buf;
28831 const char *zDir = 0;
28833 azDirs[0] = sqlite3_temp_directory;
28834 if( !azDirs[1] ) azDirs[1] = getenv("TMPDIR");
28835 for(i=0; i<sizeof(azDirs)/sizeof(azDirs[0]); zDir=azDirs[i++]){
28836 if( zDir==0 ) continue;
28837 if( osStat(zDir, &buf) ) continue;
28838 if( !S_ISDIR(buf.st_mode) ) continue;
28839 if( osAccess(zDir, 07) ) continue;
28840 break;
28842 return zDir;
28846 ** Create a temporary file name in zBuf. zBuf must be allocated
28847 ** by the calling process and must be big enough to hold at least
28848 ** pVfs->mxPathname bytes.
28850 static int unixGetTempname(int nBuf, char *zBuf){
28851 static const unsigned char zChars[] =
28852 "abcdefghijklmnopqrstuvwxyz"
28853 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
28854 "0123456789";
28855 unsigned int i, j;
28856 const char *zDir;
28858 /* It's odd to simulate an io-error here, but really this is just
28859 ** using the io-error infrastructure to test that SQLite handles this
28860 ** function failing.
28862 SimulateIOError( return SQLITE_IOERR );
28864 zDir = unixTempFileDir();
28865 if( zDir==0 ) zDir = ".";
28867 /* Check that the output buffer is large enough for the temporary file
28868 ** name. If it is not, return SQLITE_ERROR.
28870 if( (strlen(zDir) + strlen(SQLITE_TEMP_FILE_PREFIX) + 17) >= (size_t)nBuf ){
28871 return SQLITE_ERROR;
28875 sqlite3_snprintf(nBuf-17, zBuf, "%s/"SQLITE_TEMP_FILE_PREFIX, zDir);
28876 j = (int)strlen(zBuf);
28877 sqlite3_randomness(15, &zBuf[j]);
28878 for(i=0; i<15; i++, j++){
28879 zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
28881 zBuf[j] = 0;
28882 }while( osAccess(zBuf,0)==0 );
28883 return SQLITE_OK;
28886 #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
28888 ** Routine to transform a unixFile into a proxy-locking unixFile.
28889 ** Implementation in the proxy-lock division, but used by unixOpen()
28890 ** if SQLITE_PREFER_PROXY_LOCKING is defined.
28892 static int proxyTransformUnixFile(unixFile*, const char*);
28893 #endif
28896 ** Search for an unused file descriptor that was opened on the database
28897 ** file (not a journal or master-journal file) identified by pathname
28898 ** zPath with SQLITE_OPEN_XXX flags matching those passed as the second
28899 ** argument to this function.
28901 ** Such a file descriptor may exist if a database connection was closed
28902 ** but the associated file descriptor could not be closed because some
28903 ** other file descriptor open on the same file is holding a file-lock.
28904 ** Refer to comments in the unixClose() function and the lengthy comment
28905 ** describing "Posix Advisory Locking" at the start of this file for
28906 ** further details. Also, ticket #4018.
28908 ** If a suitable file descriptor is found, then it is returned. If no
28909 ** such file descriptor is located, -1 is returned.
28911 static UnixUnusedFd *findReusableFd(const char *zPath, int flags){
28912 UnixUnusedFd *pUnused = 0;
28914 /* Do not search for an unused file descriptor on vxworks. Not because
28915 ** vxworks would not benefit from the change (it might, we're not sure),
28916 ** but because no way to test it is currently available. It is better
28917 ** not to risk breaking vxworks support for the sake of such an obscure
28918 ** feature. */
28919 #if !OS_VXWORKS
28920 struct stat sStat; /* Results of stat() call */
28922 /* A stat() call may fail for various reasons. If this happens, it is
28923 ** almost certain that an open() call on the same path will also fail.
28924 ** For this reason, if an error occurs in the stat() call here, it is
28925 ** ignored and -1 is returned. The caller will try to open a new file
28926 ** descriptor on the same path, fail, and return an error to SQLite.
28928 ** Even if a subsequent open() call does succeed, the consequences of
28929 ** not searching for a resusable file descriptor are not dire. */
28930 if( 0==osStat(zPath, &sStat) ){
28931 unixInodeInfo *pInode;
28933 unixEnterMutex();
28934 pInode = inodeList;
28935 while( pInode && (pInode->fileId.dev!=sStat.st_dev
28936 || pInode->fileId.ino!=sStat.st_ino) ){
28937 pInode = pInode->pNext;
28939 if( pInode ){
28940 UnixUnusedFd **pp;
28941 for(pp=&pInode->pUnused; *pp && (*pp)->flags!=flags; pp=&((*pp)->pNext));
28942 pUnused = *pp;
28943 if( pUnused ){
28944 *pp = pUnused->pNext;
28947 unixLeaveMutex();
28949 #endif /* if !OS_VXWORKS */
28950 return pUnused;
28954 ** This function is called by unixOpen() to determine the unix permissions
28955 ** to create new files with. If no error occurs, then SQLITE_OK is returned
28956 ** and a value suitable for passing as the third argument to open(2) is
28957 ** written to *pMode. If an IO error occurs, an SQLite error code is
28958 ** returned and the value of *pMode is not modified.
28960 ** If the file being opened is a temporary file, it is always created with
28961 ** the octal permissions 0600 (read/writable by owner only). If the file
28962 ** is a database or master journal file, it is created with the permissions
28963 ** mask SQLITE_DEFAULT_FILE_PERMISSIONS.
28965 ** Finally, if the file being opened is a WAL or regular journal file, then
28966 ** this function queries the file-system for the permissions on the
28967 ** corresponding database file and sets *pMode to this value. Whenever
28968 ** possible, WAL and journal files are created using the same permissions
28969 ** as the associated database file.
28971 static int findCreateFileMode(
28972 const char *zPath, /* Path of file (possibly) being created */
28973 int flags, /* Flags passed as 4th argument to xOpen() */
28974 mode_t *pMode /* OUT: Permissions to open file with */
28976 int rc = SQLITE_OK; /* Return Code */
28977 if( flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL) ){
28978 char zDb[MAX_PATHNAME+1]; /* Database file path */
28979 int nDb; /* Number of valid bytes in zDb */
28980 struct stat sStat; /* Output of stat() on database file */
28982 /* zPath is a path to a WAL or journal file. The following block derives
28983 ** the path to the associated database file from zPath. This block handles
28984 ** the following naming conventions:
28986 ** "<path to db>-journal"
28987 ** "<path to db>-wal"
28988 ** "<path to db>-journal-NNNN"
28989 ** "<path to db>-wal-NNNN"
28991 ** where NNNN is a 4 digit decimal number. The NNNN naming schemes are
28992 ** used by the test_multiplex.c module.
28994 nDb = sqlite3Strlen30(zPath) - 1;
28995 while( nDb>0 && zPath[nDb]!='l' ) nDb--;
28996 nDb -= ((flags & SQLITE_OPEN_WAL) ? 3 : 7);
28997 memcpy(zDb, zPath, nDb);
28998 zDb[nDb] = '\0';
29000 if( 0==osStat(zDb, &sStat) ){
29001 *pMode = sStat.st_mode & 0777;
29002 }else{
29003 rc = SQLITE_IOERR_FSTAT;
29005 }else if( flags & SQLITE_OPEN_DELETEONCLOSE ){
29006 *pMode = 0600;
29007 }else{
29008 *pMode = SQLITE_DEFAULT_FILE_PERMISSIONS;
29010 return rc;
29014 ** Initializes a unixFile structure with zeros.
29016 void chromium_sqlite3_initialize_unix_sqlite3_file(sqlite3_file* file) {
29017 memset(file, 0, sizeof(unixFile));
29020 int chromium_sqlite3_fill_in_unix_sqlite3_file(sqlite3_vfs* vfs,
29021 int fd,
29022 int dirfd,
29023 sqlite3_file* file,
29024 const char* fileName,
29025 int noLock,
29026 int isDelete) {
29027 return fillInUnixFile(vfs, fd, dirfd, file, fileName, noLock, isDelete, 0);
29031 ** Search for an unused file descriptor that was opened on the database file.
29032 ** If a suitable file descriptor if found, then it is stored in *fd; otherwise,
29033 ** *fd is not modified.
29035 ** If a reusable file descriptor is not found, and a new UnixUnusedFd cannot
29036 ** be allocated, SQLITE_NOMEM is returned. Otherwise, SQLITE_OK is returned.
29038 int chromium_sqlite3_get_reusable_file_handle(sqlite3_file* file,
29039 const char* fileName,
29040 int flags,
29041 int* fd) {
29042 unixFile* unixSQLite3File = (unixFile*)file;
29043 int fileType = flags & 0xFFFFFF00;
29044 if (fileType == SQLITE_OPEN_MAIN_DB) {
29045 UnixUnusedFd *unusedFd = findReusableFd(fileName, flags);
29046 if (unusedFd) {
29047 *fd = unusedFd->fd;
29048 } else {
29049 unusedFd = sqlite3_malloc(sizeof(*unusedFd));
29050 if (!unusedFd) {
29051 return SQLITE_NOMEM;
29054 unixSQLite3File->pUnused = unusedFd;
29056 return SQLITE_OK;
29060 ** Marks 'fd' as the unused file descriptor for 'pFile'.
29062 void chromium_sqlite3_update_reusable_file_handle(sqlite3_file* file,
29063 int fd,
29064 int flags) {
29065 unixFile* unixSQLite3File = (unixFile*)file;
29066 if (unixSQLite3File->pUnused) {
29067 unixSQLite3File->pUnused->fd = fd;
29068 unixSQLite3File->pUnused->flags = flags;
29073 ** Destroys pFile's field that keeps track of the unused file descriptor.
29075 void chromium_sqlite3_destroy_reusable_file_handle(sqlite3_file* file) {
29076 unixFile* unixSQLite3File = (unixFile*)file;
29077 sqlite3_free(unixSQLite3File->pUnused);
29081 ** Open the file zPath.
29083 ** Previously, the SQLite OS layer used three functions in place of this
29084 ** one:
29086 ** sqlite3OsOpenReadWrite();
29087 ** sqlite3OsOpenReadOnly();
29088 ** sqlite3OsOpenExclusive();
29090 ** These calls correspond to the following combinations of flags:
29092 ** ReadWrite() -> (READWRITE | CREATE)
29093 ** ReadOnly() -> (READONLY)
29094 ** OpenExclusive() -> (READWRITE | CREATE | EXCLUSIVE)
29096 ** The old OpenExclusive() accepted a boolean argument - "delFlag". If
29097 ** true, the file was configured to be automatically deleted when the
29098 ** file handle closed. To achieve the same effect using this new
29099 ** interface, add the DELETEONCLOSE flag to those specified above for
29100 ** OpenExclusive().
29102 static int unixOpen(
29103 sqlite3_vfs *pVfs, /* The VFS for which this is the xOpen method */
29104 const char *zPath, /* Pathname of file to be opened */
29105 sqlite3_file *pFile, /* The file descriptor to be filled in */
29106 int flags, /* Input flags to control the opening */
29107 int *pOutFlags /* Output flags returned to SQLite core */
29109 unixFile *p = (unixFile *)pFile;
29110 int fd = -1; /* File descriptor returned by open() */
29111 int openFlags = 0; /* Flags to pass to open() */
29112 int eType = flags&0xFFFFFF00; /* Type of file to open */
29113 int noLock; /* True to omit locking primitives */
29114 int rc = SQLITE_OK; /* Function Return Code */
29116 int isExclusive = (flags & SQLITE_OPEN_EXCLUSIVE);
29117 int isDelete = (flags & SQLITE_OPEN_DELETEONCLOSE);
29118 int isCreate = (flags & SQLITE_OPEN_CREATE);
29119 int isReadonly = (flags & SQLITE_OPEN_READONLY);
29120 int isReadWrite = (flags & SQLITE_OPEN_READWRITE);
29121 #if SQLITE_ENABLE_LOCKING_STYLE
29122 int isAutoProxy = (flags & SQLITE_OPEN_AUTOPROXY);
29123 #endif
29125 /* If creating a master or main-file journal, this function will open
29126 ** a file-descriptor on the directory too. The first time unixSync()
29127 ** is called the directory file descriptor will be fsync()ed and close()d.
29129 int syncDir = (isCreate && (
29130 eType==SQLITE_OPEN_MASTER_JOURNAL
29131 || eType==SQLITE_OPEN_MAIN_JOURNAL
29132 || eType==SQLITE_OPEN_WAL
29135 /* If argument zPath is a NULL pointer, this function is required to open
29136 ** a temporary file. Use this buffer to store the file name in.
29138 char zTmpname[MAX_PATHNAME+1];
29139 const char *zName = zPath;
29141 /* Check the following statements are true:
29143 ** (a) Exactly one of the READWRITE and READONLY flags must be set, and
29144 ** (b) if CREATE is set, then READWRITE must also be set, and
29145 ** (c) if EXCLUSIVE is set, then CREATE must also be set.
29146 ** (d) if DELETEONCLOSE is set, then CREATE must also be set.
29148 assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
29149 assert(isCreate==0 || isReadWrite);
29150 assert(isExclusive==0 || isCreate);
29151 assert(isDelete==0 || isCreate);
29153 /* The main DB, main journal, WAL file and master journal are never
29154 ** automatically deleted. Nor are they ever temporary files. */
29155 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB );
29156 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL );
29157 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MASTER_JOURNAL );
29158 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_WAL );
29160 /* Assert that the upper layer has set one of the "file-type" flags. */
29161 assert( eType==SQLITE_OPEN_MAIN_DB || eType==SQLITE_OPEN_TEMP_DB
29162 || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL
29163 || eType==SQLITE_OPEN_SUBJOURNAL || eType==SQLITE_OPEN_MASTER_JOURNAL
29164 || eType==SQLITE_OPEN_TRANSIENT_DB || eType==SQLITE_OPEN_WAL
29167 chromium_sqlite3_initialize_unix_sqlite3_file(pFile);
29169 if( eType==SQLITE_OPEN_MAIN_DB ){
29170 rc = chromium_sqlite3_get_reusable_file_handle(pFile, zName, flags, &fd);
29171 if( rc!=SQLITE_OK ){
29172 return rc;
29174 }else if( !zName ){
29175 /* If zName is NULL, the upper layer is requesting a temp file. */
29176 assert(isDelete && !syncDir);
29177 rc = unixGetTempname(MAX_PATHNAME+1, zTmpname);
29178 if( rc!=SQLITE_OK ){
29179 return rc;
29181 zName = zTmpname;
29184 /* Determine the value of the flags parameter passed to POSIX function
29185 ** open(). These must be calculated even if open() is not called, as
29186 ** they may be stored as part of the file handle and used by the
29187 ** 'conch file' locking functions later on. */
29188 if( isReadonly ) openFlags |= O_RDONLY;
29189 if( isReadWrite ) openFlags |= O_RDWR;
29190 if( isCreate ) openFlags |= O_CREAT;
29191 if( isExclusive ) openFlags |= (O_EXCL|O_NOFOLLOW);
29192 openFlags |= (O_LARGEFILE|O_BINARY);
29194 if( fd<0 ){
29195 mode_t openMode; /* Permissions to create file with */
29196 rc = findCreateFileMode(zName, flags, &openMode);
29197 if( rc!=SQLITE_OK ){
29198 assert( !p->pUnused );
29199 assert( eType==SQLITE_OPEN_WAL || eType==SQLITE_OPEN_MAIN_JOURNAL );
29200 return rc;
29202 fd = robust_open(zName, openFlags, openMode);
29203 OSTRACE(("OPENX %-3d %s 0%o\n", fd, zName, openFlags));
29204 if( fd<0 && errno!=EISDIR && isReadWrite && !isExclusive ){
29205 /* Failed to open the file for read/write access. Try read-only. */
29206 flags &= ~(SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE);
29207 openFlags &= ~(O_RDWR|O_CREAT);
29208 flags |= SQLITE_OPEN_READONLY;
29209 openFlags |= O_RDONLY;
29210 isReadonly = 1;
29211 fd = robust_open(zName, openFlags, openMode);
29213 if( fd<0 ){
29214 rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zName);
29215 goto open_finished;
29218 assert( fd>=0 );
29219 if( pOutFlags ){
29220 *pOutFlags = flags;
29223 chromium_sqlite3_update_reusable_file_handle(pFile, fd, flags);
29225 if( isDelete ){
29226 #if OS_VXWORKS
29227 zPath = zName;
29228 #else
29229 osUnlink(zName);
29230 #endif
29232 #if SQLITE_ENABLE_LOCKING_STYLE
29233 else{
29234 p->openFlags = openFlags;
29236 #endif
29238 #ifdef FD_CLOEXEC
29239 osFcntl(fd, F_SETFD, osFcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
29240 #endif
29242 noLock = eType!=SQLITE_OPEN_MAIN_DB;
29245 #if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
29246 struct statfs fsInfo;
29247 if( fstatfs(fd, &fsInfo) == -1 ){
29248 ((unixFile*)pFile)->lastErrno = errno;
29249 robust_close(p, fd, __LINE__);
29250 return SQLITE_IOERR_ACCESS;
29252 if (0 == strncmp("msdos", fsInfo.f_fstypename, 5)) {
29253 ((unixFile*)pFile)->fsFlags |= SQLITE_FSFLAGS_IS_MSDOS;
29255 #endif
29257 #if SQLITE_ENABLE_LOCKING_STYLE
29258 #if SQLITE_PREFER_PROXY_LOCKING
29259 isAutoProxy = 1;
29260 #endif
29261 if( isAutoProxy && (zPath!=NULL) && (!noLock) && pVfs->xOpen ){
29262 char *envforce = getenv("SQLITE_FORCE_PROXY_LOCKING");
29263 int useProxy = 0;
29265 /* SQLITE_FORCE_PROXY_LOCKING==1 means force always use proxy, 0 means
29266 ** never use proxy, NULL means use proxy for non-local files only. */
29267 if( envforce!=NULL ){
29268 useProxy = atoi(envforce)>0;
29269 }else{
29270 struct statfs fsInfo;
29271 if( statfs(zPath, &fsInfo) == -1 ){
29272 /* In theory, the close(fd) call is sub-optimal. If the file opened
29273 ** with fd is a database file, and there are other connections open
29274 ** on that file that are currently holding advisory locks on it,
29275 ** then the call to close() will cancel those locks. In practice,
29276 ** we're assuming that statfs() doesn't fail very often. At least
29277 ** not while other file descriptors opened by the same process on
29278 ** the same file are working. */
29279 p->lastErrno = errno;
29280 robust_close(p, fd, __LINE__);
29281 rc = SQLITE_IOERR_ACCESS;
29282 goto open_finished;
29284 useProxy = !(fsInfo.f_flags&MNT_LOCAL);
29286 if( useProxy ){
29287 rc = fillInUnixFile(pVfs, fd, syncDir, pFile, zPath, noLock,
29288 isDelete, isReadonly);
29289 if( rc==SQLITE_OK ){
29290 rc = proxyTransformUnixFile((unixFile*)pFile, ":auto:");
29291 if( rc!=SQLITE_OK ){
29292 /* Use unixClose to clean up the resources added in fillInUnixFile
29293 ** and clear all the structure's references. Specifically,
29294 ** pFile->pMethods will be NULL so sqlite3OsClose will be a no-op
29296 unixClose(pFile);
29297 return rc;
29300 goto open_finished;
29303 #endif
29305 rc = fillInUnixFile(pVfs, fd, syncDir, pFile, zPath, noLock,
29306 isDelete, isReadonly);
29307 open_finished:
29308 if( rc!=SQLITE_OK ){
29309 chromium_sqlite3_destroy_reusable_file_handle(pFile);
29311 return rc;
29316 ** Delete the file at zPath. If the dirSync argument is true, fsync()
29317 ** the directory after deleting the file.
29319 static int unixDelete(
29320 sqlite3_vfs *NotUsed, /* VFS containing this as the xDelete method */
29321 const char *zPath, /* Name of file to be deleted */
29322 int dirSync /* If true, fsync() directory after deleting file */
29324 int rc = SQLITE_OK;
29325 UNUSED_PARAMETER(NotUsed);
29326 SimulateIOError(return SQLITE_IOERR_DELETE);
29327 if( osUnlink(zPath)==(-1) && errno!=ENOENT ){
29328 return unixLogError(SQLITE_IOERR_DELETE, "unlink", zPath);
29330 #ifndef SQLITE_DISABLE_DIRSYNC
29331 if( dirSync ){
29332 int fd;
29333 rc = osOpenDirectory(zPath, &fd);
29334 if( rc==SQLITE_OK ){
29335 #if OS_VXWORKS
29336 if( fsync(fd)==-1 )
29337 #else
29338 if( fsync(fd) )
29339 #endif
29341 rc = unixLogError(SQLITE_IOERR_DIR_FSYNC, "fsync", zPath);
29343 robust_close(0, fd, __LINE__);
29344 }else if( rc==SQLITE_CANTOPEN ){
29345 rc = SQLITE_OK;
29348 #endif
29349 return rc;
29353 ** Test the existance of or access permissions of file zPath. The
29354 ** test performed depends on the value of flags:
29356 ** SQLITE_ACCESS_EXISTS: Return 1 if the file exists
29357 ** SQLITE_ACCESS_READWRITE: Return 1 if the file is read and writable.
29358 ** SQLITE_ACCESS_READONLY: Return 1 if the file is readable.
29360 ** Otherwise return 0.
29362 static int unixAccess(
29363 sqlite3_vfs *NotUsed, /* The VFS containing this xAccess method */
29364 const char *zPath, /* Path of the file to examine */
29365 int flags, /* What do we want to learn about the zPath file? */
29366 int *pResOut /* Write result boolean here */
29368 int amode = 0;
29369 UNUSED_PARAMETER(NotUsed);
29370 SimulateIOError( return SQLITE_IOERR_ACCESS; );
29371 switch( flags ){
29372 case SQLITE_ACCESS_EXISTS:
29373 amode = F_OK;
29374 break;
29375 case SQLITE_ACCESS_READWRITE:
29376 amode = W_OK|R_OK;
29377 break;
29378 case SQLITE_ACCESS_READ:
29379 amode = R_OK;
29380 break;
29382 default:
29383 assert(!"Invalid flags argument");
29385 *pResOut = (osAccess(zPath, amode)==0);
29386 if( flags==SQLITE_ACCESS_EXISTS && *pResOut ){
29387 struct stat buf;
29388 if( 0==osStat(zPath, &buf) && buf.st_size==0 ){
29389 *pResOut = 0;
29392 return SQLITE_OK;
29397 ** Turn a relative pathname into a full pathname. The relative path
29398 ** is stored as a nul-terminated string in the buffer pointed to by
29399 ** zPath.
29401 ** zOut points to a buffer of at least sqlite3_vfs.mxPathname bytes
29402 ** (in this case, MAX_PATHNAME bytes). The full-path is written to
29403 ** this buffer before returning.
29405 static int unixFullPathname(
29406 sqlite3_vfs *pVfs, /* Pointer to vfs object */
29407 const char *zPath, /* Possibly relative input path */
29408 int nOut, /* Size of output buffer in bytes */
29409 char *zOut /* Output buffer */
29412 /* It's odd to simulate an io-error here, but really this is just
29413 ** using the io-error infrastructure to test that SQLite handles this
29414 ** function failing. This function could fail if, for example, the
29415 ** current working directory has been unlinked.
29417 SimulateIOError( return SQLITE_ERROR );
29419 assert( pVfs->mxPathname==MAX_PATHNAME );
29420 UNUSED_PARAMETER(pVfs);
29422 zOut[nOut-1] = '\0';
29423 if( zPath[0]=='/' ){
29424 sqlite3_snprintf(nOut, zOut, "%s", zPath);
29425 }else{
29426 int nCwd;
29427 if( osGetcwd(zOut, nOut-1)==0 ){
29428 return unixLogError(SQLITE_CANTOPEN_BKPT, "getcwd", zPath);
29430 nCwd = (int)strlen(zOut);
29431 sqlite3_snprintf(nOut-nCwd, &zOut[nCwd], "/%s", zPath);
29433 return SQLITE_OK;
29437 #ifndef SQLITE_OMIT_LOAD_EXTENSION
29439 ** Interfaces for opening a shared library, finding entry points
29440 ** within the shared library, and closing the shared library.
29442 #include <dlfcn.h>
29443 static void *unixDlOpen(sqlite3_vfs *NotUsed, const char *zFilename){
29444 UNUSED_PARAMETER(NotUsed);
29445 return dlopen(zFilename, RTLD_NOW | RTLD_GLOBAL);
29449 ** SQLite calls this function immediately after a call to unixDlSym() or
29450 ** unixDlOpen() fails (returns a null pointer). If a more detailed error
29451 ** message is available, it is written to zBufOut. If no error message
29452 ** is available, zBufOut is left unmodified and SQLite uses a default
29453 ** error message.
29455 static void unixDlError(sqlite3_vfs *NotUsed, int nBuf, char *zBufOut){
29456 const char *zErr;
29457 UNUSED_PARAMETER(NotUsed);
29458 unixEnterMutex();
29459 zErr = dlerror();
29460 if( zErr ){
29461 sqlite3_snprintf(nBuf, zBufOut, "%s", zErr);
29463 unixLeaveMutex();
29465 static void (*unixDlSym(sqlite3_vfs *NotUsed, void *p, const char*zSym))(void){
29467 ** GCC with -pedantic-errors says that C90 does not allow a void* to be
29468 ** cast into a pointer to a function. And yet the library dlsym() routine
29469 ** returns a void* which is really a pointer to a function. So how do we
29470 ** use dlsym() with -pedantic-errors?
29472 ** Variable x below is defined to be a pointer to a function taking
29473 ** parameters void* and const char* and returning a pointer to a function.
29474 ** We initialize x by assigning it a pointer to the dlsym() function.
29475 ** (That assignment requires a cast.) Then we call the function that
29476 ** x points to.
29478 ** This work-around is unlikely to work correctly on any system where
29479 ** you really cannot cast a function pointer into void*. But then, on the
29480 ** other hand, dlsym() will not work on such a system either, so we have
29481 ** not really lost anything.
29483 void (*(*x)(void*,const char*))(void);
29484 UNUSED_PARAMETER(NotUsed);
29485 x = (void(*(*)(void*,const char*))(void))dlsym;
29486 return (*x)(p, zSym);
29488 static void unixDlClose(sqlite3_vfs *NotUsed, void *pHandle){
29489 UNUSED_PARAMETER(NotUsed);
29490 dlclose(pHandle);
29492 #else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
29493 #define unixDlOpen 0
29494 #define unixDlError 0
29495 #define unixDlSym 0
29496 #define unixDlClose 0
29497 #endif
29500 ** Write nBuf bytes of random data to the supplied buffer zBuf.
29502 static int unixRandomness(sqlite3_vfs *NotUsed, int nBuf, char *zBuf){
29503 UNUSED_PARAMETER(NotUsed);
29504 assert((size_t)nBuf>=(sizeof(time_t)+sizeof(int)));
29506 /* We have to initialize zBuf to prevent valgrind from reporting
29507 ** errors. The reports issued by valgrind are incorrect - we would
29508 ** prefer that the randomness be increased by making use of the
29509 ** uninitialized space in zBuf - but valgrind errors tend to worry
29510 ** some users. Rather than argue, it seems easier just to initialize
29511 ** the whole array and silence valgrind, even if that means less randomness
29512 ** in the random seed.
29514 ** When testing, initializing zBuf[] to zero is all we do. That means
29515 ** that we always use the same random number sequence. This makes the
29516 ** tests repeatable.
29518 memset(zBuf, 0, nBuf);
29519 #if !defined(SQLITE_TEST)
29521 int pid, fd;
29522 fd = robust_open("/dev/urandom", O_RDONLY, 0);
29523 if( fd<0 ){
29524 time_t t;
29525 time(&t);
29526 memcpy(zBuf, &t, sizeof(t));
29527 pid = getpid();
29528 memcpy(&zBuf[sizeof(t)], &pid, sizeof(pid));
29529 assert( sizeof(t)+sizeof(pid)<=(size_t)nBuf );
29530 nBuf = sizeof(t) + sizeof(pid);
29531 }else{
29532 do{ nBuf = osRead(fd, zBuf, nBuf); }while( nBuf<0 && errno==EINTR );
29533 robust_close(0, fd, __LINE__);
29536 #endif
29537 return nBuf;
29542 ** Sleep for a little while. Return the amount of time slept.
29543 ** The argument is the number of microseconds we want to sleep.
29544 ** The return value is the number of microseconds of sleep actually
29545 ** requested from the underlying operating system, a number which
29546 ** might be greater than or equal to the argument, but not less
29547 ** than the argument.
29549 static int unixSleep(sqlite3_vfs *NotUsed, int microseconds){
29550 #if OS_VXWORKS
29551 struct timespec sp;
29553 sp.tv_sec = microseconds / 1000000;
29554 sp.tv_nsec = (microseconds % 1000000) * 1000;
29555 nanosleep(&sp, NULL);
29556 UNUSED_PARAMETER(NotUsed);
29557 return microseconds;
29558 #elif defined(HAVE_USLEEP) && HAVE_USLEEP
29559 usleep(microseconds);
29560 UNUSED_PARAMETER(NotUsed);
29561 return microseconds;
29562 #else
29563 int seconds = (microseconds+999999)/1000000;
29564 sleep(seconds);
29565 UNUSED_PARAMETER(NotUsed);
29566 return seconds*1000000;
29567 #endif
29571 ** The following variable, if set to a non-zero value, is interpreted as
29572 ** the number of seconds since 1970 and is used to set the result of
29573 ** sqlite3OsCurrentTime() during testing.
29575 #ifdef SQLITE_TEST
29576 SQLITE_API int sqlite3_current_time = 0; /* Fake system time in seconds since 1970. */
29577 #endif
29580 ** Find the current time (in Universal Coordinated Time). Write into *piNow
29581 ** the current time and date as a Julian Day number times 86_400_000. In
29582 ** other words, write into *piNow the number of milliseconds since the Julian
29583 ** epoch of noon in Greenwich on November 24, 4714 B.C according to the
29584 ** proleptic Gregorian calendar.
29586 ** On success, return 0. Return 1 if the time and date cannot be found.
29588 static int unixCurrentTimeInt64(sqlite3_vfs *NotUsed, sqlite3_int64 *piNow){
29589 static const sqlite3_int64 unixEpoch = 24405875*(sqlite3_int64)8640000;
29590 #if defined(NO_GETTOD)
29591 time_t t;
29592 time(&t);
29593 *piNow = ((sqlite3_int64)t)*1000 + unixEpoch;
29594 #elif OS_VXWORKS
29595 struct timespec sNow;
29596 clock_gettime(CLOCK_REALTIME, &sNow);
29597 *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_nsec/1000000;
29598 #else
29599 struct timeval sNow;
29600 gettimeofday(&sNow, 0);
29601 *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_usec/1000;
29602 #endif
29604 #ifdef SQLITE_TEST
29605 if( sqlite3_current_time ){
29606 *piNow = 1000*(sqlite3_int64)sqlite3_current_time + unixEpoch;
29608 #endif
29609 UNUSED_PARAMETER(NotUsed);
29610 return 0;
29614 ** Find the current time (in Universal Coordinated Time). Write the
29615 ** current time and date as a Julian Day number into *prNow and
29616 ** return 0. Return 1 if the time and date cannot be found.
29618 static int unixCurrentTime(sqlite3_vfs *NotUsed, double *prNow){
29619 sqlite3_int64 i;
29620 UNUSED_PARAMETER(NotUsed);
29621 unixCurrentTimeInt64(0, &i);
29622 *prNow = i/86400000.0;
29623 return 0;
29627 ** We added the xGetLastError() method with the intention of providing
29628 ** better low-level error messages when operating-system problems come up
29629 ** during SQLite operation. But so far, none of that has been implemented
29630 ** in the core. So this routine is never called. For now, it is merely
29631 ** a place-holder.
29633 static int unixGetLastError(sqlite3_vfs *NotUsed, int NotUsed2, char *NotUsed3){
29634 UNUSED_PARAMETER(NotUsed);
29635 UNUSED_PARAMETER(NotUsed2);
29636 UNUSED_PARAMETER(NotUsed3);
29637 return 0;
29642 ************************ End of sqlite3_vfs methods ***************************
29643 ******************************************************************************/
29645 /******************************************************************************
29646 ************************** Begin Proxy Locking ********************************
29648 ** Proxy locking is a "uber-locking-method" in this sense: It uses the
29649 ** other locking methods on secondary lock files. Proxy locking is a
29650 ** meta-layer over top of the primitive locking implemented above. For
29651 ** this reason, the division that implements of proxy locking is deferred
29652 ** until late in the file (here) after all of the other I/O methods have
29653 ** been defined - so that the primitive locking methods are available
29654 ** as services to help with the implementation of proxy locking.
29656 ****
29658 ** The default locking schemes in SQLite use byte-range locks on the
29659 ** database file to coordinate safe, concurrent access by multiple readers
29660 ** and writers [http://sqlite.org/lockingv3.html]. The five file locking
29661 ** states (UNLOCKED, PENDING, SHARED, RESERVED, EXCLUSIVE) are implemented
29662 ** as POSIX read & write locks over fixed set of locations (via fsctl),
29663 ** on AFP and SMB only exclusive byte-range locks are available via fsctl
29664 ** with _IOWR('z', 23, struct ByteRangeLockPB2) to track the same 5 states.
29665 ** To simulate a F_RDLCK on the shared range, on AFP a randomly selected
29666 ** address in the shared range is taken for a SHARED lock, the entire
29667 ** shared range is taken for an EXCLUSIVE lock):
29669 ** PENDING_BYTE 0x40000000
29670 ** RESERVED_BYTE 0x40000001
29671 ** SHARED_RANGE 0x40000002 -> 0x40000200
29673 ** This works well on the local file system, but shows a nearly 100x
29674 ** slowdown in read performance on AFP because the AFP client disables
29675 ** the read cache when byte-range locks are present. Enabling the read
29676 ** cache exposes a cache coherency problem that is present on all OS X
29677 ** supported network file systems. NFS and AFP both observe the
29678 ** close-to-open semantics for ensuring cache coherency
29679 ** [http://nfs.sourceforge.net/#faq_a8], which does not effectively
29680 ** address the requirements for concurrent database access by multiple
29681 ** readers and writers
29682 ** [http://www.nabble.com/SQLite-on-NFS-cache-coherency-td15655701.html].
29684 ** To address the performance and cache coherency issues, proxy file locking
29685 ** changes the way database access is controlled by limiting access to a
29686 ** single host at a time and moving file locks off of the database file
29687 ** and onto a proxy file on the local file system.
29690 ** Using proxy locks
29691 ** -----------------
29693 ** C APIs
29695 ** sqlite3_file_control(db, dbname, SQLITE_SET_LOCKPROXYFILE,
29696 ** <proxy_path> | ":auto:");
29697 ** sqlite3_file_control(db, dbname, SQLITE_GET_LOCKPROXYFILE, &<proxy_path>);
29700 ** SQL pragmas
29702 ** PRAGMA [database.]lock_proxy_file=<proxy_path> | :auto:
29703 ** PRAGMA [database.]lock_proxy_file
29705 ** Specifying ":auto:" means that if there is a conch file with a matching
29706 ** host ID in it, the proxy path in the conch file will be used, otherwise
29707 ** a proxy path based on the user's temp dir
29708 ** (via confstr(_CS_DARWIN_USER_TEMP_DIR,...)) will be used and the
29709 ** actual proxy file name is generated from the name and path of the
29710 ** database file. For example:
29712 ** For database path "/Users/me/foo.db"
29713 ** The lock path will be "<tmpdir>/sqliteplocks/_Users_me_foo.db:auto:")
29715 ** Once a lock proxy is configured for a database connection, it can not
29716 ** be removed, however it may be switched to a different proxy path via
29717 ** the above APIs (assuming the conch file is not being held by another
29718 ** connection or process).
29721 ** How proxy locking works
29722 ** -----------------------
29724 ** Proxy file locking relies primarily on two new supporting files:
29726 ** * conch file to limit access to the database file to a single host
29727 ** at a time
29729 ** * proxy file to act as a proxy for the advisory locks normally
29730 ** taken on the database
29732 ** The conch file - to use a proxy file, sqlite must first "hold the conch"
29733 ** by taking an sqlite-style shared lock on the conch file, reading the
29734 ** contents and comparing the host's unique host ID (see below) and lock
29735 ** proxy path against the values stored in the conch. The conch file is
29736 ** stored in the same directory as the database file and the file name
29737 ** is patterned after the database file name as ".<databasename>-conch".
29738 ** If the conch file does not exist, or it's contents do not match the
29739 ** host ID and/or proxy path, then the lock is escalated to an exclusive
29740 ** lock and the conch file contents is updated with the host ID and proxy
29741 ** path and the lock is downgraded to a shared lock again. If the conch
29742 ** is held by another process (with a shared lock), the exclusive lock
29743 ** will fail and SQLITE_BUSY is returned.
29745 ** The proxy file - a single-byte file used for all advisory file locks
29746 ** normally taken on the database file. This allows for safe sharing
29747 ** of the database file for multiple readers and writers on the same
29748 ** host (the conch ensures that they all use the same local lock file).
29750 ** Requesting the lock proxy does not immediately take the conch, it is
29751 ** only taken when the first request to lock database file is made.
29752 ** This matches the semantics of the traditional locking behavior, where
29753 ** opening a connection to a database file does not take a lock on it.
29754 ** The shared lock and an open file descriptor are maintained until
29755 ** the connection to the database is closed.
29757 ** The proxy file and the lock file are never deleted so they only need
29758 ** to be created the first time they are used.
29760 ** Configuration options
29761 ** ---------------------
29763 ** SQLITE_PREFER_PROXY_LOCKING
29765 ** Database files accessed on non-local file systems are
29766 ** automatically configured for proxy locking, lock files are
29767 ** named automatically using the same logic as
29768 ** PRAGMA lock_proxy_file=":auto:"
29770 ** SQLITE_PROXY_DEBUG
29772 ** Enables the logging of error messages during host id file
29773 ** retrieval and creation
29775 ** LOCKPROXYDIR
29777 ** Overrides the default directory used for lock proxy files that
29778 ** are named automatically via the ":auto:" setting
29780 ** SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
29782 ** Permissions to use when creating a directory for storing the
29783 ** lock proxy files, only used when LOCKPROXYDIR is not set.
29786 ** As mentioned above, when compiled with SQLITE_PREFER_PROXY_LOCKING,
29787 ** setting the environment variable SQLITE_FORCE_PROXY_LOCKING to 1 will
29788 ** force proxy locking to be used for every database file opened, and 0
29789 ** will force automatic proxy locking to be disabled for all database
29790 ** files (explicity calling the SQLITE_SET_LOCKPROXYFILE pragma or
29791 ** sqlite_file_control API is not affected by SQLITE_FORCE_PROXY_LOCKING).
29795 ** Proxy locking is only available on MacOSX
29797 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
29800 ** The proxyLockingContext has the path and file structures for the remote
29801 ** and local proxy files in it
29803 typedef struct proxyLockingContext proxyLockingContext;
29804 struct proxyLockingContext {
29805 unixFile *conchFile; /* Open conch file */
29806 char *conchFilePath; /* Name of the conch file */
29807 unixFile *lockProxy; /* Open proxy lock file */
29808 char *lockProxyPath; /* Name of the proxy lock file */
29809 char *dbPath; /* Name of the open file */
29810 int conchHeld; /* 1 if the conch is held, -1 if lockless */
29811 void *oldLockingContext; /* Original lockingcontext to restore on close */
29812 sqlite3_io_methods const *pOldMethod; /* Original I/O methods for close */
29816 ** The proxy lock file path for the database at dbPath is written into lPath,
29817 ** which must point to valid, writable memory large enough for a maxLen length
29818 ** file path.
29820 static int proxyGetLockPath(const char *dbPath, char *lPath, size_t maxLen){
29821 int len;
29822 int dbLen;
29823 int i;
29825 #ifdef LOCKPROXYDIR
29826 len = strlcpy(lPath, LOCKPROXYDIR, maxLen);
29827 #else
29828 # ifdef _CS_DARWIN_USER_TEMP_DIR
29830 if( !confstr(_CS_DARWIN_USER_TEMP_DIR, lPath, maxLen) ){
29831 OSTRACE(("GETLOCKPATH failed %s errno=%d pid=%d\n",
29832 lPath, errno, getpid()));
29833 return SQLITE_IOERR_LOCK;
29835 len = strlcat(lPath, "sqliteplocks", maxLen);
29837 # else
29838 len = strlcpy(lPath, "/tmp/", maxLen);
29839 # endif
29840 #endif
29842 if( lPath[len-1]!='/' ){
29843 len = strlcat(lPath, "/", maxLen);
29846 /* transform the db path to a unique cache name */
29847 dbLen = (int)strlen(dbPath);
29848 for( i=0; i<dbLen && (i+len+7)<(int)maxLen; i++){
29849 char c = dbPath[i];
29850 lPath[i+len] = (c=='/')?'_':c;
29852 lPath[i+len]='\0';
29853 strlcat(lPath, ":auto:", maxLen);
29854 OSTRACE(("GETLOCKPATH proxy lock path=%s pid=%d\n", lPath, getpid()));
29855 return SQLITE_OK;
29859 ** Creates the lock file and any missing directories in lockPath
29861 static int proxyCreateLockPath(const char *lockPath){
29862 int i, len;
29863 char buf[MAXPATHLEN];
29864 int start = 0;
29866 assert(lockPath!=NULL);
29867 /* try to create all the intermediate directories */
29868 len = (int)strlen(lockPath);
29869 buf[0] = lockPath[0];
29870 for( i=1; i<len; i++ ){
29871 if( lockPath[i] == '/' && (i - start > 0) ){
29872 /* only mkdir if leaf dir != "." or "/" or ".." */
29873 if( i-start>2 || (i-start==1 && buf[start] != '.' && buf[start] != '/')
29874 || (i-start==2 && buf[start] != '.' && buf[start+1] != '.') ){
29875 buf[i]='\0';
29876 if( mkdir(buf, SQLITE_DEFAULT_PROXYDIR_PERMISSIONS) ){
29877 int err=errno;
29878 if( err!=EEXIST ) {
29879 OSTRACE(("CREATELOCKPATH FAILED creating %s, "
29880 "'%s' proxy lock path=%s pid=%d\n",
29881 buf, strerror(err), lockPath, getpid()));
29882 return err;
29886 start=i+1;
29888 buf[i] = lockPath[i];
29890 OSTRACE(("CREATELOCKPATH proxy lock path=%s pid=%d\n", lockPath, getpid()));
29891 return 0;
29895 ** Create a new VFS file descriptor (stored in memory obtained from
29896 ** sqlite3_malloc) and open the file named "path" in the file descriptor.
29898 ** The caller is responsible not only for closing the file descriptor
29899 ** but also for freeing the memory associated with the file descriptor.
29901 static int proxyCreateUnixFile(
29902 const char *path, /* path for the new unixFile */
29903 unixFile **ppFile, /* unixFile created and returned by ref */
29904 int islockfile /* if non zero missing dirs will be created */
29906 int fd = -1;
29907 unixFile *pNew;
29908 int rc = SQLITE_OK;
29909 int openFlags = O_RDWR | O_CREAT;
29910 sqlite3_vfs dummyVfs;
29911 int terrno = 0;
29912 UnixUnusedFd *pUnused = NULL;
29914 /* 1. first try to open/create the file
29915 ** 2. if that fails, and this is a lock file (not-conch), try creating
29916 ** the parent directories and then try again.
29917 ** 3. if that fails, try to open the file read-only
29918 ** otherwise return BUSY (if lock file) or CANTOPEN for the conch file
29920 pUnused = findReusableFd(path, openFlags);
29921 if( pUnused ){
29922 fd = pUnused->fd;
29923 }else{
29924 pUnused = sqlite3_malloc(sizeof(*pUnused));
29925 if( !pUnused ){
29926 return SQLITE_NOMEM;
29929 if( fd<0 ){
29930 fd = robust_open(path, openFlags, SQLITE_DEFAULT_FILE_PERMISSIONS);
29931 terrno = errno;
29932 if( fd<0 && errno==ENOENT && islockfile ){
29933 if( proxyCreateLockPath(path) == SQLITE_OK ){
29934 fd = robust_open(path, openFlags, SQLITE_DEFAULT_FILE_PERMISSIONS);
29938 if( fd<0 ){
29939 openFlags = O_RDONLY;
29940 fd = robust_open(path, openFlags, SQLITE_DEFAULT_FILE_PERMISSIONS);
29941 terrno = errno;
29943 if( fd<0 ){
29944 if( islockfile ){
29945 return SQLITE_BUSY;
29947 switch (terrno) {
29948 case EACCES:
29949 return SQLITE_PERM;
29950 case EIO:
29951 return SQLITE_IOERR_LOCK; /* even though it is the conch */
29952 default:
29953 return SQLITE_CANTOPEN_BKPT;
29957 pNew = (unixFile *)sqlite3_malloc(sizeof(*pNew));
29958 if( pNew==NULL ){
29959 rc = SQLITE_NOMEM;
29960 goto end_create_proxy;
29962 memset(pNew, 0, sizeof(unixFile));
29963 pNew->openFlags = openFlags;
29964 memset(&dummyVfs, 0, sizeof(dummyVfs));
29965 dummyVfs.pAppData = (void*)&autolockIoFinder;
29966 dummyVfs.zName = "dummy";
29967 pUnused->fd = fd;
29968 pUnused->flags = openFlags;
29969 pNew->pUnused = pUnused;
29971 rc = fillInUnixFile(&dummyVfs, fd, 0, (sqlite3_file*)pNew, path, 0, 0, 0);
29972 if( rc==SQLITE_OK ){
29973 *ppFile = pNew;
29974 return SQLITE_OK;
29976 end_create_proxy:
29977 robust_close(pNew, fd, __LINE__);
29978 sqlite3_free(pNew);
29979 sqlite3_free(pUnused);
29980 return rc;
29983 #ifdef SQLITE_TEST
29984 /* simulate multiple hosts by creating unique hostid file paths */
29985 SQLITE_API int sqlite3_hostid_num = 0;
29986 #endif
29988 #define PROXY_HOSTIDLEN 16 /* conch file host id length */
29990 /* Not always defined in the headers as it ought to be */
29991 extern int gethostuuid(uuid_t id, const struct timespec *wait);
29993 /* get the host ID via gethostuuid(), pHostID must point to PROXY_HOSTIDLEN
29994 ** bytes of writable memory.
29996 static int proxyGetHostID(unsigned char *pHostID, int *pError){
29997 assert(PROXY_HOSTIDLEN == sizeof(uuid_t));
29998 memset(pHostID, 0, PROXY_HOSTIDLEN);
29999 #if defined(__MAX_OS_X_VERSION_MIN_REQUIRED)\
30000 && __MAC_OS_X_VERSION_MIN_REQUIRED<1050
30002 static const struct timespec timeout = {1, 0}; /* 1 sec timeout */
30003 if( gethostuuid(pHostID, &timeout) ){
30004 int err = errno;
30005 if( pError ){
30006 *pError = err;
30008 return SQLITE_IOERR;
30011 #endif
30012 #ifdef SQLITE_TEST
30013 /* simulate multiple hosts by creating unique hostid file paths */
30014 if( sqlite3_hostid_num != 0){
30015 pHostID[0] = (char)(pHostID[0] + (char)(sqlite3_hostid_num & 0xFF));
30017 #endif
30019 return SQLITE_OK;
30022 /* The conch file contains the header, host id and lock file path
30024 #define PROXY_CONCHVERSION 2 /* 1-byte header, 16-byte host id, path */
30025 #define PROXY_HEADERLEN 1 /* conch file header length */
30026 #define PROXY_PATHINDEX (PROXY_HEADERLEN+PROXY_HOSTIDLEN)
30027 #define PROXY_MAXCONCHLEN (PROXY_HEADERLEN+PROXY_HOSTIDLEN+MAXPATHLEN)
30030 ** Takes an open conch file, copies the contents to a new path and then moves
30031 ** it back. The newly created file's file descriptor is assigned to the
30032 ** conch file structure and finally the original conch file descriptor is
30033 ** closed. Returns zero if successful.
30035 static int proxyBreakConchLock(unixFile *pFile, uuid_t myHostID){
30036 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
30037 unixFile *conchFile = pCtx->conchFile;
30038 char tPath[MAXPATHLEN];
30039 char buf[PROXY_MAXCONCHLEN];
30040 char *cPath = pCtx->conchFilePath;
30041 size_t readLen = 0;
30042 size_t pathLen = 0;
30043 char errmsg[64] = "";
30044 int fd = -1;
30045 int rc = -1;
30046 UNUSED_PARAMETER(myHostID);
30048 /* create a new path by replace the trailing '-conch' with '-break' */
30049 pathLen = strlcpy(tPath, cPath, MAXPATHLEN);
30050 if( pathLen>MAXPATHLEN || pathLen<6 ||
30051 (strlcpy(&tPath[pathLen-5], "break", 6) != 5) ){
30052 sqlite3_snprintf(sizeof(errmsg),errmsg,"path error (len %d)",(int)pathLen);
30053 goto end_breaklock;
30055 /* read the conch content */
30056 readLen = osPread(conchFile->h, buf, PROXY_MAXCONCHLEN, 0);
30057 if( readLen<PROXY_PATHINDEX ){
30058 sqlite3_snprintf(sizeof(errmsg),errmsg,"read error (len %d)",(int)readLen);
30059 goto end_breaklock;
30061 /* write it out to the temporary break file */
30062 fd = robust_open(tPath, (O_RDWR|O_CREAT|O_EXCL),
30063 SQLITE_DEFAULT_FILE_PERMISSIONS);
30064 if( fd<0 ){
30065 sqlite3_snprintf(sizeof(errmsg), errmsg, "create failed (%d)", errno);
30066 goto end_breaklock;
30068 if( osPwrite(fd, buf, readLen, 0) != (ssize_t)readLen ){
30069 sqlite3_snprintf(sizeof(errmsg), errmsg, "write failed (%d)", errno);
30070 goto end_breaklock;
30072 if( rename(tPath, cPath) ){
30073 sqlite3_snprintf(sizeof(errmsg), errmsg, "rename failed (%d)", errno);
30074 goto end_breaklock;
30076 rc = 0;
30077 fprintf(stderr, "broke stale lock on %s\n", cPath);
30078 robust_close(pFile, conchFile->h, __LINE__);
30079 conchFile->h = fd;
30080 conchFile->openFlags = O_RDWR | O_CREAT;
30082 end_breaklock:
30083 if( rc ){
30084 if( fd>=0 ){
30085 osUnlink(tPath);
30086 robust_close(pFile, fd, __LINE__);
30088 fprintf(stderr, "failed to break stale lock on %s, %s\n", cPath, errmsg);
30090 return rc;
30093 /* Take the requested lock on the conch file and break a stale lock if the
30094 ** host id matches.
30096 static int proxyConchLock(unixFile *pFile, uuid_t myHostID, int lockType){
30097 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
30098 unixFile *conchFile = pCtx->conchFile;
30099 int rc = SQLITE_OK;
30100 int nTries = 0;
30101 struct timespec conchModTime;
30103 do {
30104 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
30105 nTries ++;
30106 if( rc==SQLITE_BUSY ){
30107 /* If the lock failed (busy):
30108 * 1st try: get the mod time of the conch, wait 0.5s and try again.
30109 * 2nd try: fail if the mod time changed or host id is different, wait
30110 * 10 sec and try again
30111 * 3rd try: break the lock unless the mod time has changed.
30113 struct stat buf;
30114 if( osFstat(conchFile->h, &buf) ){
30115 pFile->lastErrno = errno;
30116 return SQLITE_IOERR_LOCK;
30119 if( nTries==1 ){
30120 conchModTime = buf.st_mtimespec;
30121 usleep(500000); /* wait 0.5 sec and try the lock again*/
30122 continue;
30125 assert( nTries>1 );
30126 if( conchModTime.tv_sec != buf.st_mtimespec.tv_sec ||
30127 conchModTime.tv_nsec != buf.st_mtimespec.tv_nsec ){
30128 return SQLITE_BUSY;
30131 if( nTries==2 ){
30132 char tBuf[PROXY_MAXCONCHLEN];
30133 int len = osPread(conchFile->h, tBuf, PROXY_MAXCONCHLEN, 0);
30134 if( len<0 ){
30135 pFile->lastErrno = errno;
30136 return SQLITE_IOERR_LOCK;
30138 if( len>PROXY_PATHINDEX && tBuf[0]==(char)PROXY_CONCHVERSION){
30139 /* don't break the lock if the host id doesn't match */
30140 if( 0!=memcmp(&tBuf[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN) ){
30141 return SQLITE_BUSY;
30143 }else{
30144 /* don't break the lock on short read or a version mismatch */
30145 return SQLITE_BUSY;
30147 usleep(10000000); /* wait 10 sec and try the lock again */
30148 continue;
30151 assert( nTries==3 );
30152 if( 0==proxyBreakConchLock(pFile, myHostID) ){
30153 rc = SQLITE_OK;
30154 if( lockType==EXCLUSIVE_LOCK ){
30155 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, SHARED_LOCK);
30157 if( !rc ){
30158 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
30162 } while( rc==SQLITE_BUSY && nTries<3 );
30164 return rc;
30167 /* Takes the conch by taking a shared lock and read the contents conch, if
30168 ** lockPath is non-NULL, the host ID and lock file path must match. A NULL
30169 ** lockPath means that the lockPath in the conch file will be used if the
30170 ** host IDs match, or a new lock path will be generated automatically
30171 ** and written to the conch file.
30173 static int proxyTakeConch(unixFile *pFile){
30174 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
30176 if( pCtx->conchHeld!=0 ){
30177 return SQLITE_OK;
30178 }else{
30179 unixFile *conchFile = pCtx->conchFile;
30180 uuid_t myHostID;
30181 int pError = 0;
30182 char readBuf[PROXY_MAXCONCHLEN];
30183 char lockPath[MAXPATHLEN];
30184 char *tempLockPath = NULL;
30185 int rc = SQLITE_OK;
30186 int createConch = 0;
30187 int hostIdMatch = 0;
30188 int readLen = 0;
30189 int tryOldLockPath = 0;
30190 int forceNewLockPath = 0;
30192 OSTRACE(("TAKECONCH %d for %s pid=%d\n", conchFile->h,
30193 (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"), getpid()));
30195 rc = proxyGetHostID(myHostID, &pError);
30196 if( (rc&0xff)==SQLITE_IOERR ){
30197 pFile->lastErrno = pError;
30198 goto end_takeconch;
30200 rc = proxyConchLock(pFile, myHostID, SHARED_LOCK);
30201 if( rc!=SQLITE_OK ){
30202 goto end_takeconch;
30204 /* read the existing conch file */
30205 readLen = seekAndRead((unixFile*)conchFile, 0, readBuf, PROXY_MAXCONCHLEN);
30206 if( readLen<0 ){
30207 /* I/O error: lastErrno set by seekAndRead */
30208 pFile->lastErrno = conchFile->lastErrno;
30209 rc = SQLITE_IOERR_READ;
30210 goto end_takeconch;
30211 }else if( readLen<=(PROXY_HEADERLEN+PROXY_HOSTIDLEN) ||
30212 readBuf[0]!=(char)PROXY_CONCHVERSION ){
30213 /* a short read or version format mismatch means we need to create a new
30214 ** conch file.
30216 createConch = 1;
30218 /* if the host id matches and the lock path already exists in the conch
30219 ** we'll try to use the path there, if we can't open that path, we'll
30220 ** retry with a new auto-generated path
30222 do { /* in case we need to try again for an :auto: named lock file */
30224 if( !createConch && !forceNewLockPath ){
30225 hostIdMatch = !memcmp(&readBuf[PROXY_HEADERLEN], myHostID,
30226 PROXY_HOSTIDLEN);
30227 /* if the conch has data compare the contents */
30228 if( !pCtx->lockProxyPath ){
30229 /* for auto-named local lock file, just check the host ID and we'll
30230 ** use the local lock file path that's already in there
30232 if( hostIdMatch ){
30233 size_t pathLen = (readLen - PROXY_PATHINDEX);
30235 if( pathLen>=MAXPATHLEN ){
30236 pathLen=MAXPATHLEN-1;
30238 memcpy(lockPath, &readBuf[PROXY_PATHINDEX], pathLen);
30239 lockPath[pathLen] = 0;
30240 tempLockPath = lockPath;
30241 tryOldLockPath = 1;
30242 /* create a copy of the lock path if the conch is taken */
30243 goto end_takeconch;
30245 }else if( hostIdMatch
30246 && !strncmp(pCtx->lockProxyPath, &readBuf[PROXY_PATHINDEX],
30247 readLen-PROXY_PATHINDEX)
30249 /* conch host and lock path match */
30250 goto end_takeconch;
30254 /* if the conch isn't writable and doesn't match, we can't take it */
30255 if( (conchFile->openFlags&O_RDWR) == 0 ){
30256 rc = SQLITE_BUSY;
30257 goto end_takeconch;
30260 /* either the conch didn't match or we need to create a new one */
30261 if( !pCtx->lockProxyPath ){
30262 proxyGetLockPath(pCtx->dbPath, lockPath, MAXPATHLEN);
30263 tempLockPath = lockPath;
30264 /* create a copy of the lock path _only_ if the conch is taken */
30267 /* update conch with host and path (this will fail if other process
30268 ** has a shared lock already), if the host id matches, use the big
30269 ** stick.
30271 futimes(conchFile->h, NULL);
30272 if( hostIdMatch && !createConch ){
30273 if( conchFile->pInode && conchFile->pInode->nShared>1 ){
30274 /* We are trying for an exclusive lock but another thread in this
30275 ** same process is still holding a shared lock. */
30276 rc = SQLITE_BUSY;
30277 } else {
30278 rc = proxyConchLock(pFile, myHostID, EXCLUSIVE_LOCK);
30280 }else{
30281 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, EXCLUSIVE_LOCK);
30283 if( rc==SQLITE_OK ){
30284 char writeBuffer[PROXY_MAXCONCHLEN];
30285 int writeSize = 0;
30287 writeBuffer[0] = (char)PROXY_CONCHVERSION;
30288 memcpy(&writeBuffer[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN);
30289 if( pCtx->lockProxyPath!=NULL ){
30290 strlcpy(&writeBuffer[PROXY_PATHINDEX], pCtx->lockProxyPath, MAXPATHLEN);
30291 }else{
30292 strlcpy(&writeBuffer[PROXY_PATHINDEX], tempLockPath, MAXPATHLEN);
30294 writeSize = PROXY_PATHINDEX + strlen(&writeBuffer[PROXY_PATHINDEX]);
30295 robust_ftruncate(conchFile->h, writeSize);
30296 rc = unixWrite((sqlite3_file *)conchFile, writeBuffer, writeSize, 0);
30297 fsync(conchFile->h);
30298 /* If we created a new conch file (not just updated the contents of a
30299 ** valid conch file), try to match the permissions of the database
30301 if( rc==SQLITE_OK && createConch ){
30302 struct stat buf;
30303 int err = osFstat(pFile->h, &buf);
30304 if( err==0 ){
30305 mode_t cmode = buf.st_mode&(S_IRUSR|S_IWUSR | S_IRGRP|S_IWGRP |
30306 S_IROTH|S_IWOTH);
30307 /* try to match the database file R/W permissions, ignore failure */
30308 #ifndef SQLITE_PROXY_DEBUG
30309 osFchmod(conchFile->h, cmode);
30310 #else
30312 rc = osFchmod(conchFile->h, cmode);
30313 }while( rc==(-1) && errno==EINTR );
30314 if( rc!=0 ){
30315 int code = errno;
30316 fprintf(stderr, "fchmod %o FAILED with %d %s\n",
30317 cmode, code, strerror(code));
30318 } else {
30319 fprintf(stderr, "fchmod %o SUCCEDED\n",cmode);
30321 }else{
30322 int code = errno;
30323 fprintf(stderr, "STAT FAILED[%d] with %d %s\n",
30324 err, code, strerror(code));
30325 #endif
30329 conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, SHARED_LOCK);
30331 end_takeconch:
30332 OSTRACE(("TRANSPROXY: CLOSE %d\n", pFile->h));
30333 if( rc==SQLITE_OK && pFile->openFlags ){
30334 if( pFile->h>=0 ){
30335 robust_close(pFile, pFile->h, __LINE__);
30337 pFile->h = -1;
30338 int fd = robust_open(pCtx->dbPath, pFile->openFlags,
30339 SQLITE_DEFAULT_FILE_PERMISSIONS);
30340 OSTRACE(("TRANSPROXY: OPEN %d\n", fd));
30341 if( fd>=0 ){
30342 pFile->h = fd;
30343 }else{
30344 rc=SQLITE_CANTOPEN_BKPT; /* SQLITE_BUSY? proxyTakeConch called
30345 during locking */
30348 if( rc==SQLITE_OK && !pCtx->lockProxy ){
30349 char *path = tempLockPath ? tempLockPath : pCtx->lockProxyPath;
30350 rc = proxyCreateUnixFile(path, &pCtx->lockProxy, 1);
30351 if( rc!=SQLITE_OK && rc!=SQLITE_NOMEM && tryOldLockPath ){
30352 /* we couldn't create the proxy lock file with the old lock file path
30353 ** so try again via auto-naming
30355 forceNewLockPath = 1;
30356 tryOldLockPath = 0;
30357 continue; /* go back to the do {} while start point, try again */
30360 if( rc==SQLITE_OK ){
30361 /* Need to make a copy of path if we extracted the value
30362 ** from the conch file or the path was allocated on the stack
30364 if( tempLockPath ){
30365 pCtx->lockProxyPath = sqlite3DbStrDup(0, tempLockPath);
30366 if( !pCtx->lockProxyPath ){
30367 rc = SQLITE_NOMEM;
30371 if( rc==SQLITE_OK ){
30372 pCtx->conchHeld = 1;
30374 if( pCtx->lockProxy->pMethod == &afpIoMethods ){
30375 afpLockingContext *afpCtx;
30376 afpCtx = (afpLockingContext *)pCtx->lockProxy->lockingContext;
30377 afpCtx->dbPath = pCtx->lockProxyPath;
30379 } else {
30380 conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
30382 OSTRACE(("TAKECONCH %d %s\n", conchFile->h,
30383 rc==SQLITE_OK?"ok":"failed"));
30384 return rc;
30385 } while (1); /* in case we need to retry the :auto: lock file -
30386 ** we should never get here except via the 'continue' call. */
30391 ** If pFile holds a lock on a conch file, then release that lock.
30393 static int proxyReleaseConch(unixFile *pFile){
30394 int rc = SQLITE_OK; /* Subroutine return code */
30395 proxyLockingContext *pCtx; /* The locking context for the proxy lock */
30396 unixFile *conchFile; /* Name of the conch file */
30398 pCtx = (proxyLockingContext *)pFile->lockingContext;
30399 conchFile = pCtx->conchFile;
30400 OSTRACE(("RELEASECONCH %d for %s pid=%d\n", conchFile->h,
30401 (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"),
30402 getpid()));
30403 if( pCtx->conchHeld>0 ){
30404 rc = conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
30406 pCtx->conchHeld = 0;
30407 OSTRACE(("RELEASECONCH %d %s\n", conchFile->h,
30408 (rc==SQLITE_OK ? "ok" : "failed")));
30409 return rc;
30413 ** Given the name of a database file, compute the name of its conch file.
30414 ** Store the conch filename in memory obtained from sqlite3_malloc().
30415 ** Make *pConchPath point to the new name. Return SQLITE_OK on success
30416 ** or SQLITE_NOMEM if unable to obtain memory.
30418 ** The caller is responsible for ensuring that the allocated memory
30419 ** space is eventually freed.
30421 ** *pConchPath is set to NULL if a memory allocation error occurs.
30423 static int proxyCreateConchPathname(char *dbPath, char **pConchPath){
30424 int i; /* Loop counter */
30425 int len = (int)strlen(dbPath); /* Length of database filename - dbPath */
30426 char *conchPath; /* buffer in which to construct conch name */
30428 /* Allocate space for the conch filename and initialize the name to
30429 ** the name of the original database file. */
30430 *pConchPath = conchPath = (char *)sqlite3_malloc(len + 8);
30431 if( conchPath==0 ){
30432 return SQLITE_NOMEM;
30434 memcpy(conchPath, dbPath, len+1);
30436 /* now insert a "." before the last / character */
30437 for( i=(len-1); i>=0; i-- ){
30438 if( conchPath[i]=='/' ){
30439 i++;
30440 break;
30443 conchPath[i]='.';
30444 while ( i<len ){
30445 conchPath[i+1]=dbPath[i];
30446 i++;
30449 /* append the "-conch" suffix to the file */
30450 memcpy(&conchPath[i+1], "-conch", 7);
30451 assert( (int)strlen(conchPath) == len+7 );
30453 return SQLITE_OK;
30457 /* Takes a fully configured proxy locking-style unix file and switches
30458 ** the local lock file path
30460 static int switchLockProxyPath(unixFile *pFile, const char *path) {
30461 proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
30462 char *oldPath = pCtx->lockProxyPath;
30463 int rc = SQLITE_OK;
30465 if( pFile->eFileLock!=NO_LOCK ){
30466 return SQLITE_BUSY;
30469 /* nothing to do if the path is NULL, :auto: or matches the existing path */
30470 if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ||
30471 (oldPath && !strncmp(oldPath, path, MAXPATHLEN)) ){
30472 return SQLITE_OK;
30473 }else{
30474 unixFile *lockProxy = pCtx->lockProxy;
30475 pCtx->lockProxy=NULL;
30476 pCtx->conchHeld = 0;
30477 if( lockProxy!=NULL ){
30478 rc=lockProxy->pMethod->xClose((sqlite3_file *)lockProxy);
30479 if( rc ) return rc;
30480 sqlite3_free(lockProxy);
30482 sqlite3_free(oldPath);
30483 pCtx->lockProxyPath = sqlite3DbStrDup(0, path);
30486 return rc;
30490 ** pFile is a file that has been opened by a prior xOpen call. dbPath
30491 ** is a string buffer at least MAXPATHLEN+1 characters in size.
30493 ** This routine find the filename associated with pFile and writes it
30494 ** int dbPath.
30496 static int proxyGetDbPathForUnixFile(unixFile *pFile, char *dbPath){
30497 #if defined(__APPLE__)
30498 if( pFile->pMethod == &afpIoMethods ){
30499 /* afp style keeps a reference to the db path in the filePath field
30500 ** of the struct */
30501 assert( (int)strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
30502 strlcpy(dbPath, ((afpLockingContext *)pFile->lockingContext)->dbPath, MAXPATHLEN);
30503 } else
30504 #endif
30505 if( pFile->pMethod == &dotlockIoMethods ){
30506 /* dot lock style uses the locking context to store the dot lock
30507 ** file path */
30508 int len = strlen((char *)pFile->lockingContext) - strlen(DOTLOCK_SUFFIX);
30509 memcpy(dbPath, (char *)pFile->lockingContext, len + 1);
30510 }else{
30511 /* all other styles use the locking context to store the db file path */
30512 assert( strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
30513 strlcpy(dbPath, (char *)pFile->lockingContext, MAXPATHLEN);
30515 return SQLITE_OK;
30519 ** Takes an already filled in unix file and alters it so all file locking
30520 ** will be performed on the local proxy lock file. The following fields
30521 ** are preserved in the locking context so that they can be restored and
30522 ** the unix structure properly cleaned up at close time:
30523 ** ->lockingContext
30524 ** ->pMethod
30526 static int proxyTransformUnixFile(unixFile *pFile, const char *path) {
30527 proxyLockingContext *pCtx;
30528 char dbPath[MAXPATHLEN+1]; /* Name of the database file */
30529 char *lockPath=NULL;
30530 int rc = SQLITE_OK;
30532 if( pFile->eFileLock!=NO_LOCK ){
30533 return SQLITE_BUSY;
30535 proxyGetDbPathForUnixFile(pFile, dbPath);
30536 if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ){
30537 lockPath=NULL;
30538 }else{
30539 lockPath=(char *)path;
30542 OSTRACE(("TRANSPROXY %d for %s pid=%d\n", pFile->h,
30543 (lockPath ? lockPath : ":auto:"), getpid()));
30545 pCtx = sqlite3_malloc( sizeof(*pCtx) );
30546 if( pCtx==0 ){
30547 return SQLITE_NOMEM;
30549 memset(pCtx, 0, sizeof(*pCtx));
30551 rc = proxyCreateConchPathname(dbPath, &pCtx->conchFilePath);
30552 if( rc==SQLITE_OK ){
30553 rc = proxyCreateUnixFile(pCtx->conchFilePath, &pCtx->conchFile, 0);
30554 if( rc==SQLITE_CANTOPEN && ((pFile->openFlags&O_RDWR) == 0) ){
30555 /* if (a) the open flags are not O_RDWR, (b) the conch isn't there, and
30556 ** (c) the file system is read-only, then enable no-locking access.
30557 ** Ugh, since O_RDONLY==0x0000 we test for !O_RDWR since unixOpen asserts
30558 ** that openFlags will have only one of O_RDONLY or O_RDWR.
30560 struct statfs fsInfo;
30561 struct stat conchInfo;
30562 int goLockless = 0;
30564 if( osStat(pCtx->conchFilePath, &conchInfo) == -1 ) {
30565 int err = errno;
30566 if( (err==ENOENT) && (statfs(dbPath, &fsInfo) != -1) ){
30567 goLockless = (fsInfo.f_flags&MNT_RDONLY) == MNT_RDONLY;
30570 if( goLockless ){
30571 pCtx->conchHeld = -1; /* read only FS/ lockless */
30572 rc = SQLITE_OK;
30576 if( rc==SQLITE_OK && lockPath ){
30577 pCtx->lockProxyPath = sqlite3DbStrDup(0, lockPath);
30580 if( rc==SQLITE_OK ){
30581 pCtx->dbPath = sqlite3DbStrDup(0, dbPath);
30582 if( pCtx->dbPath==NULL ){
30583 rc = SQLITE_NOMEM;
30586 if( rc==SQLITE_OK ){
30587 /* all memory is allocated, proxys are created and assigned,
30588 ** switch the locking context and pMethod then return.
30590 pCtx->oldLockingContext = pFile->lockingContext;
30591 pFile->lockingContext = pCtx;
30592 pCtx->pOldMethod = pFile->pMethod;
30593 pFile->pMethod = &proxyIoMethods;
30594 }else{
30595 if( pCtx->conchFile ){
30596 pCtx->conchFile->pMethod->xClose((sqlite3_file *)pCtx->conchFile);
30597 sqlite3_free(pCtx->conchFile);
30599 sqlite3DbFree(0, pCtx->lockProxyPath);
30600 sqlite3_free(pCtx->conchFilePath);
30601 sqlite3_free(pCtx);
30603 OSTRACE(("TRANSPROXY %d %s\n", pFile->h,
30604 (rc==SQLITE_OK ? "ok" : "failed")));
30605 return rc;
30610 ** This routine handles sqlite3_file_control() calls that are specific
30611 ** to proxy locking.
30613 static int proxyFileControl(sqlite3_file *id, int op, void *pArg){
30614 switch( op ){
30615 case SQLITE_GET_LOCKPROXYFILE: {
30616 unixFile *pFile = (unixFile*)id;
30617 if( pFile->pMethod == &proxyIoMethods ){
30618 proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
30619 proxyTakeConch(pFile);
30620 if( pCtx->lockProxyPath ){
30621 *(const char **)pArg = pCtx->lockProxyPath;
30622 }else{
30623 *(const char **)pArg = ":auto: (not held)";
30625 } else {
30626 *(const char **)pArg = NULL;
30628 return SQLITE_OK;
30630 case SQLITE_SET_LOCKPROXYFILE: {
30631 unixFile *pFile = (unixFile*)id;
30632 int rc = SQLITE_OK;
30633 int isProxyStyle = (pFile->pMethod == &proxyIoMethods);
30634 if( pArg==NULL || (const char *)pArg==0 ){
30635 if( isProxyStyle ){
30636 /* turn off proxy locking - not supported */
30637 rc = SQLITE_ERROR /*SQLITE_PROTOCOL? SQLITE_MISUSE?*/;
30638 }else{
30639 /* turn off proxy locking - already off - NOOP */
30640 rc = SQLITE_OK;
30642 }else{
30643 const char *proxyPath = (const char *)pArg;
30644 if( isProxyStyle ){
30645 proxyLockingContext *pCtx =
30646 (proxyLockingContext*)pFile->lockingContext;
30647 if( !strcmp(pArg, ":auto:")
30648 || (pCtx->lockProxyPath &&
30649 !strncmp(pCtx->lockProxyPath, proxyPath, MAXPATHLEN))
30651 rc = SQLITE_OK;
30652 }else{
30653 rc = switchLockProxyPath(pFile, proxyPath);
30655 }else{
30656 /* turn on proxy file locking */
30657 rc = proxyTransformUnixFile(pFile, proxyPath);
30660 return rc;
30662 default: {
30663 assert( 0 ); /* The call assures that only valid opcodes are sent */
30666 /*NOTREACHED*/
30667 return SQLITE_ERROR;
30671 ** Within this division (the proxying locking implementation) the procedures
30672 ** above this point are all utilities. The lock-related methods of the
30673 ** proxy-locking sqlite3_io_method object follow.
30678 ** This routine checks if there is a RESERVED lock held on the specified
30679 ** file by this or any other process. If such a lock is held, set *pResOut
30680 ** to a non-zero value otherwise *pResOut is set to zero. The return value
30681 ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
30683 static int proxyCheckReservedLock(sqlite3_file *id, int *pResOut) {
30684 unixFile *pFile = (unixFile*)id;
30685 int rc = proxyTakeConch(pFile);
30686 if( rc==SQLITE_OK ){
30687 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
30688 if( pCtx->conchHeld>0 ){
30689 unixFile *proxy = pCtx->lockProxy;
30690 return proxy->pMethod->xCheckReservedLock((sqlite3_file*)proxy, pResOut);
30691 }else{ /* conchHeld < 0 is lockless */
30692 pResOut=0;
30695 return rc;
30699 ** Lock the file with the lock specified by parameter eFileLock - one
30700 ** of the following:
30702 ** (1) SHARED_LOCK
30703 ** (2) RESERVED_LOCK
30704 ** (3) PENDING_LOCK
30705 ** (4) EXCLUSIVE_LOCK
30707 ** Sometimes when requesting one lock state, additional lock states
30708 ** are inserted in between. The locking might fail on one of the later
30709 ** transitions leaving the lock state different from what it started but
30710 ** still short of its goal. The following chart shows the allowed
30711 ** transitions and the inserted intermediate states:
30713 ** UNLOCKED -> SHARED
30714 ** SHARED -> RESERVED
30715 ** SHARED -> (PENDING) -> EXCLUSIVE
30716 ** RESERVED -> (PENDING) -> EXCLUSIVE
30717 ** PENDING -> EXCLUSIVE
30719 ** This routine will only increase a lock. Use the sqlite3OsUnlock()
30720 ** routine to lower a locking level.
30722 static int proxyLock(sqlite3_file *id, int eFileLock) {
30723 unixFile *pFile = (unixFile*)id;
30724 int rc = proxyTakeConch(pFile);
30725 if( rc==SQLITE_OK ){
30726 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
30727 if( pCtx->conchHeld>0 ){
30728 unixFile *proxy = pCtx->lockProxy;
30729 rc = proxy->pMethod->xLock((sqlite3_file*)proxy, eFileLock);
30730 pFile->eFileLock = proxy->eFileLock;
30731 }else{
30732 /* conchHeld < 0 is lockless */
30735 return rc;
30740 ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
30741 ** must be either NO_LOCK or SHARED_LOCK.
30743 ** If the locking level of the file descriptor is already at or below
30744 ** the requested locking level, this routine is a no-op.
30746 static int proxyUnlock(sqlite3_file *id, int eFileLock) {
30747 unixFile *pFile = (unixFile*)id;
30748 int rc = proxyTakeConch(pFile);
30749 if( rc==SQLITE_OK ){
30750 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
30751 if( pCtx->conchHeld>0 ){
30752 unixFile *proxy = pCtx->lockProxy;
30753 rc = proxy->pMethod->xUnlock((sqlite3_file*)proxy, eFileLock);
30754 pFile->eFileLock = proxy->eFileLock;
30755 }else{
30756 /* conchHeld < 0 is lockless */
30759 return rc;
30763 ** Close a file that uses proxy locks.
30765 static int proxyClose(sqlite3_file *id) {
30766 if( id ){
30767 unixFile *pFile = (unixFile*)id;
30768 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
30769 unixFile *lockProxy = pCtx->lockProxy;
30770 unixFile *conchFile = pCtx->conchFile;
30771 int rc = SQLITE_OK;
30773 if( lockProxy ){
30774 rc = lockProxy->pMethod->xUnlock((sqlite3_file*)lockProxy, NO_LOCK);
30775 if( rc ) return rc;
30776 rc = lockProxy->pMethod->xClose((sqlite3_file*)lockProxy);
30777 if( rc ) return rc;
30778 sqlite3_free(lockProxy);
30779 pCtx->lockProxy = 0;
30781 if( conchFile ){
30782 if( pCtx->conchHeld ){
30783 rc = proxyReleaseConch(pFile);
30784 if( rc ) return rc;
30786 rc = conchFile->pMethod->xClose((sqlite3_file*)conchFile);
30787 if( rc ) return rc;
30788 sqlite3_free(conchFile);
30790 sqlite3DbFree(0, pCtx->lockProxyPath);
30791 sqlite3_free(pCtx->conchFilePath);
30792 sqlite3DbFree(0, pCtx->dbPath);
30793 /* restore the original locking context and pMethod then close it */
30794 pFile->lockingContext = pCtx->oldLockingContext;
30795 pFile->pMethod = pCtx->pOldMethod;
30796 sqlite3_free(pCtx);
30797 return pFile->pMethod->xClose(id);
30799 return SQLITE_OK;
30804 #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
30806 ** The proxy locking style is intended for use with AFP filesystems.
30807 ** And since AFP is only supported on MacOSX, the proxy locking is also
30808 ** restricted to MacOSX.
30811 ******************* End of the proxy lock implementation **********************
30812 ******************************************************************************/
30815 ** Initialize the operating system interface.
30817 ** This routine registers all VFS implementations for unix-like operating
30818 ** systems. This routine, and the sqlite3_os_end() routine that follows,
30819 ** should be the only routines in this file that are visible from other
30820 ** files.
30822 ** This routine is called once during SQLite initialization and by a
30823 ** single thread. The memory allocation and mutex subsystems have not
30824 ** necessarily been initialized when this routine is called, and so they
30825 ** should not be used.
30827 SQLITE_API int sqlite3_os_init(void){
30829 ** The following macro defines an initializer for an sqlite3_vfs object.
30830 ** The name of the VFS is NAME. The pAppData is a pointer to a pointer
30831 ** to the "finder" function. (pAppData is a pointer to a pointer because
30832 ** silly C90 rules prohibit a void* from being cast to a function pointer
30833 ** and so we have to go through the intermediate pointer to avoid problems
30834 ** when compiling with -pedantic-errors on GCC.)
30836 ** The FINDER parameter to this macro is the name of the pointer to the
30837 ** finder-function. The finder-function returns a pointer to the
30838 ** sqlite_io_methods object that implements the desired locking
30839 ** behaviors. See the division above that contains the IOMETHODS
30840 ** macro for addition information on finder-functions.
30842 ** Most finders simply return a pointer to a fixed sqlite3_io_methods
30843 ** object. But the "autolockIoFinder" available on MacOSX does a little
30844 ** more than that; it looks at the filesystem type that hosts the
30845 ** database file and tries to choose an locking method appropriate for
30846 ** that filesystem time.
30848 #define UNIXVFS(VFSNAME, FINDER) { \
30849 3, /* iVersion */ \
30850 sizeof(unixFile), /* szOsFile */ \
30851 MAX_PATHNAME, /* mxPathname */ \
30852 0, /* pNext */ \
30853 VFSNAME, /* zName */ \
30854 (void*)&FINDER, /* pAppData */ \
30855 unixOpen, /* xOpen */ \
30856 unixDelete, /* xDelete */ \
30857 unixAccess, /* xAccess */ \
30858 unixFullPathname, /* xFullPathname */ \
30859 unixDlOpen, /* xDlOpen */ \
30860 unixDlError, /* xDlError */ \
30861 unixDlSym, /* xDlSym */ \
30862 unixDlClose, /* xDlClose */ \
30863 unixRandomness, /* xRandomness */ \
30864 unixSleep, /* xSleep */ \
30865 unixCurrentTime, /* xCurrentTime */ \
30866 unixGetLastError, /* xGetLastError */ \
30867 unixCurrentTimeInt64, /* xCurrentTimeInt64 */ \
30868 unixSetSystemCall, /* xSetSystemCall */ \
30869 unixGetSystemCall, /* xGetSystemCall */ \
30870 unixNextSystemCall, /* xNextSystemCall */ \
30874 ** All default VFSes for unix are contained in the following array.
30876 ** Note that the sqlite3_vfs.pNext field of the VFS object is modified
30877 ** by the SQLite core when the VFS is registered. So the following
30878 ** array cannot be const.
30880 static sqlite3_vfs aVfs[] = {
30881 #if SQLITE_ENABLE_LOCKING_STYLE && (OS_VXWORKS || defined(__APPLE__))
30882 UNIXVFS("unix", autolockIoFinder ),
30883 #else
30884 UNIXVFS("unix", posixIoFinder ),
30885 #endif
30886 UNIXVFS("unix-none", nolockIoFinder ),
30887 UNIXVFS("unix-dotfile", dotlockIoFinder ),
30888 UNIXVFS("unix-excl", posixIoFinder ),
30889 #if OS_VXWORKS
30890 UNIXVFS("unix-namedsem", semIoFinder ),
30891 #endif
30892 #if SQLITE_ENABLE_LOCKING_STYLE
30893 UNIXVFS("unix-posix", posixIoFinder ),
30894 #if !OS_VXWORKS
30895 UNIXVFS("unix-flock", flockIoFinder ),
30896 #endif
30897 #endif
30898 #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
30899 UNIXVFS("unix-afp", afpIoFinder ),
30900 UNIXVFS("unix-nfs", nfsIoFinder ),
30901 UNIXVFS("unix-proxy", proxyIoFinder ),
30902 #endif
30904 unsigned int i; /* Loop counter */
30906 /* Double-check that the aSyscall[] array has been constructed
30907 ** correctly. See ticket [bb3a86e890c8e96ab] */
30908 assert( ArraySize(aSyscall)==18 );
30910 /* Register all VFSes defined in the aVfs[] array */
30911 for(i=0; i<(sizeof(aVfs)/sizeof(sqlite3_vfs)); i++){
30912 sqlite3_vfs_register(&aVfs[i], i==0);
30914 return SQLITE_OK;
30918 ** Shutdown the operating system interface.
30920 ** Some operating systems might need to do some cleanup in this routine,
30921 ** to release dynamically allocated objects. But not on unix.
30922 ** This routine is a no-op for unix.
30924 SQLITE_API int sqlite3_os_end(void){
30925 return SQLITE_OK;
30928 #endif /* SQLITE_OS_UNIX */
30930 /************** End of os_unix.c *********************************************/
30931 /************** Begin file os_win.c ******************************************/
30933 ** 2004 May 22
30935 ** The author disclaims copyright to this source code. In place of
30936 ** a legal notice, here is a blessing:
30938 ** May you do good and not evil.
30939 ** May you find forgiveness for yourself and forgive others.
30940 ** May you share freely, never taking more than you give.
30942 ******************************************************************************
30944 ** This file contains code that is specific to windows.
30946 #if SQLITE_OS_WIN /* This file is used for windows only */
30950 ** A Note About Memory Allocation:
30952 ** This driver uses malloc()/free() directly rather than going through
30953 ** the SQLite-wrappers sqlite3_malloc()/sqlite3_free(). Those wrappers
30954 ** are designed for use on embedded systems where memory is scarce and
30955 ** malloc failures happen frequently. Win32 does not typically run on
30956 ** embedded systems, and when it does the developers normally have bigger
30957 ** problems to worry about than running out of memory. So there is not
30958 ** a compelling need to use the wrappers.
30960 ** But there is a good reason to not use the wrappers. If we use the
30961 ** wrappers then we will get simulated malloc() failures within this
30962 ** driver. And that causes all kinds of problems for our tests. We
30963 ** could enhance SQLite to deal with simulated malloc failures within
30964 ** the OS driver, but the code to deal with those failure would not
30965 ** be exercised on Linux (which does not need to malloc() in the driver)
30966 ** and so we would have difficulty writing coverage tests for that
30967 ** code. Better to leave the code out, we think.
30969 ** The point of this discussion is as follows: When creating a new
30970 ** OS layer for an embedded system, if you use this file as an example,
30971 ** avoid the use of malloc()/free(). Those routines work ok on windows
30972 ** desktops but not so well in embedded systems.
30975 #include <winbase.h>
30977 #ifdef __CYGWIN__
30978 # include <sys/cygwin.h>
30979 #endif
30982 ** Macros used to determine whether or not to use threads.
30984 #if defined(THREADSAFE) && THREADSAFE
30985 # define SQLITE_W32_THREADS 1
30986 #endif
30989 ** Include code that is common to all os_*.c files
30991 /************** Include os_common.h in the middle of os_win.c ****************/
30992 /************** Begin file os_common.h ***************************************/
30994 ** 2004 May 22
30996 ** The author disclaims copyright to this source code. In place of
30997 ** a legal notice, here is a blessing:
30999 ** May you do good and not evil.
31000 ** May you find forgiveness for yourself and forgive others.
31001 ** May you share freely, never taking more than you give.
31003 ******************************************************************************
31005 ** This file contains macros and a little bit of code that is common to
31006 ** all of the platform-specific files (os_*.c) and is #included into those
31007 ** files.
31009 ** This file should be #included by the os_*.c files only. It is not a
31010 ** general purpose header file.
31012 #ifndef _OS_COMMON_H_
31013 #define _OS_COMMON_H_
31016 ** At least two bugs have slipped in because we changed the MEMORY_DEBUG
31017 ** macro to SQLITE_DEBUG and some older makefiles have not yet made the
31018 ** switch. The following code should catch this problem at compile-time.
31020 #ifdef MEMORY_DEBUG
31021 # error "The MEMORY_DEBUG macro is obsolete. Use SQLITE_DEBUG instead."
31022 #endif
31024 #ifdef SQLITE_DEBUG
31025 SQLITE_PRIVATE int sqlite3OSTrace = 0;
31026 #define OSTRACE(X) if( sqlite3OSTrace ) sqlite3DebugPrintf X
31027 #else
31028 #define OSTRACE(X)
31029 #endif
31032 ** Macros for performance tracing. Normally turned off. Only works
31033 ** on i486 hardware.
31035 #ifdef SQLITE_PERFORMANCE_TRACE
31038 ** hwtime.h contains inline assembler code for implementing
31039 ** high-performance timing routines.
31041 /************** Include hwtime.h in the middle of os_common.h ****************/
31042 /************** Begin file hwtime.h ******************************************/
31044 ** 2008 May 27
31046 ** The author disclaims copyright to this source code. In place of
31047 ** a legal notice, here is a blessing:
31049 ** May you do good and not evil.
31050 ** May you find forgiveness for yourself and forgive others.
31051 ** May you share freely, never taking more than you give.
31053 ******************************************************************************
31055 ** This file contains inline asm code for retrieving "high-performance"
31056 ** counters for x86 class CPUs.
31058 #ifndef _HWTIME_H_
31059 #define _HWTIME_H_
31062 ** The following routine only works on pentium-class (or newer) processors.
31063 ** It uses the RDTSC opcode to read the cycle count value out of the
31064 ** processor and returns that value. This can be used for high-res
31065 ** profiling.
31067 #if (defined(__GNUC__) || defined(_MSC_VER)) && \
31068 (defined(i386) || defined(__i386__) || defined(_M_IX86))
31070 #if defined(__GNUC__)
31072 __inline__ sqlite_uint64 sqlite3Hwtime(void){
31073 unsigned int lo, hi;
31074 __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
31075 return (sqlite_uint64)hi << 32 | lo;
31078 #elif defined(_MSC_VER)
31080 __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
31081 __asm {
31082 rdtsc
31083 ret ; return value at EDX:EAX
31087 #endif
31089 #elif (defined(__GNUC__) && defined(__x86_64__))
31091 __inline__ sqlite_uint64 sqlite3Hwtime(void){
31092 unsigned long val;
31093 __asm__ __volatile__ ("rdtsc" : "=A" (val));
31094 return val;
31097 #elif (defined(__GNUC__) && defined(__ppc__))
31099 __inline__ sqlite_uint64 sqlite3Hwtime(void){
31100 unsigned long long retval;
31101 unsigned long junk;
31102 __asm__ __volatile__ ("\n\
31103 1: mftbu %1\n\
31104 mftb %L0\n\
31105 mftbu %0\n\
31106 cmpw %0,%1\n\
31107 bne 1b"
31108 : "=r" (retval), "=r" (junk));
31109 return retval;
31112 #else
31114 #error Need implementation of sqlite3Hwtime() for your platform.
31117 ** To compile without implementing sqlite3Hwtime() for your platform,
31118 ** you can remove the above #error and use the following
31119 ** stub function. You will lose timing support for many
31120 ** of the debugging and testing utilities, but it should at
31121 ** least compile and run.
31123 SQLITE_PRIVATE sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
31125 #endif
31127 #endif /* !defined(_HWTIME_H_) */
31129 /************** End of hwtime.h **********************************************/
31130 /************** Continuing where we left off in os_common.h ******************/
31132 static sqlite_uint64 g_start;
31133 static sqlite_uint64 g_elapsed;
31134 #define TIMER_START g_start=sqlite3Hwtime()
31135 #define TIMER_END g_elapsed=sqlite3Hwtime()-g_start
31136 #define TIMER_ELAPSED g_elapsed
31137 #else
31138 #define TIMER_START
31139 #define TIMER_END
31140 #define TIMER_ELAPSED ((sqlite_uint64)0)
31141 #endif
31144 ** If we compile with the SQLITE_TEST macro set, then the following block
31145 ** of code will give us the ability to simulate a disk I/O error. This
31146 ** is used for testing the I/O recovery logic.
31148 #ifdef SQLITE_TEST
31149 SQLITE_API int sqlite3_io_error_hit = 0; /* Total number of I/O Errors */
31150 SQLITE_API int sqlite3_io_error_hardhit = 0; /* Number of non-benign errors */
31151 SQLITE_API int sqlite3_io_error_pending = 0; /* Count down to first I/O error */
31152 SQLITE_API int sqlite3_io_error_persist = 0; /* True if I/O errors persist */
31153 SQLITE_API int sqlite3_io_error_benign = 0; /* True if errors are benign */
31154 SQLITE_API int sqlite3_diskfull_pending = 0;
31155 SQLITE_API int sqlite3_diskfull = 0;
31156 #define SimulateIOErrorBenign(X) sqlite3_io_error_benign=(X)
31157 #define SimulateIOError(CODE) \
31158 if( (sqlite3_io_error_persist && sqlite3_io_error_hit) \
31159 || sqlite3_io_error_pending-- == 1 ) \
31160 { local_ioerr(); CODE; }
31161 static void local_ioerr(){
31162 IOTRACE(("IOERR\n"));
31163 sqlite3_io_error_hit++;
31164 if( !sqlite3_io_error_benign ) sqlite3_io_error_hardhit++;
31166 #define SimulateDiskfullError(CODE) \
31167 if( sqlite3_diskfull_pending ){ \
31168 if( sqlite3_diskfull_pending == 1 ){ \
31169 local_ioerr(); \
31170 sqlite3_diskfull = 1; \
31171 sqlite3_io_error_hit = 1; \
31172 CODE; \
31173 }else{ \
31174 sqlite3_diskfull_pending--; \
31177 #else
31178 #define SimulateIOErrorBenign(X)
31179 #define SimulateIOError(A)
31180 #define SimulateDiskfullError(A)
31181 #endif
31184 ** When testing, keep a count of the number of open files.
31186 #ifdef SQLITE_TEST
31187 SQLITE_API int sqlite3_open_file_count = 0;
31188 #define OpenCounter(X) sqlite3_open_file_count+=(X)
31189 #else
31190 #define OpenCounter(X)
31191 #endif
31193 #endif /* !defined(_OS_COMMON_H_) */
31195 /************** End of os_common.h *******************************************/
31196 /************** Continuing where we left off in os_win.c *********************/
31199 ** Some microsoft compilers lack this definition.
31201 #ifndef INVALID_FILE_ATTRIBUTES
31202 # define INVALID_FILE_ATTRIBUTES ((DWORD)-1)
31203 #endif
31206 ** Determine if we are dealing with WindowsCE - which has a much
31207 ** reduced API.
31209 #if SQLITE_OS_WINCE
31210 # define AreFileApisANSI() 1
31211 # define FormatMessageW(a,b,c,d,e,f,g) 0
31212 #endif
31214 /* Forward references */
31215 typedef struct winShm winShm; /* A connection to shared-memory */
31216 typedef struct winShmNode winShmNode; /* A region of shared-memory */
31219 ** WinCE lacks native support for file locking so we have to fake it
31220 ** with some code of our own.
31222 #if SQLITE_OS_WINCE
31223 typedef struct winceLock {
31224 int nReaders; /* Number of reader locks obtained */
31225 BOOL bPending; /* Indicates a pending lock has been obtained */
31226 BOOL bReserved; /* Indicates a reserved lock has been obtained */
31227 BOOL bExclusive; /* Indicates an exclusive lock has been obtained */
31228 } winceLock;
31229 #endif
31232 ** The winFile structure is a subclass of sqlite3_file* specific to the win32
31233 ** portability layer.
31235 typedef struct winFile winFile;
31236 struct winFile {
31237 const sqlite3_io_methods *pMethod; /*** Must be first ***/
31238 sqlite3_vfs *pVfs; /* The VFS used to open this file */
31239 HANDLE h; /* Handle for accessing the file */
31240 unsigned char locktype; /* Type of lock currently held on this file */
31241 short sharedLockByte; /* Randomly chosen byte used as a shared lock */
31242 DWORD lastErrno; /* The Windows errno from the last I/O error */
31243 DWORD sectorSize; /* Sector size of the device file is on */
31244 winShm *pShm; /* Instance of shared memory on this file */
31245 const char *zPath; /* Full pathname of this file */
31246 int szChunk; /* Chunk size configured by FCNTL_CHUNK_SIZE */
31247 #if SQLITE_OS_WINCE
31248 WCHAR *zDeleteOnClose; /* Name of file to delete when closing */
31249 HANDLE hMutex; /* Mutex used to control access to shared lock */
31250 HANDLE hShared; /* Shared memory segment used for locking */
31251 winceLock local; /* Locks obtained by this instance of winFile */
31252 winceLock *shared; /* Global shared lock memory for the file */
31253 #endif
31257 ** Forward prototypes.
31259 static int getSectorSize(
31260 sqlite3_vfs *pVfs,
31261 const char *zRelative /* UTF-8 file name */
31265 ** The following variable is (normally) set once and never changes
31266 ** thereafter. It records whether the operating system is Win95
31267 ** or WinNT.
31269 ** 0: Operating system unknown.
31270 ** 1: Operating system is Win95.
31271 ** 2: Operating system is WinNT.
31273 ** In order to facilitate testing on a WinNT system, the test fixture
31274 ** can manually set this value to 1 to emulate Win98 behavior.
31276 #ifdef SQLITE_TEST
31277 SQLITE_API int sqlite3_os_type = 0;
31278 #else
31279 static int sqlite3_os_type = 0;
31280 #endif
31283 ** Return true (non-zero) if we are running under WinNT, Win2K, WinXP,
31284 ** or WinCE. Return false (zero) for Win95, Win98, or WinME.
31286 ** Here is an interesting observation: Win95, Win98, and WinME lack
31287 ** the LockFileEx() API. But we can still statically link against that
31288 ** API as long as we don't call it when running Win95/98/ME. A call to
31289 ** this routine is used to determine if the host is Win95/98/ME or
31290 ** WinNT/2K/XP so that we will know whether or not we can safely call
31291 ** the LockFileEx() API.
31293 #if SQLITE_OS_WINCE
31294 # define isNT() (1)
31295 #else
31296 static int isNT(void){
31297 if( sqlite3_os_type==0 ){
31298 OSVERSIONINFO sInfo;
31299 sInfo.dwOSVersionInfoSize = sizeof(sInfo);
31300 GetVersionEx(&sInfo);
31301 sqlite3_os_type = sInfo.dwPlatformId==VER_PLATFORM_WIN32_NT ? 2 : 1;
31303 return sqlite3_os_type==2;
31305 #endif /* SQLITE_OS_WINCE */
31308 ** Convert a UTF-8 string to microsoft unicode (UTF-16?).
31310 ** Space to hold the returned string is obtained from malloc.
31312 static WCHAR *utf8ToUnicode(const char *zFilename){
31313 int nChar;
31314 WCHAR *zWideFilename;
31316 nChar = MultiByteToWideChar(CP_UTF8, 0, zFilename, -1, NULL, 0);
31317 zWideFilename = malloc( nChar*sizeof(zWideFilename[0]) );
31318 if( zWideFilename==0 ){
31319 return 0;
31321 nChar = MultiByteToWideChar(CP_UTF8, 0, zFilename, -1, zWideFilename, nChar);
31322 if( nChar==0 ){
31323 free(zWideFilename);
31324 zWideFilename = 0;
31326 return zWideFilename;
31330 ** Convert microsoft unicode to UTF-8. Space to hold the returned string is
31331 ** obtained from malloc().
31333 static char *unicodeToUtf8(const WCHAR *zWideFilename){
31334 int nByte;
31335 char *zFilename;
31337 nByte = WideCharToMultiByte(CP_UTF8, 0, zWideFilename, -1, 0, 0, 0, 0);
31338 zFilename = malloc( nByte );
31339 if( zFilename==0 ){
31340 return 0;
31342 nByte = WideCharToMultiByte(CP_UTF8, 0, zWideFilename, -1, zFilename, nByte,
31343 0, 0);
31344 if( nByte == 0 ){
31345 free(zFilename);
31346 zFilename = 0;
31348 return zFilename;
31352 ** Convert an ansi string to microsoft unicode, based on the
31353 ** current codepage settings for file apis.
31355 ** Space to hold the returned string is obtained
31356 ** from malloc.
31358 static WCHAR *mbcsToUnicode(const char *zFilename){
31359 int nByte;
31360 WCHAR *zMbcsFilename;
31361 int codepage = AreFileApisANSI() ? CP_ACP : CP_OEMCP;
31363 nByte = MultiByteToWideChar(codepage, 0, zFilename, -1, NULL,0)*sizeof(WCHAR);
31364 zMbcsFilename = malloc( nByte*sizeof(zMbcsFilename[0]) );
31365 if( zMbcsFilename==0 ){
31366 return 0;
31368 nByte = MultiByteToWideChar(codepage, 0, zFilename, -1, zMbcsFilename, nByte);
31369 if( nByte==0 ){
31370 free(zMbcsFilename);
31371 zMbcsFilename = 0;
31373 return zMbcsFilename;
31377 ** Convert microsoft unicode to multibyte character string, based on the
31378 ** user's Ansi codepage.
31380 ** Space to hold the returned string is obtained from
31381 ** malloc().
31383 static char *unicodeToMbcs(const WCHAR *zWideFilename){
31384 int nByte;
31385 char *zFilename;
31386 int codepage = AreFileApisANSI() ? CP_ACP : CP_OEMCP;
31388 nByte = WideCharToMultiByte(codepage, 0, zWideFilename, -1, 0, 0, 0, 0);
31389 zFilename = malloc( nByte );
31390 if( zFilename==0 ){
31391 return 0;
31393 nByte = WideCharToMultiByte(codepage, 0, zWideFilename, -1, zFilename, nByte,
31394 0, 0);
31395 if( nByte == 0 ){
31396 free(zFilename);
31397 zFilename = 0;
31399 return zFilename;
31403 ** Convert multibyte character string to UTF-8. Space to hold the
31404 ** returned string is obtained from malloc().
31406 SQLITE_API char *sqlite3_win32_mbcs_to_utf8(const char *zFilename){
31407 char *zFilenameUtf8;
31408 WCHAR *zTmpWide;
31410 zTmpWide = mbcsToUnicode(zFilename);
31411 if( zTmpWide==0 ){
31412 return 0;
31414 zFilenameUtf8 = unicodeToUtf8(zTmpWide);
31415 free(zTmpWide);
31416 return zFilenameUtf8;
31420 ** Convert UTF-8 to multibyte character string. Space to hold the
31421 ** returned string is obtained from malloc().
31423 static char *utf8ToMbcs(const char *zFilename){
31424 char *zFilenameMbcs;
31425 WCHAR *zTmpWide;
31427 zTmpWide = utf8ToUnicode(zFilename);
31428 if( zTmpWide==0 ){
31429 return 0;
31431 zFilenameMbcs = unicodeToMbcs(zTmpWide);
31432 free(zTmpWide);
31433 return zFilenameMbcs;
31436 #if SQLITE_OS_WINCE
31437 /*************************************************************************
31438 ** This section contains code for WinCE only.
31441 ** WindowsCE does not have a localtime() function. So create a
31442 ** substitute.
31444 struct tm *__cdecl localtime(const time_t *t)
31446 static struct tm y;
31447 FILETIME uTm, lTm;
31448 SYSTEMTIME pTm;
31449 sqlite3_int64 t64;
31450 t64 = *t;
31451 t64 = (t64 + 11644473600)*10000000;
31452 uTm.dwLowDateTime = (DWORD)(t64 & 0xFFFFFFFF);
31453 uTm.dwHighDateTime= (DWORD)(t64 >> 32);
31454 FileTimeToLocalFileTime(&uTm,&lTm);
31455 FileTimeToSystemTime(&lTm,&pTm);
31456 y.tm_year = pTm.wYear - 1900;
31457 y.tm_mon = pTm.wMonth - 1;
31458 y.tm_wday = pTm.wDayOfWeek;
31459 y.tm_mday = pTm.wDay;
31460 y.tm_hour = pTm.wHour;
31461 y.tm_min = pTm.wMinute;
31462 y.tm_sec = pTm.wSecond;
31463 return &y;
31466 /* This will never be called, but defined to make the code compile */
31467 #define GetTempPathA(a,b)
31469 #define LockFile(a,b,c,d,e) winceLockFile(&a, b, c, d, e)
31470 #define UnlockFile(a,b,c,d,e) winceUnlockFile(&a, b, c, d, e)
31471 #define LockFileEx(a,b,c,d,e,f) winceLockFileEx(&a, b, c, d, e, f)
31473 #define HANDLE_TO_WINFILE(a) (winFile*)&((char*)a)[-(int)offsetof(winFile,h)]
31476 ** Acquire a lock on the handle h
31478 static void winceMutexAcquire(HANDLE h){
31479 DWORD dwErr;
31480 do {
31481 dwErr = WaitForSingleObject(h, INFINITE);
31482 } while (dwErr != WAIT_OBJECT_0 && dwErr != WAIT_ABANDONED);
31485 ** Release a lock acquired by winceMutexAcquire()
31487 #define winceMutexRelease(h) ReleaseMutex(h)
31490 ** Create the mutex and shared memory used for locking in the file
31491 ** descriptor pFile
31493 static BOOL winceCreateLock(const char *zFilename, winFile *pFile){
31494 WCHAR *zTok;
31495 WCHAR *zName = utf8ToUnicode(zFilename);
31496 BOOL bInit = TRUE;
31498 /* Initialize the local lockdata */
31499 ZeroMemory(&pFile->local, sizeof(pFile->local));
31501 /* Replace the backslashes from the filename and lowercase it
31502 ** to derive a mutex name. */
31503 zTok = CharLowerW(zName);
31504 for (;*zTok;zTok++){
31505 if (*zTok == '\\') *zTok = '_';
31508 /* Create/open the named mutex */
31509 pFile->hMutex = CreateMutexW(NULL, FALSE, zName);
31510 if (!pFile->hMutex){
31511 pFile->lastErrno = GetLastError();
31512 free(zName);
31513 return FALSE;
31516 /* Acquire the mutex before continuing */
31517 winceMutexAcquire(pFile->hMutex);
31519 /* Since the names of named mutexes, semaphores, file mappings etc are
31520 ** case-sensitive, take advantage of that by uppercasing the mutex name
31521 ** and using that as the shared filemapping name.
31523 CharUpperW(zName);
31524 pFile->hShared = CreateFileMappingW(INVALID_HANDLE_VALUE, NULL,
31525 PAGE_READWRITE, 0, sizeof(winceLock),
31526 zName);
31528 /* Set a flag that indicates we're the first to create the memory so it
31529 ** must be zero-initialized */
31530 if (GetLastError() == ERROR_ALREADY_EXISTS){
31531 bInit = FALSE;
31534 free(zName);
31536 /* If we succeeded in making the shared memory handle, map it. */
31537 if (pFile->hShared){
31538 pFile->shared = (winceLock*)MapViewOfFile(pFile->hShared,
31539 FILE_MAP_READ|FILE_MAP_WRITE, 0, 0, sizeof(winceLock));
31540 /* If mapping failed, close the shared memory handle and erase it */
31541 if (!pFile->shared){
31542 pFile->lastErrno = GetLastError();
31543 CloseHandle(pFile->hShared);
31544 pFile->hShared = NULL;
31548 /* If shared memory could not be created, then close the mutex and fail */
31549 if (pFile->hShared == NULL){
31550 winceMutexRelease(pFile->hMutex);
31551 CloseHandle(pFile->hMutex);
31552 pFile->hMutex = NULL;
31553 return FALSE;
31556 /* Initialize the shared memory if we're supposed to */
31557 if (bInit) {
31558 ZeroMemory(pFile->shared, sizeof(winceLock));
31561 winceMutexRelease(pFile->hMutex);
31562 return TRUE;
31566 ** Destroy the part of winFile that deals with wince locks
31568 static void winceDestroyLock(winFile *pFile){
31569 if (pFile->hMutex){
31570 /* Acquire the mutex */
31571 winceMutexAcquire(pFile->hMutex);
31573 /* The following blocks should probably assert in debug mode, but they
31574 are to cleanup in case any locks remained open */
31575 if (pFile->local.nReaders){
31576 pFile->shared->nReaders --;
31578 if (pFile->local.bReserved){
31579 pFile->shared->bReserved = FALSE;
31581 if (pFile->local.bPending){
31582 pFile->shared->bPending = FALSE;
31584 if (pFile->local.bExclusive){
31585 pFile->shared->bExclusive = FALSE;
31588 /* De-reference and close our copy of the shared memory handle */
31589 UnmapViewOfFile(pFile->shared);
31590 CloseHandle(pFile->hShared);
31592 /* Done with the mutex */
31593 winceMutexRelease(pFile->hMutex);
31594 CloseHandle(pFile->hMutex);
31595 pFile->hMutex = NULL;
31600 ** An implementation of the LockFile() API of windows for wince
31602 static BOOL winceLockFile(
31603 HANDLE *phFile,
31604 DWORD dwFileOffsetLow,
31605 DWORD dwFileOffsetHigh,
31606 DWORD nNumberOfBytesToLockLow,
31607 DWORD nNumberOfBytesToLockHigh
31609 winFile *pFile = HANDLE_TO_WINFILE(phFile);
31610 BOOL bReturn = FALSE;
31612 UNUSED_PARAMETER(dwFileOffsetHigh);
31613 UNUSED_PARAMETER(nNumberOfBytesToLockHigh);
31615 if (!pFile->hMutex) return TRUE;
31616 winceMutexAcquire(pFile->hMutex);
31618 /* Wanting an exclusive lock? */
31619 if (dwFileOffsetLow == (DWORD)SHARED_FIRST
31620 && nNumberOfBytesToLockLow == (DWORD)SHARED_SIZE){
31621 if (pFile->shared->nReaders == 0 && pFile->shared->bExclusive == 0){
31622 pFile->shared->bExclusive = TRUE;
31623 pFile->local.bExclusive = TRUE;
31624 bReturn = TRUE;
31628 /* Want a read-only lock? */
31629 else if (dwFileOffsetLow == (DWORD)SHARED_FIRST &&
31630 nNumberOfBytesToLockLow == 1){
31631 if (pFile->shared->bExclusive == 0){
31632 pFile->local.nReaders ++;
31633 if (pFile->local.nReaders == 1){
31634 pFile->shared->nReaders ++;
31636 bReturn = TRUE;
31640 /* Want a pending lock? */
31641 else if (dwFileOffsetLow == (DWORD)PENDING_BYTE && nNumberOfBytesToLockLow == 1){
31642 /* If no pending lock has been acquired, then acquire it */
31643 if (pFile->shared->bPending == 0) {
31644 pFile->shared->bPending = TRUE;
31645 pFile->local.bPending = TRUE;
31646 bReturn = TRUE;
31650 /* Want a reserved lock? */
31651 else if (dwFileOffsetLow == (DWORD)RESERVED_BYTE && nNumberOfBytesToLockLow == 1){
31652 if (pFile->shared->bReserved == 0) {
31653 pFile->shared->bReserved = TRUE;
31654 pFile->local.bReserved = TRUE;
31655 bReturn = TRUE;
31659 winceMutexRelease(pFile->hMutex);
31660 return bReturn;
31664 ** An implementation of the UnlockFile API of windows for wince
31666 static BOOL winceUnlockFile(
31667 HANDLE *phFile,
31668 DWORD dwFileOffsetLow,
31669 DWORD dwFileOffsetHigh,
31670 DWORD nNumberOfBytesToUnlockLow,
31671 DWORD nNumberOfBytesToUnlockHigh
31673 winFile *pFile = HANDLE_TO_WINFILE(phFile);
31674 BOOL bReturn = FALSE;
31676 UNUSED_PARAMETER(dwFileOffsetHigh);
31677 UNUSED_PARAMETER(nNumberOfBytesToUnlockHigh);
31679 if (!pFile->hMutex) return TRUE;
31680 winceMutexAcquire(pFile->hMutex);
31682 /* Releasing a reader lock or an exclusive lock */
31683 if (dwFileOffsetLow == (DWORD)SHARED_FIRST){
31684 /* Did we have an exclusive lock? */
31685 if (pFile->local.bExclusive){
31686 assert(nNumberOfBytesToUnlockLow == (DWORD)SHARED_SIZE);
31687 pFile->local.bExclusive = FALSE;
31688 pFile->shared->bExclusive = FALSE;
31689 bReturn = TRUE;
31692 /* Did we just have a reader lock? */
31693 else if (pFile->local.nReaders){
31694 assert(nNumberOfBytesToUnlockLow == (DWORD)SHARED_SIZE || nNumberOfBytesToUnlockLow == 1);
31695 pFile->local.nReaders --;
31696 if (pFile->local.nReaders == 0)
31698 pFile->shared->nReaders --;
31700 bReturn = TRUE;
31704 /* Releasing a pending lock */
31705 else if (dwFileOffsetLow == (DWORD)PENDING_BYTE && nNumberOfBytesToUnlockLow == 1){
31706 if (pFile->local.bPending){
31707 pFile->local.bPending = FALSE;
31708 pFile->shared->bPending = FALSE;
31709 bReturn = TRUE;
31712 /* Releasing a reserved lock */
31713 else if (dwFileOffsetLow == (DWORD)RESERVED_BYTE && nNumberOfBytesToUnlockLow == 1){
31714 if (pFile->local.bReserved) {
31715 pFile->local.bReserved = FALSE;
31716 pFile->shared->bReserved = FALSE;
31717 bReturn = TRUE;
31721 winceMutexRelease(pFile->hMutex);
31722 return bReturn;
31726 ** An implementation of the LockFileEx() API of windows for wince
31728 static BOOL winceLockFileEx(
31729 HANDLE *phFile,
31730 DWORD dwFlags,
31731 DWORD dwReserved,
31732 DWORD nNumberOfBytesToLockLow,
31733 DWORD nNumberOfBytesToLockHigh,
31734 LPOVERLAPPED lpOverlapped
31736 UNUSED_PARAMETER(dwReserved);
31737 UNUSED_PARAMETER(nNumberOfBytesToLockHigh);
31739 /* If the caller wants a shared read lock, forward this call
31740 ** to winceLockFile */
31741 if (lpOverlapped->Offset == (DWORD)SHARED_FIRST &&
31742 dwFlags == 1 &&
31743 nNumberOfBytesToLockLow == (DWORD)SHARED_SIZE){
31744 return winceLockFile(phFile, SHARED_FIRST, 0, 1, 0);
31746 return FALSE;
31749 ** End of the special code for wince
31750 *****************************************************************************/
31751 #endif /* SQLITE_OS_WINCE */
31753 /*****************************************************************************
31754 ** The next group of routines implement the I/O methods specified
31755 ** by the sqlite3_io_methods object.
31756 ******************************************************************************/
31759 ** Some microsoft compilers lack this definition.
31761 #ifndef INVALID_SET_FILE_POINTER
31762 # define INVALID_SET_FILE_POINTER ((DWORD)-1)
31763 #endif
31766 ** Move the current position of the file handle passed as the first
31767 ** argument to offset iOffset within the file. If successful, return 0.
31768 ** Otherwise, set pFile->lastErrno and return non-zero.
31770 static int seekWinFile(winFile *pFile, sqlite3_int64 iOffset){
31771 LONG upperBits; /* Most sig. 32 bits of new offset */
31772 LONG lowerBits; /* Least sig. 32 bits of new offset */
31773 DWORD dwRet; /* Value returned by SetFilePointer() */
31775 upperBits = (LONG)((iOffset>>32) & 0x7fffffff);
31776 lowerBits = (LONG)(iOffset & 0xffffffff);
31778 /* API oddity: If successful, SetFilePointer() returns a dword
31779 ** containing the lower 32-bits of the new file-offset. Or, if it fails,
31780 ** it returns INVALID_SET_FILE_POINTER. However according to MSDN,
31781 ** INVALID_SET_FILE_POINTER may also be a valid new offset. So to determine
31782 ** whether an error has actually occured, it is also necessary to call
31783 ** GetLastError().
31785 dwRet = SetFilePointer(pFile->h, lowerBits, &upperBits, FILE_BEGIN);
31786 if( (dwRet==INVALID_SET_FILE_POINTER && GetLastError()!=NO_ERROR) ){
31787 pFile->lastErrno = GetLastError();
31788 return 1;
31791 return 0;
31795 ** Close a file.
31797 ** It is reported that an attempt to close a handle might sometimes
31798 ** fail. This is a very unreasonable result, but windows is notorious
31799 ** for being unreasonable so I do not doubt that it might happen. If
31800 ** the close fails, we pause for 100 milliseconds and try again. As
31801 ** many as MX_CLOSE_ATTEMPT attempts to close the handle are made before
31802 ** giving up and returning an error.
31804 #define MX_CLOSE_ATTEMPT 3
31805 static int winClose(sqlite3_file *id){
31806 int rc, cnt = 0;
31807 winFile *pFile = (winFile*)id;
31809 assert( id!=0 );
31810 assert( pFile->pShm==0 );
31811 OSTRACE(("CLOSE %d\n", pFile->h));
31813 rc = CloseHandle(pFile->h);
31814 /* SimulateIOError( rc=0; cnt=MX_CLOSE_ATTEMPT; ); */
31815 }while( rc==0 && ++cnt < MX_CLOSE_ATTEMPT && (Sleep(100), 1) );
31816 #if SQLITE_OS_WINCE
31817 #define WINCE_DELETION_ATTEMPTS 3
31818 winceDestroyLock(pFile);
31819 if( pFile->zDeleteOnClose ){
31820 int cnt = 0;
31821 while(
31822 DeleteFileW(pFile->zDeleteOnClose)==0
31823 && GetFileAttributesW(pFile->zDeleteOnClose)!=0xffffffff
31824 && cnt++ < WINCE_DELETION_ATTEMPTS
31826 Sleep(100); /* Wait a little before trying again */
31828 free(pFile->zDeleteOnClose);
31830 #endif
31831 OSTRACE(("CLOSE %d %s\n", pFile->h, rc ? "ok" : "failed"));
31832 OpenCounter(-1);
31833 return rc ? SQLITE_OK : SQLITE_IOERR;
31837 ** Read data from a file into a buffer. Return SQLITE_OK if all
31838 ** bytes were read successfully and SQLITE_IOERR if anything goes
31839 ** wrong.
31841 static int winRead(
31842 sqlite3_file *id, /* File to read from */
31843 void *pBuf, /* Write content into this buffer */
31844 int amt, /* Number of bytes to read */
31845 sqlite3_int64 offset /* Begin reading at this offset */
31847 winFile *pFile = (winFile*)id; /* file handle */
31848 DWORD nRead; /* Number of bytes actually read from file */
31850 assert( id!=0 );
31851 SimulateIOError(return SQLITE_IOERR_READ);
31852 OSTRACE(("READ %d lock=%d\n", pFile->h, pFile->locktype));
31854 if( seekWinFile(pFile, offset) ){
31855 return SQLITE_FULL;
31857 if( !ReadFile(pFile->h, pBuf, amt, &nRead, 0) ){
31858 pFile->lastErrno = GetLastError();
31859 return SQLITE_IOERR_READ;
31861 if( nRead<(DWORD)amt ){
31862 /* Unread parts of the buffer must be zero-filled */
31863 memset(&((char*)pBuf)[nRead], 0, amt-nRead);
31864 return SQLITE_IOERR_SHORT_READ;
31867 return SQLITE_OK;
31871 ** Write data from a buffer into a file. Return SQLITE_OK on success
31872 ** or some other error code on failure.
31874 static int winWrite(
31875 sqlite3_file *id, /* File to write into */
31876 const void *pBuf, /* The bytes to be written */
31877 int amt, /* Number of bytes to write */
31878 sqlite3_int64 offset /* Offset into the file to begin writing at */
31880 int rc; /* True if error has occured, else false */
31881 winFile *pFile = (winFile*)id; /* File handle */
31883 assert( amt>0 );
31884 assert( pFile );
31885 SimulateIOError(return SQLITE_IOERR_WRITE);
31886 SimulateDiskfullError(return SQLITE_FULL);
31888 OSTRACE(("WRITE %d lock=%d\n", pFile->h, pFile->locktype));
31890 rc = seekWinFile(pFile, offset);
31891 if( rc==0 ){
31892 u8 *aRem = (u8 *)pBuf; /* Data yet to be written */
31893 int nRem = amt; /* Number of bytes yet to be written */
31894 DWORD nWrite; /* Bytes written by each WriteFile() call */
31896 while( nRem>0 && WriteFile(pFile->h, aRem, nRem, &nWrite, 0) && nWrite>0 ){
31897 aRem += nWrite;
31898 nRem -= nWrite;
31900 if( nRem>0 ){
31901 pFile->lastErrno = GetLastError();
31902 rc = 1;
31906 if( rc ){
31907 if( pFile->lastErrno==ERROR_HANDLE_DISK_FULL ){
31908 return SQLITE_FULL;
31910 return SQLITE_IOERR_WRITE;
31912 return SQLITE_OK;
31916 ** Truncate an open file to a specified size
31918 static int winTruncate(sqlite3_file *id, sqlite3_int64 nByte){
31919 winFile *pFile = (winFile*)id; /* File handle object */
31920 int rc = SQLITE_OK; /* Return code for this function */
31922 assert( pFile );
31924 OSTRACE(("TRUNCATE %d %lld\n", pFile->h, nByte));
31925 SimulateIOError(return SQLITE_IOERR_TRUNCATE);
31927 /* If the user has configured a chunk-size for this file, truncate the
31928 ** file so that it consists of an integer number of chunks (i.e. the
31929 ** actual file size after the operation may be larger than the requested
31930 ** size).
31932 if( pFile->szChunk ){
31933 nByte = ((nByte + pFile->szChunk - 1)/pFile->szChunk) * pFile->szChunk;
31936 /* SetEndOfFile() returns non-zero when successful, or zero when it fails. */
31937 if( seekWinFile(pFile, nByte) ){
31938 rc = SQLITE_IOERR_TRUNCATE;
31939 }else if( 0==SetEndOfFile(pFile->h) ){
31940 pFile->lastErrno = GetLastError();
31941 rc = SQLITE_IOERR_TRUNCATE;
31944 OSTRACE(("TRUNCATE %d %lld %s\n", pFile->h, nByte, rc ? "failed" : "ok"));
31945 return rc;
31948 #ifdef SQLITE_TEST
31950 ** Count the number of fullsyncs and normal syncs. This is used to test
31951 ** that syncs and fullsyncs are occuring at the right times.
31953 SQLITE_API int sqlite3_sync_count = 0;
31954 SQLITE_API int sqlite3_fullsync_count = 0;
31955 #endif
31958 ** Make sure all writes to a particular file are committed to disk.
31960 static int winSync(sqlite3_file *id, int flags){
31961 #if !defined(NDEBUG) || !defined(SQLITE_NO_SYNC) || defined(SQLITE_DEBUG)
31962 winFile *pFile = (winFile*)id;
31963 #else
31964 UNUSED_PARAMETER(id);
31965 #endif
31967 assert( pFile );
31968 /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */
31969 assert((flags&0x0F)==SQLITE_SYNC_NORMAL
31970 || (flags&0x0F)==SQLITE_SYNC_FULL
31973 OSTRACE(("SYNC %d lock=%d\n", pFile->h, pFile->locktype));
31975 #ifndef SQLITE_TEST
31976 UNUSED_PARAMETER(flags);
31977 #else
31978 if( flags & SQLITE_SYNC_FULL ){
31979 sqlite3_fullsync_count++;
31981 sqlite3_sync_count++;
31982 #endif
31984 /* Unix cannot, but some systems may return SQLITE_FULL from here. This
31985 ** line is to test that doing so does not cause any problems.
31987 SimulateDiskfullError( return SQLITE_FULL );
31988 SimulateIOError( return SQLITE_IOERR; );
31990 /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
31991 ** no-op
31993 #ifdef SQLITE_NO_SYNC
31994 return SQLITE_OK;
31995 #else
31996 if( FlushFileBuffers(pFile->h) ){
31997 return SQLITE_OK;
31998 }else{
31999 pFile->lastErrno = GetLastError();
32000 return SQLITE_IOERR;
32002 #endif
32006 ** Determine the current size of a file in bytes
32008 static int winFileSize(sqlite3_file *id, sqlite3_int64 *pSize){
32009 DWORD upperBits;
32010 DWORD lowerBits;
32011 winFile *pFile = (winFile*)id;
32012 DWORD error;
32014 assert( id!=0 );
32015 SimulateIOError(return SQLITE_IOERR_FSTAT);
32016 lowerBits = GetFileSize(pFile->h, &upperBits);
32017 if( (lowerBits == INVALID_FILE_SIZE)
32018 && ((error = GetLastError()) != NO_ERROR) )
32020 pFile->lastErrno = error;
32021 return SQLITE_IOERR_FSTAT;
32023 *pSize = (((sqlite3_int64)upperBits)<<32) + lowerBits;
32024 return SQLITE_OK;
32028 ** LOCKFILE_FAIL_IMMEDIATELY is undefined on some Windows systems.
32030 #ifndef LOCKFILE_FAIL_IMMEDIATELY
32031 # define LOCKFILE_FAIL_IMMEDIATELY 1
32032 #endif
32035 ** Acquire a reader lock.
32036 ** Different API routines are called depending on whether or not this
32037 ** is Win95 or WinNT.
32039 static int getReadLock(winFile *pFile){
32040 int res;
32041 if( isNT() ){
32042 OVERLAPPED ovlp;
32043 ovlp.Offset = SHARED_FIRST;
32044 ovlp.OffsetHigh = 0;
32045 ovlp.hEvent = 0;
32046 res = LockFileEx(pFile->h, LOCKFILE_FAIL_IMMEDIATELY,
32047 0, SHARED_SIZE, 0, &ovlp);
32048 /* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed.
32050 #if SQLITE_OS_WINCE==0
32051 }else{
32052 int lk;
32053 sqlite3_randomness(sizeof(lk), &lk);
32054 pFile->sharedLockByte = (short)((lk & 0x7fffffff)%(SHARED_SIZE - 1));
32055 res = LockFile(pFile->h, SHARED_FIRST+pFile->sharedLockByte, 0, 1, 0);
32056 #endif
32058 if( res == 0 ){
32059 pFile->lastErrno = GetLastError();
32061 return res;
32065 ** Undo a readlock
32067 static int unlockReadLock(winFile *pFile){
32068 int res;
32069 if( isNT() ){
32070 res = UnlockFile(pFile->h, SHARED_FIRST, 0, SHARED_SIZE, 0);
32071 /* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed.
32073 #if SQLITE_OS_WINCE==0
32074 }else{
32075 res = UnlockFile(pFile->h, SHARED_FIRST + pFile->sharedLockByte, 0, 1, 0);
32076 #endif
32078 if( res == 0 ){
32079 pFile->lastErrno = GetLastError();
32081 return res;
32085 ** Lock the file with the lock specified by parameter locktype - one
32086 ** of the following:
32088 ** (1) SHARED_LOCK
32089 ** (2) RESERVED_LOCK
32090 ** (3) PENDING_LOCK
32091 ** (4) EXCLUSIVE_LOCK
32093 ** Sometimes when requesting one lock state, additional lock states
32094 ** are inserted in between. The locking might fail on one of the later
32095 ** transitions leaving the lock state different from what it started but
32096 ** still short of its goal. The following chart shows the allowed
32097 ** transitions and the inserted intermediate states:
32099 ** UNLOCKED -> SHARED
32100 ** SHARED -> RESERVED
32101 ** SHARED -> (PENDING) -> EXCLUSIVE
32102 ** RESERVED -> (PENDING) -> EXCLUSIVE
32103 ** PENDING -> EXCLUSIVE
32105 ** This routine will only increase a lock. The winUnlock() routine
32106 ** erases all locks at once and returns us immediately to locking level 0.
32107 ** It is not possible to lower the locking level one step at a time. You
32108 ** must go straight to locking level 0.
32110 static int winLock(sqlite3_file *id, int locktype){
32111 int rc = SQLITE_OK; /* Return code from subroutines */
32112 int res = 1; /* Result of a windows lock call */
32113 int newLocktype; /* Set pFile->locktype to this value before exiting */
32114 int gotPendingLock = 0;/* True if we acquired a PENDING lock this time */
32115 winFile *pFile = (winFile*)id;
32116 DWORD error = NO_ERROR;
32118 assert( id!=0 );
32119 OSTRACE(("LOCK %d %d was %d(%d)\n",
32120 pFile->h, locktype, pFile->locktype, pFile->sharedLockByte));
32122 /* If there is already a lock of this type or more restrictive on the
32123 ** OsFile, do nothing. Don't use the end_lock: exit path, as
32124 ** sqlite3OsEnterMutex() hasn't been called yet.
32126 if( pFile->locktype>=locktype ){
32127 return SQLITE_OK;
32130 /* Make sure the locking sequence is correct
32132 assert( pFile->locktype!=NO_LOCK || locktype==SHARED_LOCK );
32133 assert( locktype!=PENDING_LOCK );
32134 assert( locktype!=RESERVED_LOCK || pFile->locktype==SHARED_LOCK );
32136 /* Lock the PENDING_LOCK byte if we need to acquire a PENDING lock or
32137 ** a SHARED lock. If we are acquiring a SHARED lock, the acquisition of
32138 ** the PENDING_LOCK byte is temporary.
32140 newLocktype = pFile->locktype;
32141 if( (pFile->locktype==NO_LOCK)
32142 || ( (locktype==EXCLUSIVE_LOCK)
32143 && (pFile->locktype==RESERVED_LOCK))
32145 int cnt = 3;
32146 while( cnt-->0 && (res = LockFile(pFile->h, PENDING_BYTE, 0, 1, 0))==0 ){
32147 /* Try 3 times to get the pending lock. The pending lock might be
32148 ** held by another reader process who will release it momentarily.
32150 OSTRACE(("could not get a PENDING lock. cnt=%d\n", cnt));
32151 Sleep(1);
32153 gotPendingLock = res;
32154 if( !res ){
32155 error = GetLastError();
32159 /* Acquire a shared lock
32161 if( locktype==SHARED_LOCK && res ){
32162 assert( pFile->locktype==NO_LOCK );
32163 res = getReadLock(pFile);
32164 if( res ){
32165 newLocktype = SHARED_LOCK;
32166 }else{
32167 error = GetLastError();
32171 /* Acquire a RESERVED lock
32173 if( locktype==RESERVED_LOCK && res ){
32174 assert( pFile->locktype==SHARED_LOCK );
32175 res = LockFile(pFile->h, RESERVED_BYTE, 0, 1, 0);
32176 if( res ){
32177 newLocktype = RESERVED_LOCK;
32178 }else{
32179 error = GetLastError();
32183 /* Acquire a PENDING lock
32185 if( locktype==EXCLUSIVE_LOCK && res ){
32186 newLocktype = PENDING_LOCK;
32187 gotPendingLock = 0;
32190 /* Acquire an EXCLUSIVE lock
32192 if( locktype==EXCLUSIVE_LOCK && res ){
32193 assert( pFile->locktype>=SHARED_LOCK );
32194 res = unlockReadLock(pFile);
32195 OSTRACE(("unreadlock = %d\n", res));
32196 res = LockFile(pFile->h, SHARED_FIRST, 0, SHARED_SIZE, 0);
32197 if( res ){
32198 newLocktype = EXCLUSIVE_LOCK;
32199 }else{
32200 error = GetLastError();
32201 OSTRACE(("error-code = %d\n", error));
32202 getReadLock(pFile);
32206 /* If we are holding a PENDING lock that ought to be released, then
32207 ** release it now.
32209 if( gotPendingLock && locktype==SHARED_LOCK ){
32210 UnlockFile(pFile->h, PENDING_BYTE, 0, 1, 0);
32213 /* Update the state of the lock has held in the file descriptor then
32214 ** return the appropriate result code.
32216 if( res ){
32217 rc = SQLITE_OK;
32218 }else{
32219 OSTRACE(("LOCK FAILED %d trying for %d but got %d\n", pFile->h,
32220 locktype, newLocktype));
32221 pFile->lastErrno = error;
32222 rc = SQLITE_BUSY;
32224 pFile->locktype = (u8)newLocktype;
32225 return rc;
32229 ** This routine checks if there is a RESERVED lock held on the specified
32230 ** file by this or any other process. If such a lock is held, return
32231 ** non-zero, otherwise zero.
32233 static int winCheckReservedLock(sqlite3_file *id, int *pResOut){
32234 int rc;
32235 winFile *pFile = (winFile*)id;
32237 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
32239 assert( id!=0 );
32240 if( pFile->locktype>=RESERVED_LOCK ){
32241 rc = 1;
32242 OSTRACE(("TEST WR-LOCK %d %d (local)\n", pFile->h, rc));
32243 }else{
32244 rc = LockFile(pFile->h, RESERVED_BYTE, 0, 1, 0);
32245 if( rc ){
32246 UnlockFile(pFile->h, RESERVED_BYTE, 0, 1, 0);
32248 rc = !rc;
32249 OSTRACE(("TEST WR-LOCK %d %d (remote)\n", pFile->h, rc));
32251 *pResOut = rc;
32252 return SQLITE_OK;
32256 ** Lower the locking level on file descriptor id to locktype. locktype
32257 ** must be either NO_LOCK or SHARED_LOCK.
32259 ** If the locking level of the file descriptor is already at or below
32260 ** the requested locking level, this routine is a no-op.
32262 ** It is not possible for this routine to fail if the second argument
32263 ** is NO_LOCK. If the second argument is SHARED_LOCK then this routine
32264 ** might return SQLITE_IOERR;
32266 static int winUnlock(sqlite3_file *id, int locktype){
32267 int type;
32268 winFile *pFile = (winFile*)id;
32269 int rc = SQLITE_OK;
32270 assert( pFile!=0 );
32271 assert( locktype<=SHARED_LOCK );
32272 OSTRACE(("UNLOCK %d to %d was %d(%d)\n", pFile->h, locktype,
32273 pFile->locktype, pFile->sharedLockByte));
32274 type = pFile->locktype;
32275 if( type>=EXCLUSIVE_LOCK ){
32276 UnlockFile(pFile->h, SHARED_FIRST, 0, SHARED_SIZE, 0);
32277 if( locktype==SHARED_LOCK && !getReadLock(pFile) ){
32278 /* This should never happen. We should always be able to
32279 ** reacquire the read lock */
32280 rc = SQLITE_IOERR_UNLOCK;
32283 if( type>=RESERVED_LOCK ){
32284 UnlockFile(pFile->h, RESERVED_BYTE, 0, 1, 0);
32286 if( locktype==NO_LOCK && type>=SHARED_LOCK ){
32287 unlockReadLock(pFile);
32289 if( type>=PENDING_LOCK ){
32290 UnlockFile(pFile->h, PENDING_BYTE, 0, 1, 0);
32292 pFile->locktype = (u8)locktype;
32293 return rc;
32297 ** Control and query of the open file handle.
32299 static int winFileControl(sqlite3_file *id, int op, void *pArg){
32300 switch( op ){
32301 case SQLITE_FCNTL_LOCKSTATE: {
32302 *(int*)pArg = ((winFile*)id)->locktype;
32303 return SQLITE_OK;
32305 case SQLITE_LAST_ERRNO: {
32306 *(int*)pArg = (int)((winFile*)id)->lastErrno;
32307 return SQLITE_OK;
32309 case SQLITE_FCNTL_CHUNK_SIZE: {
32310 ((winFile*)id)->szChunk = *(int *)pArg;
32311 return SQLITE_OK;
32313 case SQLITE_FCNTL_SIZE_HINT: {
32314 sqlite3_int64 sz = *(sqlite3_int64*)pArg;
32315 SimulateIOErrorBenign(1);
32316 winTruncate(id, sz);
32317 SimulateIOErrorBenign(0);
32318 return SQLITE_OK;
32320 case SQLITE_FCNTL_SYNC_OMITTED: {
32321 return SQLITE_OK;
32324 return SQLITE_NOTFOUND;
32328 ** Return the sector size in bytes of the underlying block device for
32329 ** the specified file. This is almost always 512 bytes, but may be
32330 ** larger for some devices.
32332 ** SQLite code assumes this function cannot fail. It also assumes that
32333 ** if two files are created in the same file-system directory (i.e.
32334 ** a database and its journal file) that the sector size will be the
32335 ** same for both.
32337 static int winSectorSize(sqlite3_file *id){
32338 assert( id!=0 );
32339 return (int)(((winFile*)id)->sectorSize);
32343 ** Return a vector of device characteristics.
32345 static int winDeviceCharacteristics(sqlite3_file *id){
32346 UNUSED_PARAMETER(id);
32347 return SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN;
32350 #ifndef SQLITE_OMIT_WAL
32353 ** Windows will only let you create file view mappings
32354 ** on allocation size granularity boundaries.
32355 ** During sqlite3_os_init() we do a GetSystemInfo()
32356 ** to get the granularity size.
32358 SYSTEM_INFO winSysInfo;
32361 ** Helper functions to obtain and relinquish the global mutex. The
32362 ** global mutex is used to protect the winLockInfo objects used by
32363 ** this file, all of which may be shared by multiple threads.
32365 ** Function winShmMutexHeld() is used to assert() that the global mutex
32366 ** is held when required. This function is only used as part of assert()
32367 ** statements. e.g.
32369 ** winShmEnterMutex()
32370 ** assert( winShmMutexHeld() );
32371 ** winShmLeaveMutex()
32373 static void winShmEnterMutex(void){
32374 sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
32376 static void winShmLeaveMutex(void){
32377 sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
32379 #ifdef SQLITE_DEBUG
32380 static int winShmMutexHeld(void) {
32381 return sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
32383 #endif
32386 ** Object used to represent a single file opened and mmapped to provide
32387 ** shared memory. When multiple threads all reference the same
32388 ** log-summary, each thread has its own winFile object, but they all
32389 ** point to a single instance of this object. In other words, each
32390 ** log-summary is opened only once per process.
32392 ** winShmMutexHeld() must be true when creating or destroying
32393 ** this object or while reading or writing the following fields:
32395 ** nRef
32396 ** pNext
32398 ** The following fields are read-only after the object is created:
32400 ** fid
32401 ** zFilename
32403 ** Either winShmNode.mutex must be held or winShmNode.nRef==0 and
32404 ** winShmMutexHeld() is true when reading or writing any other field
32405 ** in this structure.
32408 struct winShmNode {
32409 sqlite3_mutex *mutex; /* Mutex to access this object */
32410 char *zFilename; /* Name of the file */
32411 winFile hFile; /* File handle from winOpen */
32413 int szRegion; /* Size of shared-memory regions */
32414 int nRegion; /* Size of array apRegion */
32415 struct ShmRegion {
32416 HANDLE hMap; /* File handle from CreateFileMapping */
32417 void *pMap;
32418 } *aRegion;
32419 DWORD lastErrno; /* The Windows errno from the last I/O error */
32421 int nRef; /* Number of winShm objects pointing to this */
32422 winShm *pFirst; /* All winShm objects pointing to this */
32423 winShmNode *pNext; /* Next in list of all winShmNode objects */
32424 #ifdef SQLITE_DEBUG
32425 u8 nextShmId; /* Next available winShm.id value */
32426 #endif
32430 ** A global array of all winShmNode objects.
32432 ** The winShmMutexHeld() must be true while reading or writing this list.
32434 static winShmNode *winShmNodeList = 0;
32437 ** Structure used internally by this VFS to record the state of an
32438 ** open shared memory connection.
32440 ** The following fields are initialized when this object is created and
32441 ** are read-only thereafter:
32443 ** winShm.pShmNode
32444 ** winShm.id
32446 ** All other fields are read/write. The winShm.pShmNode->mutex must be held
32447 ** while accessing any read/write fields.
32449 struct winShm {
32450 winShmNode *pShmNode; /* The underlying winShmNode object */
32451 winShm *pNext; /* Next winShm with the same winShmNode */
32452 u8 hasMutex; /* True if holding the winShmNode mutex */
32453 u16 sharedMask; /* Mask of shared locks held */
32454 u16 exclMask; /* Mask of exclusive locks held */
32455 #ifdef SQLITE_DEBUG
32456 u8 id; /* Id of this connection with its winShmNode */
32457 #endif
32461 ** Constants used for locking
32463 #define WIN_SHM_BASE ((22+SQLITE_SHM_NLOCK)*4) /* first lock byte */
32464 #define WIN_SHM_DMS (WIN_SHM_BASE+SQLITE_SHM_NLOCK) /* deadman switch */
32467 ** Apply advisory locks for all n bytes beginning at ofst.
32469 #define _SHM_UNLCK 1
32470 #define _SHM_RDLCK 2
32471 #define _SHM_WRLCK 3
32472 static int winShmSystemLock(
32473 winShmNode *pFile, /* Apply locks to this open shared-memory segment */
32474 int lockType, /* _SHM_UNLCK, _SHM_RDLCK, or _SHM_WRLCK */
32475 int ofst, /* Offset to first byte to be locked/unlocked */
32476 int nByte /* Number of bytes to lock or unlock */
32478 OVERLAPPED ovlp;
32479 DWORD dwFlags;
32480 int rc = 0; /* Result code form Lock/UnlockFileEx() */
32482 /* Access to the winShmNode object is serialized by the caller */
32483 assert( sqlite3_mutex_held(pFile->mutex) || pFile->nRef==0 );
32485 /* Initialize the locking parameters */
32486 dwFlags = LOCKFILE_FAIL_IMMEDIATELY;
32487 if( lockType == _SHM_WRLCK ) dwFlags |= LOCKFILE_EXCLUSIVE_LOCK;
32489 memset(&ovlp, 0, sizeof(OVERLAPPED));
32490 ovlp.Offset = ofst;
32492 /* Release/Acquire the system-level lock */
32493 if( lockType==_SHM_UNLCK ){
32494 rc = UnlockFileEx(pFile->hFile.h, 0, nByte, 0, &ovlp);
32495 }else{
32496 rc = LockFileEx(pFile->hFile.h, dwFlags, 0, nByte, 0, &ovlp);
32499 if( rc!= 0 ){
32500 rc = SQLITE_OK;
32501 }else{
32502 pFile->lastErrno = GetLastError();
32503 rc = SQLITE_BUSY;
32506 OSTRACE(("SHM-LOCK %d %s %s 0x%08lx\n",
32507 pFile->hFile.h,
32508 rc==SQLITE_OK ? "ok" : "failed",
32509 lockType==_SHM_UNLCK ? "UnlockFileEx" : "LockFileEx",
32510 pFile->lastErrno));
32512 return rc;
32515 /* Forward references to VFS methods */
32516 static int winOpen(sqlite3_vfs*,const char*,sqlite3_file*,int,int*);
32517 static int winDelete(sqlite3_vfs *,const char*,int);
32520 ** Purge the winShmNodeList list of all entries with winShmNode.nRef==0.
32522 ** This is not a VFS shared-memory method; it is a utility function called
32523 ** by VFS shared-memory methods.
32525 static void winShmPurge(sqlite3_vfs *pVfs, int deleteFlag){
32526 winShmNode **pp;
32527 winShmNode *p;
32528 BOOL bRc;
32529 assert( winShmMutexHeld() );
32530 pp = &winShmNodeList;
32531 while( (p = *pp)!=0 ){
32532 if( p->nRef==0 ){
32533 int i;
32534 if( p->mutex ) sqlite3_mutex_free(p->mutex);
32535 for(i=0; i<p->nRegion; i++){
32536 bRc = UnmapViewOfFile(p->aRegion[i].pMap);
32537 OSTRACE(("SHM-PURGE pid-%d unmap region=%d %s\n",
32538 (int)GetCurrentProcessId(), i,
32539 bRc ? "ok" : "failed"));
32540 bRc = CloseHandle(p->aRegion[i].hMap);
32541 OSTRACE(("SHM-PURGE pid-%d close region=%d %s\n",
32542 (int)GetCurrentProcessId(), i,
32543 bRc ? "ok" : "failed"));
32545 if( p->hFile.h != INVALID_HANDLE_VALUE ){
32546 SimulateIOErrorBenign(1);
32547 winClose((sqlite3_file *)&p->hFile);
32548 SimulateIOErrorBenign(0);
32550 if( deleteFlag ){
32551 SimulateIOErrorBenign(1);
32552 winDelete(pVfs, p->zFilename, 0);
32553 SimulateIOErrorBenign(0);
32555 *pp = p->pNext;
32556 sqlite3_free(p->aRegion);
32557 sqlite3_free(p);
32558 }else{
32559 pp = &p->pNext;
32565 ** Open the shared-memory area associated with database file pDbFd.
32567 ** When opening a new shared-memory file, if no other instances of that
32568 ** file are currently open, in this process or in other processes, then
32569 ** the file must be truncated to zero length or have its header cleared.
32571 static int winOpenSharedMemory(winFile *pDbFd){
32572 struct winShm *p; /* The connection to be opened */
32573 struct winShmNode *pShmNode = 0; /* The underlying mmapped file */
32574 int rc; /* Result code */
32575 struct winShmNode *pNew; /* Newly allocated winShmNode */
32576 int nName; /* Size of zName in bytes */
32578 assert( pDbFd->pShm==0 ); /* Not previously opened */
32580 /* Allocate space for the new sqlite3_shm object. Also speculatively
32581 ** allocate space for a new winShmNode and filename.
32583 p = sqlite3_malloc( sizeof(*p) );
32584 if( p==0 ) return SQLITE_NOMEM;
32585 memset(p, 0, sizeof(*p));
32586 nName = sqlite3Strlen30(pDbFd->zPath);
32587 pNew = sqlite3_malloc( sizeof(*pShmNode) + nName + 15 );
32588 if( pNew==0 ){
32589 sqlite3_free(p);
32590 return SQLITE_NOMEM;
32592 memset(pNew, 0, sizeof(*pNew));
32593 pNew->zFilename = (char*)&pNew[1];
32594 sqlite3_snprintf(nName+15, pNew->zFilename, "%s-shm", pDbFd->zPath);
32596 /* Look to see if there is an existing winShmNode that can be used.
32597 ** If no matching winShmNode currently exists, create a new one.
32599 winShmEnterMutex();
32600 for(pShmNode = winShmNodeList; pShmNode; pShmNode=pShmNode->pNext){
32601 /* TBD need to come up with better match here. Perhaps
32602 ** use FILE_ID_BOTH_DIR_INFO Structure.
32604 if( sqlite3StrICmp(pShmNode->zFilename, pNew->zFilename)==0 ) break;
32606 if( pShmNode ){
32607 sqlite3_free(pNew);
32608 }else{
32609 pShmNode = pNew;
32610 pNew = 0;
32611 ((winFile*)(&pShmNode->hFile))->h = INVALID_HANDLE_VALUE;
32612 pShmNode->pNext = winShmNodeList;
32613 winShmNodeList = pShmNode;
32615 pShmNode->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
32616 if( pShmNode->mutex==0 ){
32617 rc = SQLITE_NOMEM;
32618 goto shm_open_err;
32621 rc = winOpen(pDbFd->pVfs,
32622 pShmNode->zFilename, /* Name of the file (UTF-8) */
32623 (sqlite3_file*)&pShmNode->hFile, /* File handle here */
32624 SQLITE_OPEN_WAL | SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, /* Mode flags */
32626 if( SQLITE_OK!=rc ){
32627 rc = SQLITE_CANTOPEN_BKPT;
32628 goto shm_open_err;
32631 /* Check to see if another process is holding the dead-man switch.
32632 ** If not, truncate the file to zero length.
32634 if( winShmSystemLock(pShmNode, _SHM_WRLCK, WIN_SHM_DMS, 1)==SQLITE_OK ){
32635 rc = winTruncate((sqlite3_file *)&pShmNode->hFile, 0);
32636 if( rc!=SQLITE_OK ){
32637 rc = SQLITE_IOERR_SHMOPEN;
32640 if( rc==SQLITE_OK ){
32641 winShmSystemLock(pShmNode, _SHM_UNLCK, WIN_SHM_DMS, 1);
32642 rc = winShmSystemLock(pShmNode, _SHM_RDLCK, WIN_SHM_DMS, 1);
32644 if( rc ) goto shm_open_err;
32647 /* Make the new connection a child of the winShmNode */
32648 p->pShmNode = pShmNode;
32649 #ifdef SQLITE_DEBUG
32650 p->id = pShmNode->nextShmId++;
32651 #endif
32652 pShmNode->nRef++;
32653 pDbFd->pShm = p;
32654 winShmLeaveMutex();
32656 /* The reference count on pShmNode has already been incremented under
32657 ** the cover of the winShmEnterMutex() mutex and the pointer from the
32658 ** new (struct winShm) object to the pShmNode has been set. All that is
32659 ** left to do is to link the new object into the linked list starting
32660 ** at pShmNode->pFirst. This must be done while holding the pShmNode->mutex
32661 ** mutex.
32663 sqlite3_mutex_enter(pShmNode->mutex);
32664 p->pNext = pShmNode->pFirst;
32665 pShmNode->pFirst = p;
32666 sqlite3_mutex_leave(pShmNode->mutex);
32667 return SQLITE_OK;
32669 /* Jump here on any error */
32670 shm_open_err:
32671 winShmSystemLock(pShmNode, _SHM_UNLCK, WIN_SHM_DMS, 1);
32672 winShmPurge(pDbFd->pVfs, 0); /* This call frees pShmNode if required */
32673 sqlite3_free(p);
32674 sqlite3_free(pNew);
32675 winShmLeaveMutex();
32676 return rc;
32680 ** Close a connection to shared-memory. Delete the underlying
32681 ** storage if deleteFlag is true.
32683 static int winShmUnmap(
32684 sqlite3_file *fd, /* Database holding shared memory */
32685 int deleteFlag /* Delete after closing if true */
32687 winFile *pDbFd; /* Database holding shared-memory */
32688 winShm *p; /* The connection to be closed */
32689 winShmNode *pShmNode; /* The underlying shared-memory file */
32690 winShm **pp; /* For looping over sibling connections */
32692 pDbFd = (winFile*)fd;
32693 p = pDbFd->pShm;
32694 if( p==0 ) return SQLITE_OK;
32695 pShmNode = p->pShmNode;
32697 /* Remove connection p from the set of connections associated
32698 ** with pShmNode */
32699 sqlite3_mutex_enter(pShmNode->mutex);
32700 for(pp=&pShmNode->pFirst; (*pp)!=p; pp = &(*pp)->pNext){}
32701 *pp = p->pNext;
32703 /* Free the connection p */
32704 sqlite3_free(p);
32705 pDbFd->pShm = 0;
32706 sqlite3_mutex_leave(pShmNode->mutex);
32708 /* If pShmNode->nRef has reached 0, then close the underlying
32709 ** shared-memory file, too */
32710 winShmEnterMutex();
32711 assert( pShmNode->nRef>0 );
32712 pShmNode->nRef--;
32713 if( pShmNode->nRef==0 ){
32714 winShmPurge(pDbFd->pVfs, deleteFlag);
32716 winShmLeaveMutex();
32718 return SQLITE_OK;
32722 ** Change the lock state for a shared-memory segment.
32724 static int winShmLock(
32725 sqlite3_file *fd, /* Database file holding the shared memory */
32726 int ofst, /* First lock to acquire or release */
32727 int n, /* Number of locks to acquire or release */
32728 int flags /* What to do with the lock */
32730 winFile *pDbFd = (winFile*)fd; /* Connection holding shared memory */
32731 winShm *p = pDbFd->pShm; /* The shared memory being locked */
32732 winShm *pX; /* For looping over all siblings */
32733 winShmNode *pShmNode = p->pShmNode;
32734 int rc = SQLITE_OK; /* Result code */
32735 u16 mask; /* Mask of locks to take or release */
32737 assert( ofst>=0 && ofst+n<=SQLITE_SHM_NLOCK );
32738 assert( n>=1 );
32739 assert( flags==(SQLITE_SHM_LOCK | SQLITE_SHM_SHARED)
32740 || flags==(SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE)
32741 || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED)
32742 || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE) );
32743 assert( n==1 || (flags & SQLITE_SHM_EXCLUSIVE)!=0 );
32745 mask = (u16)((1U<<(ofst+n)) - (1U<<ofst));
32746 assert( n>1 || mask==(1<<ofst) );
32747 sqlite3_mutex_enter(pShmNode->mutex);
32748 if( flags & SQLITE_SHM_UNLOCK ){
32749 u16 allMask = 0; /* Mask of locks held by siblings */
32751 /* See if any siblings hold this same lock */
32752 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
32753 if( pX==p ) continue;
32754 assert( (pX->exclMask & (p->exclMask|p->sharedMask))==0 );
32755 allMask |= pX->sharedMask;
32758 /* Unlock the system-level locks */
32759 if( (mask & allMask)==0 ){
32760 rc = winShmSystemLock(pShmNode, _SHM_UNLCK, ofst+WIN_SHM_BASE, n);
32761 }else{
32762 rc = SQLITE_OK;
32765 /* Undo the local locks */
32766 if( rc==SQLITE_OK ){
32767 p->exclMask &= ~mask;
32768 p->sharedMask &= ~mask;
32770 }else if( flags & SQLITE_SHM_SHARED ){
32771 u16 allShared = 0; /* Union of locks held by connections other than "p" */
32773 /* Find out which shared locks are already held by sibling connections.
32774 ** If any sibling already holds an exclusive lock, go ahead and return
32775 ** SQLITE_BUSY.
32777 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
32778 if( (pX->exclMask & mask)!=0 ){
32779 rc = SQLITE_BUSY;
32780 break;
32782 allShared |= pX->sharedMask;
32785 /* Get shared locks at the system level, if necessary */
32786 if( rc==SQLITE_OK ){
32787 if( (allShared & mask)==0 ){
32788 rc = winShmSystemLock(pShmNode, _SHM_RDLCK, ofst+WIN_SHM_BASE, n);
32789 }else{
32790 rc = SQLITE_OK;
32794 /* Get the local shared locks */
32795 if( rc==SQLITE_OK ){
32796 p->sharedMask |= mask;
32798 }else{
32799 /* Make sure no sibling connections hold locks that will block this
32800 ** lock. If any do, return SQLITE_BUSY right away.
32802 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
32803 if( (pX->exclMask & mask)!=0 || (pX->sharedMask & mask)!=0 ){
32804 rc = SQLITE_BUSY;
32805 break;
32809 /* Get the exclusive locks at the system level. Then if successful
32810 ** also mark the local connection as being locked.
32812 if( rc==SQLITE_OK ){
32813 rc = winShmSystemLock(pShmNode, _SHM_WRLCK, ofst+WIN_SHM_BASE, n);
32814 if( rc==SQLITE_OK ){
32815 assert( (p->sharedMask & mask)==0 );
32816 p->exclMask |= mask;
32820 sqlite3_mutex_leave(pShmNode->mutex);
32821 OSTRACE(("SHM-LOCK shmid-%d, pid-%d got %03x,%03x %s\n",
32822 p->id, (int)GetCurrentProcessId(), p->sharedMask, p->exclMask,
32823 rc ? "failed" : "ok"));
32824 return rc;
32828 ** Implement a memory barrier or memory fence on shared memory.
32830 ** All loads and stores begun before the barrier must complete before
32831 ** any load or store begun after the barrier.
32833 static void winShmBarrier(
32834 sqlite3_file *fd /* Database holding the shared memory */
32836 UNUSED_PARAMETER(fd);
32837 /* MemoryBarrier(); // does not work -- do not know why not */
32838 winShmEnterMutex();
32839 winShmLeaveMutex();
32843 ** This function is called to obtain a pointer to region iRegion of the
32844 ** shared-memory associated with the database file fd. Shared-memory regions
32845 ** are numbered starting from zero. Each shared-memory region is szRegion
32846 ** bytes in size.
32848 ** If an error occurs, an error code is returned and *pp is set to NULL.
32850 ** Otherwise, if the isWrite parameter is 0 and the requested shared-memory
32851 ** region has not been allocated (by any client, including one running in a
32852 ** separate process), then *pp is set to NULL and SQLITE_OK returned. If
32853 ** isWrite is non-zero and the requested shared-memory region has not yet
32854 ** been allocated, it is allocated by this function.
32856 ** If the shared-memory region has already been allocated or is allocated by
32857 ** this call as described above, then it is mapped into this processes
32858 ** address space (if it is not already), *pp is set to point to the mapped
32859 ** memory and SQLITE_OK returned.
32861 static int winShmMap(
32862 sqlite3_file *fd, /* Handle open on database file */
32863 int iRegion, /* Region to retrieve */
32864 int szRegion, /* Size of regions */
32865 int isWrite, /* True to extend file if necessary */
32866 void volatile **pp /* OUT: Mapped memory */
32868 winFile *pDbFd = (winFile*)fd;
32869 winShm *p = pDbFd->pShm;
32870 winShmNode *pShmNode;
32871 int rc = SQLITE_OK;
32873 if( !p ){
32874 rc = winOpenSharedMemory(pDbFd);
32875 if( rc!=SQLITE_OK ) return rc;
32876 p = pDbFd->pShm;
32878 pShmNode = p->pShmNode;
32880 sqlite3_mutex_enter(pShmNode->mutex);
32881 assert( szRegion==pShmNode->szRegion || pShmNode->nRegion==0 );
32883 if( pShmNode->nRegion<=iRegion ){
32884 struct ShmRegion *apNew; /* New aRegion[] array */
32885 int nByte = (iRegion+1)*szRegion; /* Minimum required file size */
32886 sqlite3_int64 sz; /* Current size of wal-index file */
32888 pShmNode->szRegion = szRegion;
32890 /* The requested region is not mapped into this processes address space.
32891 ** Check to see if it has been allocated (i.e. if the wal-index file is
32892 ** large enough to contain the requested region).
32894 rc = winFileSize((sqlite3_file *)&pShmNode->hFile, &sz);
32895 if( rc!=SQLITE_OK ){
32896 rc = SQLITE_IOERR_SHMSIZE;
32897 goto shmpage_out;
32900 if( sz<nByte ){
32901 /* The requested memory region does not exist. If isWrite is set to
32902 ** zero, exit early. *pp will be set to NULL and SQLITE_OK returned.
32904 ** Alternatively, if isWrite is non-zero, use ftruncate() to allocate
32905 ** the requested memory region.
32907 if( !isWrite ) goto shmpage_out;
32908 rc = winTruncate((sqlite3_file *)&pShmNode->hFile, nByte);
32909 if( rc!=SQLITE_OK ){
32910 rc = SQLITE_IOERR_SHMSIZE;
32911 goto shmpage_out;
32915 /* Map the requested memory region into this processes address space. */
32916 apNew = (struct ShmRegion *)sqlite3_realloc(
32917 pShmNode->aRegion, (iRegion+1)*sizeof(apNew[0])
32919 if( !apNew ){
32920 rc = SQLITE_IOERR_NOMEM;
32921 goto shmpage_out;
32923 pShmNode->aRegion = apNew;
32925 while( pShmNode->nRegion<=iRegion ){
32926 HANDLE hMap; /* file-mapping handle */
32927 void *pMap = 0; /* Mapped memory region */
32929 hMap = CreateFileMapping(pShmNode->hFile.h,
32930 NULL, PAGE_READWRITE, 0, nByte, NULL
32932 OSTRACE(("SHM-MAP pid-%d create region=%d nbyte=%d %s\n",
32933 (int)GetCurrentProcessId(), pShmNode->nRegion, nByte,
32934 hMap ? "ok" : "failed"));
32935 if( hMap ){
32936 int iOffset = pShmNode->nRegion*szRegion;
32937 int iOffsetShift = iOffset % winSysInfo.dwAllocationGranularity;
32938 pMap = MapViewOfFile(hMap, FILE_MAP_WRITE | FILE_MAP_READ,
32939 0, iOffset - iOffsetShift, szRegion + iOffsetShift
32941 OSTRACE(("SHM-MAP pid-%d map region=%d offset=%d size=%d %s\n",
32942 (int)GetCurrentProcessId(), pShmNode->nRegion, iOffset, szRegion,
32943 pMap ? "ok" : "failed"));
32945 if( !pMap ){
32946 pShmNode->lastErrno = GetLastError();
32947 rc = SQLITE_IOERR;
32948 if( hMap ) CloseHandle(hMap);
32949 goto shmpage_out;
32952 pShmNode->aRegion[pShmNode->nRegion].pMap = pMap;
32953 pShmNode->aRegion[pShmNode->nRegion].hMap = hMap;
32954 pShmNode->nRegion++;
32958 shmpage_out:
32959 if( pShmNode->nRegion>iRegion ){
32960 int iOffset = iRegion*szRegion;
32961 int iOffsetShift = iOffset % winSysInfo.dwAllocationGranularity;
32962 char *p = (char *)pShmNode->aRegion[iRegion].pMap;
32963 *pp = (void *)&p[iOffsetShift];
32964 }else{
32965 *pp = 0;
32967 sqlite3_mutex_leave(pShmNode->mutex);
32968 return rc;
32971 #else
32972 # define winShmMap 0
32973 # define winShmLock 0
32974 # define winShmBarrier 0
32975 # define winShmUnmap 0
32976 #endif /* #ifndef SQLITE_OMIT_WAL */
32979 ** Here ends the implementation of all sqlite3_file methods.
32981 ********************** End sqlite3_file Methods *******************************
32982 ******************************************************************************/
32985 ** This vector defines all the methods that can operate on an
32986 ** sqlite3_file for win32.
32988 static const sqlite3_io_methods winIoMethod = {
32989 2, /* iVersion */
32990 winClose, /* xClose */
32991 winRead, /* xRead */
32992 winWrite, /* xWrite */
32993 winTruncate, /* xTruncate */
32994 winSync, /* xSync */
32995 winFileSize, /* xFileSize */
32996 winLock, /* xLock */
32997 winUnlock, /* xUnlock */
32998 winCheckReservedLock, /* xCheckReservedLock */
32999 winFileControl, /* xFileControl */
33000 winSectorSize, /* xSectorSize */
33001 winDeviceCharacteristics, /* xDeviceCharacteristics */
33002 winShmMap, /* xShmMap */
33003 winShmLock, /* xShmLock */
33004 winShmBarrier, /* xShmBarrier */
33005 winShmUnmap /* xShmUnmap */
33008 /****************************************************************************
33009 **************************** sqlite3_vfs methods ****************************
33011 ** This division contains the implementation of methods on the
33012 ** sqlite3_vfs object.
33016 ** Convert a UTF-8 filename into whatever form the underlying
33017 ** operating system wants filenames in. Space to hold the result
33018 ** is obtained from malloc and must be freed by the calling
33019 ** function.
33021 static void *convertUtf8Filename(const char *zFilename){
33022 void *zConverted = 0;
33023 if( isNT() ){
33024 zConverted = utf8ToUnicode(zFilename);
33025 /* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed.
33027 #if SQLITE_OS_WINCE==0
33028 }else{
33029 zConverted = utf8ToMbcs(zFilename);
33030 #endif
33032 /* caller will handle out of memory */
33033 return zConverted;
33037 ** Create a temporary file name in zBuf. zBuf must be big enough to
33038 ** hold at pVfs->mxPathname characters.
33040 static int getTempname(int nBuf, char *zBuf){
33041 static char zChars[] =
33042 "abcdefghijklmnopqrstuvwxyz"
33043 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
33044 "0123456789";
33045 size_t i, j;
33046 char zTempPath[MAX_PATH+1];
33048 /* It's odd to simulate an io-error here, but really this is just
33049 ** using the io-error infrastructure to test that SQLite handles this
33050 ** function failing.
33052 SimulateIOError( return SQLITE_IOERR );
33054 if( sqlite3_temp_directory ){
33055 sqlite3_snprintf(MAX_PATH-30, zTempPath, "%s", sqlite3_temp_directory);
33056 }else if( isNT() ){
33057 char *zMulti;
33058 WCHAR zWidePath[MAX_PATH];
33059 GetTempPathW(MAX_PATH-30, zWidePath);
33060 zMulti = unicodeToUtf8(zWidePath);
33061 if( zMulti ){
33062 sqlite3_snprintf(MAX_PATH-30, zTempPath, "%s", zMulti);
33063 free(zMulti);
33064 }else{
33065 return SQLITE_NOMEM;
33067 /* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed.
33068 ** Since the ASCII version of these Windows API do not exist for WINCE,
33069 ** it's important to not reference them for WINCE builds.
33071 #if SQLITE_OS_WINCE==0
33072 }else{
33073 char *zUtf8;
33074 char zMbcsPath[MAX_PATH];
33075 GetTempPathA(MAX_PATH-30, zMbcsPath);
33076 zUtf8 = sqlite3_win32_mbcs_to_utf8(zMbcsPath);
33077 if( zUtf8 ){
33078 sqlite3_snprintf(MAX_PATH-30, zTempPath, "%s", zUtf8);
33079 free(zUtf8);
33080 }else{
33081 return SQLITE_NOMEM;
33083 #endif
33086 /* Check that the output buffer is large enough for the temporary file
33087 ** name. If it is not, return SQLITE_ERROR.
33089 if( (sqlite3Strlen30(zTempPath) + sqlite3Strlen30(SQLITE_TEMP_FILE_PREFIX) + 17) >= nBuf ){
33090 return SQLITE_ERROR;
33093 for(i=sqlite3Strlen30(zTempPath); i>0 && zTempPath[i-1]=='\\'; i--){}
33094 zTempPath[i] = 0;
33096 sqlite3_snprintf(nBuf-17, zBuf,
33097 "%s\\"SQLITE_TEMP_FILE_PREFIX, zTempPath);
33098 j = sqlite3Strlen30(zBuf);
33099 sqlite3_randomness(15, &zBuf[j]);
33100 for(i=0; i<15; i++, j++){
33101 zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
33103 zBuf[j] = 0;
33105 OSTRACE(("TEMP FILENAME: %s\n", zBuf));
33106 return SQLITE_OK;
33110 ** The return value of getLastErrorMsg
33111 ** is zero if the error message fits in the buffer, or non-zero
33112 ** otherwise (if the message was truncated).
33114 static int getLastErrorMsg(int nBuf, char *zBuf){
33115 /* FormatMessage returns 0 on failure. Otherwise it
33116 ** returns the number of TCHARs written to the output
33117 ** buffer, excluding the terminating null char.
33119 DWORD error = GetLastError();
33120 DWORD dwLen = 0;
33121 char *zOut = 0;
33123 if( isNT() ){
33124 WCHAR *zTempWide = NULL;
33125 dwLen = FormatMessageW(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
33126 NULL,
33127 error,
33129 (LPWSTR) &zTempWide,
33132 if( dwLen > 0 ){
33133 /* allocate a buffer and convert to UTF8 */
33134 zOut = unicodeToUtf8(zTempWide);
33135 /* free the system buffer allocated by FormatMessage */
33136 LocalFree(zTempWide);
33138 /* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed.
33139 ** Since the ASCII version of these Windows API do not exist for WINCE,
33140 ** it's important to not reference them for WINCE builds.
33142 #if SQLITE_OS_WINCE==0
33143 }else{
33144 char *zTemp = NULL;
33145 dwLen = FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
33146 NULL,
33147 error,
33149 (LPSTR) &zTemp,
33152 if( dwLen > 0 ){
33153 /* allocate a buffer and convert to UTF8 */
33154 zOut = sqlite3_win32_mbcs_to_utf8(zTemp);
33155 /* free the system buffer allocated by FormatMessage */
33156 LocalFree(zTemp);
33158 #endif
33160 if( 0 == dwLen ){
33161 sqlite3_snprintf(nBuf, zBuf, "OsError 0x%x (%u)", error, error);
33162 }else{
33163 /* copy a maximum of nBuf chars to output buffer */
33164 sqlite3_snprintf(nBuf, zBuf, "%s", zOut);
33165 /* free the UTF8 buffer */
33166 free(zOut);
33168 return 0;
33172 ** Open a file.
33174 static int winOpen(
33175 sqlite3_vfs *pVfs, /* Not used */
33176 const char *zName, /* Name of the file (UTF-8) */
33177 sqlite3_file *id, /* Write the SQLite file handle here */
33178 int flags, /* Open mode flags */
33179 int *pOutFlags /* Status return flags */
33181 HANDLE h;
33182 DWORD dwDesiredAccess;
33183 DWORD dwShareMode;
33184 DWORD dwCreationDisposition;
33185 DWORD dwFlagsAndAttributes = 0;
33186 #if SQLITE_OS_WINCE
33187 int isTemp = 0;
33188 #endif
33189 winFile *pFile = (winFile*)id;
33190 void *zConverted; /* Filename in OS encoding */
33191 const char *zUtf8Name = zName; /* Filename in UTF-8 encoding */
33193 /* If argument zPath is a NULL pointer, this function is required to open
33194 ** a temporary file. Use this buffer to store the file name in.
33196 char zTmpname[MAX_PATH+1]; /* Buffer used to create temp filename */
33198 int rc = SQLITE_OK; /* Function Return Code */
33199 #if !defined(NDEBUG) || SQLITE_OS_WINCE
33200 int eType = flags&0xFFFFFF00; /* Type of file to open */
33201 #endif
33203 int isExclusive = (flags & SQLITE_OPEN_EXCLUSIVE);
33204 int isDelete = (flags & SQLITE_OPEN_DELETEONCLOSE);
33205 int isCreate = (flags & SQLITE_OPEN_CREATE);
33206 #ifndef NDEBUG
33207 int isReadonly = (flags & SQLITE_OPEN_READONLY);
33208 #endif
33209 int isReadWrite = (flags & SQLITE_OPEN_READWRITE);
33211 #ifndef NDEBUG
33212 int isOpenJournal = (isCreate && (
33213 eType==SQLITE_OPEN_MASTER_JOURNAL
33214 || eType==SQLITE_OPEN_MAIN_JOURNAL
33215 || eType==SQLITE_OPEN_WAL
33217 #endif
33219 /* Check the following statements are true:
33221 ** (a) Exactly one of the READWRITE and READONLY flags must be set, and
33222 ** (b) if CREATE is set, then READWRITE must also be set, and
33223 ** (c) if EXCLUSIVE is set, then CREATE must also be set.
33224 ** (d) if DELETEONCLOSE is set, then CREATE must also be set.
33226 assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
33227 assert(isCreate==0 || isReadWrite);
33228 assert(isExclusive==0 || isCreate);
33229 assert(isDelete==0 || isCreate);
33231 /* The main DB, main journal, WAL file and master journal are never
33232 ** automatically deleted. Nor are they ever temporary files. */
33233 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB );
33234 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL );
33235 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MASTER_JOURNAL );
33236 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_WAL );
33238 /* Assert that the upper layer has set one of the "file-type" flags. */
33239 assert( eType==SQLITE_OPEN_MAIN_DB || eType==SQLITE_OPEN_TEMP_DB
33240 || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL
33241 || eType==SQLITE_OPEN_SUBJOURNAL || eType==SQLITE_OPEN_MASTER_JOURNAL
33242 || eType==SQLITE_OPEN_TRANSIENT_DB || eType==SQLITE_OPEN_WAL
33245 assert( id!=0 );
33246 UNUSED_PARAMETER(pVfs);
33248 pFile->h = INVALID_HANDLE_VALUE;
33250 /* If the second argument to this function is NULL, generate a
33251 ** temporary file name to use
33253 if( !zUtf8Name ){
33254 assert(isDelete && !isOpenJournal);
33255 rc = getTempname(MAX_PATH+1, zTmpname);
33256 if( rc!=SQLITE_OK ){
33257 return rc;
33259 zUtf8Name = zTmpname;
33262 /* Convert the filename to the system encoding. */
33263 zConverted = convertUtf8Filename(zUtf8Name);
33264 if( zConverted==0 ){
33265 return SQLITE_NOMEM;
33268 if( isReadWrite ){
33269 dwDesiredAccess = GENERIC_READ | GENERIC_WRITE;
33270 }else{
33271 dwDesiredAccess = GENERIC_READ;
33274 /* SQLITE_OPEN_EXCLUSIVE is used to make sure that a new file is
33275 ** created. SQLite doesn't use it to indicate "exclusive access"
33276 ** as it is usually understood.
33278 if( isExclusive ){
33279 /* Creates a new file, only if it does not already exist. */
33280 /* If the file exists, it fails. */
33281 dwCreationDisposition = CREATE_NEW;
33282 }else if( isCreate ){
33283 /* Open existing file, or create if it doesn't exist */
33284 dwCreationDisposition = OPEN_ALWAYS;
33285 }else{
33286 /* Opens a file, only if it exists. */
33287 dwCreationDisposition = OPEN_EXISTING;
33290 dwShareMode = FILE_SHARE_READ | FILE_SHARE_WRITE;
33292 if( isDelete ){
33293 #if SQLITE_OS_WINCE
33294 dwFlagsAndAttributes = FILE_ATTRIBUTE_HIDDEN;
33295 isTemp = 1;
33296 #else
33297 dwFlagsAndAttributes = FILE_ATTRIBUTE_TEMPORARY
33298 | FILE_ATTRIBUTE_HIDDEN
33299 | FILE_FLAG_DELETE_ON_CLOSE;
33300 #endif
33301 }else{
33302 dwFlagsAndAttributes = FILE_ATTRIBUTE_NORMAL;
33304 /* Reports from the internet are that performance is always
33305 ** better if FILE_FLAG_RANDOM_ACCESS is used. Ticket #2699. */
33306 #if SQLITE_OS_WINCE
33307 dwFlagsAndAttributes |= FILE_FLAG_RANDOM_ACCESS;
33308 #endif
33310 if( isNT() ){
33311 h = CreateFileW((WCHAR*)zConverted,
33312 dwDesiredAccess,
33313 dwShareMode,
33314 NULL,
33315 dwCreationDisposition,
33316 dwFlagsAndAttributes,
33317 NULL
33319 /* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed.
33320 ** Since the ASCII version of these Windows API do not exist for WINCE,
33321 ** it's important to not reference them for WINCE builds.
33323 #if SQLITE_OS_WINCE==0
33324 }else{
33325 h = CreateFileA((char*)zConverted,
33326 dwDesiredAccess,
33327 dwShareMode,
33328 NULL,
33329 dwCreationDisposition,
33330 dwFlagsAndAttributes,
33331 NULL
33333 #endif
33336 OSTRACE(("OPEN %d %s 0x%lx %s\n",
33337 h, zName, dwDesiredAccess,
33338 h==INVALID_HANDLE_VALUE ? "failed" : "ok"));
33340 if( h==INVALID_HANDLE_VALUE ){
33341 pFile->lastErrno = GetLastError();
33342 free(zConverted);
33343 if( isReadWrite ){
33344 return winOpen(pVfs, zName, id,
33345 ((flags|SQLITE_OPEN_READONLY)&~(SQLITE_OPEN_CREATE|SQLITE_OPEN_READWRITE)), pOutFlags);
33346 }else{
33347 return SQLITE_CANTOPEN_BKPT;
33351 if( pOutFlags ){
33352 if( isReadWrite ){
33353 *pOutFlags = SQLITE_OPEN_READWRITE;
33354 }else{
33355 *pOutFlags = SQLITE_OPEN_READONLY;
33359 memset(pFile, 0, sizeof(*pFile));
33360 pFile->pMethod = &winIoMethod;
33361 pFile->h = h;
33362 pFile->lastErrno = NO_ERROR;
33363 pFile->pVfs = pVfs;
33364 pFile->pShm = 0;
33365 pFile->zPath = zName;
33366 pFile->sectorSize = getSectorSize(pVfs, zUtf8Name);
33368 #if SQLITE_OS_WINCE
33369 if( isReadWrite && eType==SQLITE_OPEN_MAIN_DB
33370 && !winceCreateLock(zName, pFile)
33372 CloseHandle(h);
33373 free(zConverted);
33374 return SQLITE_CANTOPEN_BKPT;
33376 if( isTemp ){
33377 pFile->zDeleteOnClose = zConverted;
33378 }else
33379 #endif
33381 free(zConverted);
33384 OpenCounter(+1);
33385 return rc;
33389 ** Delete the named file.
33391 ** Note that windows does not allow a file to be deleted if some other
33392 ** process has it open. Sometimes a virus scanner or indexing program
33393 ** will open a journal file shortly after it is created in order to do
33394 ** whatever it does. While this other process is holding the
33395 ** file open, we will be unable to delete it. To work around this
33396 ** problem, we delay 100 milliseconds and try to delete again. Up
33397 ** to MX_DELETION_ATTEMPTs deletion attempts are run before giving
33398 ** up and returning an error.
33400 #define MX_DELETION_ATTEMPTS 5
33401 static int winDelete(
33402 sqlite3_vfs *pVfs, /* Not used on win32 */
33403 const char *zFilename, /* Name of file to delete */
33404 int syncDir /* Not used on win32 */
33406 int cnt = 0;
33407 DWORD rc;
33408 DWORD error = 0;
33409 void *zConverted;
33410 UNUSED_PARAMETER(pVfs);
33411 UNUSED_PARAMETER(syncDir);
33413 SimulateIOError(return SQLITE_IOERR_DELETE);
33414 zConverted = convertUtf8Filename(zFilename);
33415 if( zConverted==0 ){
33416 return SQLITE_NOMEM;
33418 if( isNT() ){
33420 DeleteFileW(zConverted);
33421 }while( ( ((rc = GetFileAttributesW(zConverted)) != INVALID_FILE_ATTRIBUTES)
33422 || ((error = GetLastError()) == ERROR_ACCESS_DENIED))
33423 && (++cnt < MX_DELETION_ATTEMPTS)
33424 && (Sleep(100), 1) );
33425 /* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed.
33426 ** Since the ASCII version of these Windows API do not exist for WINCE,
33427 ** it's important to not reference them for WINCE builds.
33429 #if SQLITE_OS_WINCE==0
33430 }else{
33432 DeleteFileA(zConverted);
33433 }while( ( ((rc = GetFileAttributesA(zConverted)) != INVALID_FILE_ATTRIBUTES)
33434 || ((error = GetLastError()) == ERROR_ACCESS_DENIED))
33435 && (++cnt < MX_DELETION_ATTEMPTS)
33436 && (Sleep(100), 1) );
33437 #endif
33439 free(zConverted);
33440 OSTRACE(("DELETE \"%s\" %s\n", zFilename,
33441 ( (rc==INVALID_FILE_ATTRIBUTES) && (error==ERROR_FILE_NOT_FOUND)) ?
33442 "ok" : "failed" ));
33444 return ( (rc == INVALID_FILE_ATTRIBUTES)
33445 && (error == ERROR_FILE_NOT_FOUND)) ? SQLITE_OK : SQLITE_IOERR_DELETE;
33449 ** Check the existance and status of a file.
33451 static int winAccess(
33452 sqlite3_vfs *pVfs, /* Not used on win32 */
33453 const char *zFilename, /* Name of file to check */
33454 int flags, /* Type of test to make on this file */
33455 int *pResOut /* OUT: Result */
33457 DWORD attr;
33458 int rc = 0;
33459 void *zConverted;
33460 UNUSED_PARAMETER(pVfs);
33462 SimulateIOError( return SQLITE_IOERR_ACCESS; );
33463 zConverted = convertUtf8Filename(zFilename);
33464 if( zConverted==0 ){
33465 return SQLITE_NOMEM;
33467 if( isNT() ){
33468 WIN32_FILE_ATTRIBUTE_DATA sAttrData;
33469 memset(&sAttrData, 0, sizeof(sAttrData));
33470 if( GetFileAttributesExW((WCHAR*)zConverted,
33471 GetFileExInfoStandard,
33472 &sAttrData) ){
33473 /* For an SQLITE_ACCESS_EXISTS query, treat a zero-length file
33474 ** as if it does not exist.
33476 if( flags==SQLITE_ACCESS_EXISTS
33477 && sAttrData.nFileSizeHigh==0
33478 && sAttrData.nFileSizeLow==0 ){
33479 attr = INVALID_FILE_ATTRIBUTES;
33480 }else{
33481 attr = sAttrData.dwFileAttributes;
33483 }else{
33484 if( GetLastError()!=ERROR_FILE_NOT_FOUND ){
33485 free(zConverted);
33486 return SQLITE_IOERR_ACCESS;
33487 }else{
33488 attr = INVALID_FILE_ATTRIBUTES;
33491 /* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed.
33492 ** Since the ASCII version of these Windows API do not exist for WINCE,
33493 ** it's important to not reference them for WINCE builds.
33495 #if SQLITE_OS_WINCE==0
33496 }else{
33497 attr = GetFileAttributesA((char*)zConverted);
33498 #endif
33500 free(zConverted);
33501 switch( flags ){
33502 case SQLITE_ACCESS_READ:
33503 case SQLITE_ACCESS_EXISTS:
33504 rc = attr!=INVALID_FILE_ATTRIBUTES;
33505 break;
33506 case SQLITE_ACCESS_READWRITE:
33507 rc = (attr & FILE_ATTRIBUTE_READONLY)==0;
33508 break;
33509 default:
33510 assert(!"Invalid flags argument");
33512 *pResOut = rc;
33513 return SQLITE_OK;
33518 ** Turn a relative pathname into a full pathname. Write the full
33519 ** pathname into zOut[]. zOut[] will be at least pVfs->mxPathname
33520 ** bytes in size.
33522 static int winFullPathname(
33523 sqlite3_vfs *pVfs, /* Pointer to vfs object */
33524 const char *zRelative, /* Possibly relative input path */
33525 int nFull, /* Size of output buffer in bytes */
33526 char *zFull /* Output buffer */
33529 #if defined(__CYGWIN__)
33530 SimulateIOError( return SQLITE_ERROR );
33531 UNUSED_PARAMETER(nFull);
33532 cygwin_conv_to_full_win32_path(zRelative, zFull);
33533 return SQLITE_OK;
33534 #endif
33536 #if SQLITE_OS_WINCE
33537 SimulateIOError( return SQLITE_ERROR );
33538 UNUSED_PARAMETER(nFull);
33539 /* WinCE has no concept of a relative pathname, or so I am told. */
33540 sqlite3_snprintf(pVfs->mxPathname, zFull, "%s", zRelative);
33541 return SQLITE_OK;
33542 #endif
33544 #if !SQLITE_OS_WINCE && !defined(__CYGWIN__)
33545 int nByte;
33546 void *zConverted;
33547 char *zOut;
33549 /* It's odd to simulate an io-error here, but really this is just
33550 ** using the io-error infrastructure to test that SQLite handles this
33551 ** function failing. This function could fail if, for example, the
33552 ** current working directory has been unlinked.
33554 SimulateIOError( return SQLITE_ERROR );
33555 UNUSED_PARAMETER(nFull);
33556 zConverted = convertUtf8Filename(zRelative);
33557 if( isNT() ){
33558 WCHAR *zTemp;
33559 nByte = GetFullPathNameW((WCHAR*)zConverted, 0, 0, 0) + 3;
33560 zTemp = malloc( nByte*sizeof(zTemp[0]) );
33561 if( zTemp==0 ){
33562 free(zConverted);
33563 return SQLITE_NOMEM;
33565 GetFullPathNameW((WCHAR*)zConverted, nByte, zTemp, 0);
33566 free(zConverted);
33567 zOut = unicodeToUtf8(zTemp);
33568 free(zTemp);
33569 /* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed.
33570 ** Since the ASCII version of these Windows API do not exist for WINCE,
33571 ** it's important to not reference them for WINCE builds.
33573 #if SQLITE_OS_WINCE==0
33574 }else{
33575 char *zTemp;
33576 nByte = GetFullPathNameA((char*)zConverted, 0, 0, 0) + 3;
33577 zTemp = malloc( nByte*sizeof(zTemp[0]) );
33578 if( zTemp==0 ){
33579 free(zConverted);
33580 return SQLITE_NOMEM;
33582 GetFullPathNameA((char*)zConverted, nByte, zTemp, 0);
33583 free(zConverted);
33584 zOut = sqlite3_win32_mbcs_to_utf8(zTemp);
33585 free(zTemp);
33586 #endif
33588 if( zOut ){
33589 sqlite3_snprintf(pVfs->mxPathname, zFull, "%s", zOut);
33590 free(zOut);
33591 return SQLITE_OK;
33592 }else{
33593 return SQLITE_NOMEM;
33595 #endif
33599 ** Get the sector size of the device used to store
33600 ** file.
33602 static int getSectorSize(
33603 sqlite3_vfs *pVfs,
33604 const char *zRelative /* UTF-8 file name */
33606 DWORD bytesPerSector = SQLITE_DEFAULT_SECTOR_SIZE;
33607 /* GetDiskFreeSpace is not supported under WINCE */
33608 #if SQLITE_OS_WINCE
33609 UNUSED_PARAMETER(pVfs);
33610 UNUSED_PARAMETER(zRelative);
33611 #else
33612 char zFullpath[MAX_PATH+1];
33613 int rc;
33614 DWORD dwRet = 0;
33615 DWORD dwDummy;
33618 ** We need to get the full path name of the file
33619 ** to get the drive letter to look up the sector
33620 ** size.
33622 SimulateIOErrorBenign(1);
33623 rc = winFullPathname(pVfs, zRelative, MAX_PATH, zFullpath);
33624 SimulateIOErrorBenign(0);
33625 if( rc == SQLITE_OK )
33627 void *zConverted = convertUtf8Filename(zFullpath);
33628 if( zConverted ){
33629 if( isNT() ){
33630 /* trim path to just drive reference */
33631 WCHAR *p = zConverted;
33632 for(;*p;p++){
33633 if( *p == '\\' ){
33634 *p = '\0';
33635 break;
33638 dwRet = GetDiskFreeSpaceW((WCHAR*)zConverted,
33639 &dwDummy,
33640 &bytesPerSector,
33641 &dwDummy,
33642 &dwDummy);
33643 }else{
33644 /* trim path to just drive reference */
33645 char *p = (char *)zConverted;
33646 for(;*p;p++){
33647 if( *p == '\\' ){
33648 *p = '\0';
33649 break;
33652 dwRet = GetDiskFreeSpaceA((char*)zConverted,
33653 &dwDummy,
33654 &bytesPerSector,
33655 &dwDummy,
33656 &dwDummy);
33658 free(zConverted);
33660 if( !dwRet ){
33661 bytesPerSector = SQLITE_DEFAULT_SECTOR_SIZE;
33664 #endif
33665 return (int) bytesPerSector;
33668 #ifndef SQLITE_OMIT_LOAD_EXTENSION
33670 ** Interfaces for opening a shared library, finding entry points
33671 ** within the shared library, and closing the shared library.
33674 ** Interfaces for opening a shared library, finding entry points
33675 ** within the shared library, and closing the shared library.
33677 static void *winDlOpen(sqlite3_vfs *pVfs, const char *zFilename){
33678 HANDLE h;
33679 void *zConverted = convertUtf8Filename(zFilename);
33680 UNUSED_PARAMETER(pVfs);
33681 if( zConverted==0 ){
33682 return 0;
33684 if( isNT() ){
33685 h = LoadLibraryW((WCHAR*)zConverted);
33686 /* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed.
33687 ** Since the ASCII version of these Windows API do not exist for WINCE,
33688 ** it's important to not reference them for WINCE builds.
33690 #if SQLITE_OS_WINCE==0
33691 }else{
33692 h = LoadLibraryA((char*)zConverted);
33693 #endif
33695 free(zConverted);
33696 return (void*)h;
33698 static void winDlError(sqlite3_vfs *pVfs, int nBuf, char *zBufOut){
33699 UNUSED_PARAMETER(pVfs);
33700 getLastErrorMsg(nBuf, zBufOut);
33702 void (*winDlSym(sqlite3_vfs *pVfs, void *pHandle, const char *zSymbol))(void){
33703 UNUSED_PARAMETER(pVfs);
33704 #if SQLITE_OS_WINCE
33705 /* The GetProcAddressA() routine is only available on wince. */
33706 return (void(*)(void))GetProcAddressA((HANDLE)pHandle, zSymbol);
33707 #else
33708 /* All other windows platforms expect GetProcAddress() to take
33709 ** an Ansi string regardless of the _UNICODE setting */
33710 return (void(*)(void))GetProcAddress((HANDLE)pHandle, zSymbol);
33711 #endif
33713 void winDlClose(sqlite3_vfs *pVfs, void *pHandle){
33714 UNUSED_PARAMETER(pVfs);
33715 FreeLibrary((HANDLE)pHandle);
33717 #else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
33718 #define winDlOpen 0
33719 #define winDlError 0
33720 #define winDlSym 0
33721 #define winDlClose 0
33722 #endif
33726 ** Write up to nBuf bytes of randomness into zBuf.
33728 static int winRandomness(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
33729 int n = 0;
33730 UNUSED_PARAMETER(pVfs);
33731 #if defined(SQLITE_TEST)
33732 n = nBuf;
33733 memset(zBuf, 0, nBuf);
33734 #else
33735 if( sizeof(SYSTEMTIME)<=nBuf-n ){
33736 SYSTEMTIME x;
33737 GetSystemTime(&x);
33738 memcpy(&zBuf[n], &x, sizeof(x));
33739 n += sizeof(x);
33741 if( sizeof(DWORD)<=nBuf-n ){
33742 DWORD pid = GetCurrentProcessId();
33743 memcpy(&zBuf[n], &pid, sizeof(pid));
33744 n += sizeof(pid);
33746 if( sizeof(DWORD)<=nBuf-n ){
33747 DWORD cnt = GetTickCount();
33748 memcpy(&zBuf[n], &cnt, sizeof(cnt));
33749 n += sizeof(cnt);
33751 if( sizeof(LARGE_INTEGER)<=nBuf-n ){
33752 LARGE_INTEGER i;
33753 QueryPerformanceCounter(&i);
33754 memcpy(&zBuf[n], &i, sizeof(i));
33755 n += sizeof(i);
33757 #endif
33758 return n;
33763 ** Sleep for a little while. Return the amount of time slept.
33765 static int winSleep(sqlite3_vfs *pVfs, int microsec){
33766 Sleep((microsec+999)/1000);
33767 UNUSED_PARAMETER(pVfs);
33768 return ((microsec+999)/1000)*1000;
33772 ** The following variable, if set to a non-zero value, is interpreted as
33773 ** the number of seconds since 1970 and is used to set the result of
33774 ** sqlite3OsCurrentTime() during testing.
33776 #ifdef SQLITE_TEST
33777 SQLITE_API int sqlite3_current_time = 0; /* Fake system time in seconds since 1970. */
33778 #endif
33781 ** Find the current time (in Universal Coordinated Time). Write into *piNow
33782 ** the current time and date as a Julian Day number times 86_400_000. In
33783 ** other words, write into *piNow the number of milliseconds since the Julian
33784 ** epoch of noon in Greenwich on November 24, 4714 B.C according to the
33785 ** proleptic Gregorian calendar.
33787 ** On success, return 0. Return 1 if the time and date cannot be found.
33789 static int winCurrentTimeInt64(sqlite3_vfs *pVfs, sqlite3_int64 *piNow){
33790 /* FILETIME structure is a 64-bit value representing the number of
33791 100-nanosecond intervals since January 1, 1601 (= JD 2305813.5).
33793 FILETIME ft;
33794 static const sqlite3_int64 winFiletimeEpoch = 23058135*(sqlite3_int64)8640000;
33795 #ifdef SQLITE_TEST
33796 static const sqlite3_int64 unixEpoch = 24405875*(sqlite3_int64)8640000;
33797 #endif
33798 /* 2^32 - to avoid use of LL and warnings in gcc */
33799 static const sqlite3_int64 max32BitValue =
33800 (sqlite3_int64)2000000000 + (sqlite3_int64)2000000000 + (sqlite3_int64)294967296;
33802 #if SQLITE_OS_WINCE
33803 SYSTEMTIME time;
33804 GetSystemTime(&time);
33805 /* if SystemTimeToFileTime() fails, it returns zero. */
33806 if (!SystemTimeToFileTime(&time,&ft)){
33807 return 1;
33809 #else
33810 GetSystemTimeAsFileTime( &ft );
33811 #endif
33813 *piNow = winFiletimeEpoch +
33814 ((((sqlite3_int64)ft.dwHighDateTime)*max32BitValue) +
33815 (sqlite3_int64)ft.dwLowDateTime)/(sqlite3_int64)10000;
33817 #ifdef SQLITE_TEST
33818 if( sqlite3_current_time ){
33819 *piNow = 1000*(sqlite3_int64)sqlite3_current_time + unixEpoch;
33821 #endif
33822 UNUSED_PARAMETER(pVfs);
33823 return 0;
33827 ** Find the current time (in Universal Coordinated Time). Write the
33828 ** current time and date as a Julian Day number into *prNow and
33829 ** return 0. Return 1 if the time and date cannot be found.
33831 int winCurrentTime(sqlite3_vfs *pVfs, double *prNow){
33832 int rc;
33833 sqlite3_int64 i;
33834 rc = winCurrentTimeInt64(pVfs, &i);
33835 if( !rc ){
33836 *prNow = i/86400000.0;
33838 return rc;
33842 ** The idea is that this function works like a combination of
33843 ** GetLastError() and FormatMessage() on windows (or errno and
33844 ** strerror_r() on unix). After an error is returned by an OS
33845 ** function, SQLite calls this function with zBuf pointing to
33846 ** a buffer of nBuf bytes. The OS layer should populate the
33847 ** buffer with a nul-terminated UTF-8 encoded error message
33848 ** describing the last IO error to have occurred within the calling
33849 ** thread.
33851 ** If the error message is too large for the supplied buffer,
33852 ** it should be truncated. The return value of xGetLastError
33853 ** is zero if the error message fits in the buffer, or non-zero
33854 ** otherwise (if the message was truncated). If non-zero is returned,
33855 ** then it is not necessary to include the nul-terminator character
33856 ** in the output buffer.
33858 ** Not supplying an error message will have no adverse effect
33859 ** on SQLite. It is fine to have an implementation that never
33860 ** returns an error message:
33862 ** int xGetLastError(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
33863 ** assert(zBuf[0]=='\0');
33864 ** return 0;
33865 ** }
33867 ** However if an error message is supplied, it will be incorporated
33868 ** by sqlite into the error message available to the user using
33869 ** sqlite3_errmsg(), possibly making IO errors easier to debug.
33871 static int winGetLastError(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
33872 UNUSED_PARAMETER(pVfs);
33873 return getLastErrorMsg(nBuf, zBuf);
33879 ** Initialize and deinitialize the operating system interface.
33881 SQLITE_API int sqlite3_os_init(void){
33882 static sqlite3_vfs winVfs = {
33883 3, /* iVersion */
33884 sizeof(winFile), /* szOsFile */
33885 MAX_PATH, /* mxPathname */
33886 0, /* pNext */
33887 "win32", /* zName */
33888 0, /* pAppData */
33889 winOpen, /* xOpen */
33890 winDelete, /* xDelete */
33891 winAccess, /* xAccess */
33892 winFullPathname, /* xFullPathname */
33893 winDlOpen, /* xDlOpen */
33894 winDlError, /* xDlError */
33895 winDlSym, /* xDlSym */
33896 winDlClose, /* xDlClose */
33897 winRandomness, /* xRandomness */
33898 winSleep, /* xSleep */
33899 winCurrentTime, /* xCurrentTime */
33900 winGetLastError, /* xGetLastError */
33901 winCurrentTimeInt64, /* xCurrentTimeInt64 */
33902 0, /* xSetSystemCall */
33903 0, /* xGetSystemCall */
33904 0, /* xNextSystemCall */
33907 #ifndef SQLITE_OMIT_WAL
33908 /* get memory map allocation granularity */
33909 memset(&winSysInfo, 0, sizeof(SYSTEM_INFO));
33910 GetSystemInfo(&winSysInfo);
33911 assert(winSysInfo.dwAllocationGranularity > 0);
33912 #endif
33914 sqlite3_vfs_register(&winVfs, 1);
33915 return SQLITE_OK;
33917 SQLITE_API int sqlite3_os_end(void){
33918 return SQLITE_OK;
33921 void chromium_sqlite3_initialize_win_sqlite3_file(sqlite3_file* file, HANDLE handle) {
33922 winFile* winSQLite3File = (winFile*)file;
33923 memset(file, 0, sizeof(*file));
33924 winSQLite3File->pMethod = &winIoMethod;
33925 winSQLite3File->h = handle;
33928 #endif /* SQLITE_OS_WIN */
33930 /************** End of os_win.c **********************************************/
33931 /************** Begin file bitvec.c ******************************************/
33933 ** 2008 February 16
33935 ** The author disclaims copyright to this source code. In place of
33936 ** a legal notice, here is a blessing:
33938 ** May you do good and not evil.
33939 ** May you find forgiveness for yourself and forgive others.
33940 ** May you share freely, never taking more than you give.
33942 *************************************************************************
33943 ** This file implements an object that represents a fixed-length
33944 ** bitmap. Bits are numbered starting with 1.
33946 ** A bitmap is used to record which pages of a database file have been
33947 ** journalled during a transaction, or which pages have the "dont-write"
33948 ** property. Usually only a few pages are meet either condition.
33949 ** So the bitmap is usually sparse and has low cardinality.
33950 ** But sometimes (for example when during a DROP of a large table) most
33951 ** or all of the pages in a database can get journalled. In those cases,
33952 ** the bitmap becomes dense with high cardinality. The algorithm needs
33953 ** to handle both cases well.
33955 ** The size of the bitmap is fixed when the object is created.
33957 ** All bits are clear when the bitmap is created. Individual bits
33958 ** may be set or cleared one at a time.
33960 ** Test operations are about 100 times more common that set operations.
33961 ** Clear operations are exceedingly rare. There are usually between
33962 ** 5 and 500 set operations per Bitvec object, though the number of sets can
33963 ** sometimes grow into tens of thousands or larger. The size of the
33964 ** Bitvec object is the number of pages in the database file at the
33965 ** start of a transaction, and is thus usually less than a few thousand,
33966 ** but can be as large as 2 billion for a really big database.
33969 /* Size of the Bitvec structure in bytes. */
33970 #define BITVEC_SZ 512
33972 /* Round the union size down to the nearest pointer boundary, since that's how
33973 ** it will be aligned within the Bitvec struct. */
33974 #define BITVEC_USIZE (((BITVEC_SZ-(3*sizeof(u32)))/sizeof(Bitvec*))*sizeof(Bitvec*))
33976 /* Type of the array "element" for the bitmap representation.
33977 ** Should be a power of 2, and ideally, evenly divide into BITVEC_USIZE.
33978 ** Setting this to the "natural word" size of your CPU may improve
33979 ** performance. */
33980 #define BITVEC_TELEM u8
33981 /* Size, in bits, of the bitmap element. */
33982 #define BITVEC_SZELEM 8
33983 /* Number of elements in a bitmap array. */
33984 #define BITVEC_NELEM (BITVEC_USIZE/sizeof(BITVEC_TELEM))
33985 /* Number of bits in the bitmap array. */
33986 #define BITVEC_NBIT (BITVEC_NELEM*BITVEC_SZELEM)
33988 /* Number of u32 values in hash table. */
33989 #define BITVEC_NINT (BITVEC_USIZE/sizeof(u32))
33990 /* Maximum number of entries in hash table before
33991 ** sub-dividing and re-hashing. */
33992 #define BITVEC_MXHASH (BITVEC_NINT/2)
33993 /* Hashing function for the aHash representation.
33994 ** Empirical testing showed that the *37 multiplier
33995 ** (an arbitrary prime)in the hash function provided
33996 ** no fewer collisions than the no-op *1. */
33997 #define BITVEC_HASH(X) (((X)*1)%BITVEC_NINT)
33999 #define BITVEC_NPTR (BITVEC_USIZE/sizeof(Bitvec *))
34003 ** A bitmap is an instance of the following structure.
34005 ** This bitmap records the existance of zero or more bits
34006 ** with values between 1 and iSize, inclusive.
34008 ** There are three possible representations of the bitmap.
34009 ** If iSize<=BITVEC_NBIT, then Bitvec.u.aBitmap[] is a straight
34010 ** bitmap. The least significant bit is bit 1.
34012 ** If iSize>BITVEC_NBIT and iDivisor==0 then Bitvec.u.aHash[] is
34013 ** a hash table that will hold up to BITVEC_MXHASH distinct values.
34015 ** Otherwise, the value i is redirected into one of BITVEC_NPTR
34016 ** sub-bitmaps pointed to by Bitvec.u.apSub[]. Each subbitmap
34017 ** handles up to iDivisor separate values of i. apSub[0] holds
34018 ** values between 1 and iDivisor. apSub[1] holds values between
34019 ** iDivisor+1 and 2*iDivisor. apSub[N] holds values between
34020 ** N*iDivisor+1 and (N+1)*iDivisor. Each subbitmap is normalized
34021 ** to hold deal with values between 1 and iDivisor.
34023 struct Bitvec {
34024 u32 iSize; /* Maximum bit index. Max iSize is 4,294,967,296. */
34025 u32 nSet; /* Number of bits that are set - only valid for aHash
34026 ** element. Max is BITVEC_NINT. For BITVEC_SZ of 512,
34027 ** this would be 125. */
34028 u32 iDivisor; /* Number of bits handled by each apSub[] entry. */
34029 /* Should >=0 for apSub element. */
34030 /* Max iDivisor is max(u32) / BITVEC_NPTR + 1. */
34031 /* For a BITVEC_SZ of 512, this would be 34,359,739. */
34032 union {
34033 BITVEC_TELEM aBitmap[BITVEC_NELEM]; /* Bitmap representation */
34034 u32 aHash[BITVEC_NINT]; /* Hash table representation */
34035 Bitvec *apSub[BITVEC_NPTR]; /* Recursive representation */
34036 } u;
34040 ** Create a new bitmap object able to handle bits between 0 and iSize,
34041 ** inclusive. Return a pointer to the new object. Return NULL if
34042 ** malloc fails.
34044 SQLITE_PRIVATE Bitvec *sqlite3BitvecCreate(u32 iSize){
34045 Bitvec *p;
34046 assert( sizeof(*p)==BITVEC_SZ );
34047 p = sqlite3MallocZero( sizeof(*p) );
34048 if( p ){
34049 p->iSize = iSize;
34051 return p;
34055 ** Check to see if the i-th bit is set. Return true or false.
34056 ** If p is NULL (if the bitmap has not been created) or if
34057 ** i is out of range, then return false.
34059 SQLITE_PRIVATE int sqlite3BitvecTest(Bitvec *p, u32 i){
34060 if( p==0 ) return 0;
34061 if( i>p->iSize || i==0 ) return 0;
34062 i--;
34063 while( p->iDivisor ){
34064 u32 bin = i/p->iDivisor;
34065 i = i%p->iDivisor;
34066 p = p->u.apSub[bin];
34067 if (!p) {
34068 return 0;
34071 if( p->iSize<=BITVEC_NBIT ){
34072 return (p->u.aBitmap[i/BITVEC_SZELEM] & (1<<(i&(BITVEC_SZELEM-1))))!=0;
34073 } else{
34074 u32 h = BITVEC_HASH(i++);
34075 while( p->u.aHash[h] ){
34076 if( p->u.aHash[h]==i ) return 1;
34077 h = (h+1) % BITVEC_NINT;
34079 return 0;
34084 ** Set the i-th bit. Return 0 on success and an error code if
34085 ** anything goes wrong.
34087 ** This routine might cause sub-bitmaps to be allocated. Failing
34088 ** to get the memory needed to hold the sub-bitmap is the only
34089 ** that can go wrong with an insert, assuming p and i are valid.
34091 ** The calling function must ensure that p is a valid Bitvec object
34092 ** and that the value for "i" is within range of the Bitvec object.
34093 ** Otherwise the behavior is undefined.
34095 SQLITE_PRIVATE int sqlite3BitvecSet(Bitvec *p, u32 i){
34096 u32 h;
34097 if( p==0 ) return SQLITE_OK;
34098 assert( i>0 );
34099 assert( i<=p->iSize );
34100 i--;
34101 while((p->iSize > BITVEC_NBIT) && p->iDivisor) {
34102 u32 bin = i/p->iDivisor;
34103 i = i%p->iDivisor;
34104 if( p->u.apSub[bin]==0 ){
34105 p->u.apSub[bin] = sqlite3BitvecCreate( p->iDivisor );
34106 if( p->u.apSub[bin]==0 ) return SQLITE_NOMEM;
34108 p = p->u.apSub[bin];
34110 if( p->iSize<=BITVEC_NBIT ){
34111 p->u.aBitmap[i/BITVEC_SZELEM] |= 1 << (i&(BITVEC_SZELEM-1));
34112 return SQLITE_OK;
34114 h = BITVEC_HASH(i++);
34115 /* if there wasn't a hash collision, and this doesn't */
34116 /* completely fill the hash, then just add it without */
34117 /* worring about sub-dividing and re-hashing. */
34118 if( !p->u.aHash[h] ){
34119 if (p->nSet<(BITVEC_NINT-1)) {
34120 goto bitvec_set_end;
34121 } else {
34122 goto bitvec_set_rehash;
34125 /* there was a collision, check to see if it's already */
34126 /* in hash, if not, try to find a spot for it */
34127 do {
34128 if( p->u.aHash[h]==i ) return SQLITE_OK;
34129 h++;
34130 if( h>=BITVEC_NINT ) h = 0;
34131 } while( p->u.aHash[h] );
34132 /* we didn't find it in the hash. h points to the first */
34133 /* available free spot. check to see if this is going to */
34134 /* make our hash too "full". */
34135 bitvec_set_rehash:
34136 if( p->nSet>=BITVEC_MXHASH ){
34137 unsigned int j;
34138 int rc;
34139 u32 *aiValues = sqlite3StackAllocRaw(0, sizeof(p->u.aHash));
34140 if( aiValues==0 ){
34141 return SQLITE_NOMEM;
34142 }else{
34143 memcpy(aiValues, p->u.aHash, sizeof(p->u.aHash));
34144 memset(p->u.apSub, 0, sizeof(p->u.apSub));
34145 p->iDivisor = (p->iSize + BITVEC_NPTR - 1)/BITVEC_NPTR;
34146 rc = sqlite3BitvecSet(p, i);
34147 for(j=0; j<BITVEC_NINT; j++){
34148 if( aiValues[j] ) rc |= sqlite3BitvecSet(p, aiValues[j]);
34150 sqlite3StackFree(0, aiValues);
34151 return rc;
34154 bitvec_set_end:
34155 p->nSet++;
34156 p->u.aHash[h] = i;
34157 return SQLITE_OK;
34161 ** Clear the i-th bit.
34163 ** pBuf must be a pointer to at least BITVEC_SZ bytes of temporary storage
34164 ** that BitvecClear can use to rebuilt its hash table.
34166 SQLITE_PRIVATE void sqlite3BitvecClear(Bitvec *p, u32 i, void *pBuf){
34167 if( p==0 ) return;
34168 assert( i>0 );
34169 i--;
34170 while( p->iDivisor ){
34171 u32 bin = i/p->iDivisor;
34172 i = i%p->iDivisor;
34173 p = p->u.apSub[bin];
34174 if (!p) {
34175 return;
34178 if( p->iSize<=BITVEC_NBIT ){
34179 p->u.aBitmap[i/BITVEC_SZELEM] &= ~(1 << (i&(BITVEC_SZELEM-1)));
34180 }else{
34181 unsigned int j;
34182 u32 *aiValues = pBuf;
34183 memcpy(aiValues, p->u.aHash, sizeof(p->u.aHash));
34184 memset(p->u.aHash, 0, sizeof(p->u.aHash));
34185 p->nSet = 0;
34186 for(j=0; j<BITVEC_NINT; j++){
34187 if( aiValues[j] && aiValues[j]!=(i+1) ){
34188 u32 h = BITVEC_HASH(aiValues[j]-1);
34189 p->nSet++;
34190 while( p->u.aHash[h] ){
34191 h++;
34192 if( h>=BITVEC_NINT ) h = 0;
34194 p->u.aHash[h] = aiValues[j];
34201 ** Destroy a bitmap object. Reclaim all memory used.
34203 SQLITE_PRIVATE void sqlite3BitvecDestroy(Bitvec *p){
34204 if( p==0 ) return;
34205 if( p->iDivisor ){
34206 unsigned int i;
34207 for(i=0; i<BITVEC_NPTR; i++){
34208 sqlite3BitvecDestroy(p->u.apSub[i]);
34211 sqlite3_free(p);
34215 ** Return the value of the iSize parameter specified when Bitvec *p
34216 ** was created.
34218 SQLITE_PRIVATE u32 sqlite3BitvecSize(Bitvec *p){
34219 return p->iSize;
34222 #ifndef SQLITE_OMIT_BUILTIN_TEST
34224 ** Let V[] be an array of unsigned characters sufficient to hold
34225 ** up to N bits. Let I be an integer between 0 and N. 0<=I<N.
34226 ** Then the following macros can be used to set, clear, or test
34227 ** individual bits within V.
34229 #define SETBIT(V,I) V[I>>3] |= (1<<(I&7))
34230 #define CLEARBIT(V,I) V[I>>3] &= ~(1<<(I&7))
34231 #define TESTBIT(V,I) (V[I>>3]&(1<<(I&7)))!=0
34234 ** This routine runs an extensive test of the Bitvec code.
34236 ** The input is an array of integers that acts as a program
34237 ** to test the Bitvec. The integers are opcodes followed
34238 ** by 0, 1, or 3 operands, depending on the opcode. Another
34239 ** opcode follows immediately after the last operand.
34241 ** There are 6 opcodes numbered from 0 through 5. 0 is the
34242 ** "halt" opcode and causes the test to end.
34244 ** 0 Halt and return the number of errors
34245 ** 1 N S X Set N bits beginning with S and incrementing by X
34246 ** 2 N S X Clear N bits beginning with S and incrementing by X
34247 ** 3 N Set N randomly chosen bits
34248 ** 4 N Clear N randomly chosen bits
34249 ** 5 N S X Set N bits from S increment X in array only, not in bitvec
34251 ** The opcodes 1 through 4 perform set and clear operations are performed
34252 ** on both a Bitvec object and on a linear array of bits obtained from malloc.
34253 ** Opcode 5 works on the linear array only, not on the Bitvec.
34254 ** Opcode 5 is used to deliberately induce a fault in order to
34255 ** confirm that error detection works.
34257 ** At the conclusion of the test the linear array is compared
34258 ** against the Bitvec object. If there are any differences,
34259 ** an error is returned. If they are the same, zero is returned.
34261 ** If a memory allocation error occurs, return -1.
34263 SQLITE_PRIVATE int sqlite3BitvecBuiltinTest(int sz, int *aOp){
34264 Bitvec *pBitvec = 0;
34265 unsigned char *pV = 0;
34266 int rc = -1;
34267 int i, nx, pc, op;
34268 void *pTmpSpace;
34270 /* Allocate the Bitvec to be tested and a linear array of
34271 ** bits to act as the reference */
34272 pBitvec = sqlite3BitvecCreate( sz );
34273 pV = sqlite3_malloc( (sz+7)/8 + 1 );
34274 pTmpSpace = sqlite3_malloc(BITVEC_SZ);
34275 if( pBitvec==0 || pV==0 || pTmpSpace==0 ) goto bitvec_end;
34276 memset(pV, 0, (sz+7)/8 + 1);
34278 /* NULL pBitvec tests */
34279 sqlite3BitvecSet(0, 1);
34280 sqlite3BitvecClear(0, 1, pTmpSpace);
34282 /* Run the program */
34283 pc = 0;
34284 while( (op = aOp[pc])!=0 ){
34285 switch( op ){
34286 case 1:
34287 case 2:
34288 case 5: {
34289 nx = 4;
34290 i = aOp[pc+2] - 1;
34291 aOp[pc+2] += aOp[pc+3];
34292 break;
34294 case 3:
34295 case 4:
34296 default: {
34297 nx = 2;
34298 sqlite3_randomness(sizeof(i), &i);
34299 break;
34302 if( (--aOp[pc+1]) > 0 ) nx = 0;
34303 pc += nx;
34304 i = (i & 0x7fffffff)%sz;
34305 if( (op & 1)!=0 ){
34306 SETBIT(pV, (i+1));
34307 if( op!=5 ){
34308 if( sqlite3BitvecSet(pBitvec, i+1) ) goto bitvec_end;
34310 }else{
34311 CLEARBIT(pV, (i+1));
34312 sqlite3BitvecClear(pBitvec, i+1, pTmpSpace);
34316 /* Test to make sure the linear array exactly matches the
34317 ** Bitvec object. Start with the assumption that they do
34318 ** match (rc==0). Change rc to non-zero if a discrepancy
34319 ** is found.
34321 rc = sqlite3BitvecTest(0,0) + sqlite3BitvecTest(pBitvec, sz+1)
34322 + sqlite3BitvecTest(pBitvec, 0)
34323 + (sqlite3BitvecSize(pBitvec) - sz);
34324 for(i=1; i<=sz; i++){
34325 if( (TESTBIT(pV,i))!=sqlite3BitvecTest(pBitvec,i) ){
34326 rc = i;
34327 break;
34331 /* Free allocated structure */
34332 bitvec_end:
34333 sqlite3_free(pTmpSpace);
34334 sqlite3_free(pV);
34335 sqlite3BitvecDestroy(pBitvec);
34336 return rc;
34338 #endif /* SQLITE_OMIT_BUILTIN_TEST */
34340 /************** End of bitvec.c **********************************************/
34341 /************** Begin file pcache.c ******************************************/
34343 ** 2008 August 05
34345 ** The author disclaims copyright to this source code. In place of
34346 ** a legal notice, here is a blessing:
34348 ** May you do good and not evil.
34349 ** May you find forgiveness for yourself and forgive others.
34350 ** May you share freely, never taking more than you give.
34352 *************************************************************************
34353 ** This file implements that page cache.
34357 ** A complete page cache is an instance of this structure.
34359 struct PCache {
34360 PgHdr *pDirty, *pDirtyTail; /* List of dirty pages in LRU order */
34361 PgHdr *pSynced; /* Last synced page in dirty page list */
34362 int nRef; /* Number of referenced pages */
34363 int nMax; /* Configured cache size */
34364 int szPage; /* Size of every page in this cache */
34365 int szExtra; /* Size of extra space for each page */
34366 int bPurgeable; /* True if pages are on backing store */
34367 int (*xStress)(void*,PgHdr*); /* Call to try make a page clean */
34368 void *pStress; /* Argument to xStress */
34369 sqlite3_pcache *pCache; /* Pluggable cache module */
34370 PgHdr *pPage1; /* Reference to page 1 */
34374 ** Some of the assert() macros in this code are too expensive to run
34375 ** even during normal debugging. Use them only rarely on long-running
34376 ** tests. Enable the expensive asserts using the
34377 ** -DSQLITE_ENABLE_EXPENSIVE_ASSERT=1 compile-time option.
34379 #ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
34380 # define expensive_assert(X) assert(X)
34381 #else
34382 # define expensive_assert(X)
34383 #endif
34385 /********************************** Linked List Management ********************/
34387 #if !defined(NDEBUG) && defined(SQLITE_ENABLE_EXPENSIVE_ASSERT)
34389 ** Check that the pCache->pSynced variable is set correctly. If it
34390 ** is not, either fail an assert or return zero. Otherwise, return
34391 ** non-zero. This is only used in debugging builds, as follows:
34393 ** expensive_assert( pcacheCheckSynced(pCache) );
34395 static int pcacheCheckSynced(PCache *pCache){
34396 PgHdr *p;
34397 for(p=pCache->pDirtyTail; p!=pCache->pSynced; p=p->pDirtyPrev){
34398 assert( p->nRef || (p->flags&PGHDR_NEED_SYNC) );
34400 return (p==0 || p->nRef || (p->flags&PGHDR_NEED_SYNC)==0);
34402 #endif /* !NDEBUG && SQLITE_ENABLE_EXPENSIVE_ASSERT */
34405 ** Remove page pPage from the list of dirty pages.
34407 static void pcacheRemoveFromDirtyList(PgHdr *pPage){
34408 PCache *p = pPage->pCache;
34410 assert( pPage->pDirtyNext || pPage==p->pDirtyTail );
34411 assert( pPage->pDirtyPrev || pPage==p->pDirty );
34413 /* Update the PCache1.pSynced variable if necessary. */
34414 if( p->pSynced==pPage ){
34415 PgHdr *pSynced = pPage->pDirtyPrev;
34416 while( pSynced && (pSynced->flags&PGHDR_NEED_SYNC) ){
34417 pSynced = pSynced->pDirtyPrev;
34419 p->pSynced = pSynced;
34422 if( pPage->pDirtyNext ){
34423 pPage->pDirtyNext->pDirtyPrev = pPage->pDirtyPrev;
34424 }else{
34425 assert( pPage==p->pDirtyTail );
34426 p->pDirtyTail = pPage->pDirtyPrev;
34428 if( pPage->pDirtyPrev ){
34429 pPage->pDirtyPrev->pDirtyNext = pPage->pDirtyNext;
34430 }else{
34431 assert( pPage==p->pDirty );
34432 p->pDirty = pPage->pDirtyNext;
34434 pPage->pDirtyNext = 0;
34435 pPage->pDirtyPrev = 0;
34437 expensive_assert( pcacheCheckSynced(p) );
34441 ** Add page pPage to the head of the dirty list (PCache1.pDirty is set to
34442 ** pPage).
34444 static void pcacheAddToDirtyList(PgHdr *pPage){
34445 PCache *p = pPage->pCache;
34447 assert( pPage->pDirtyNext==0 && pPage->pDirtyPrev==0 && p->pDirty!=pPage );
34449 pPage->pDirtyNext = p->pDirty;
34450 if( pPage->pDirtyNext ){
34451 assert( pPage->pDirtyNext->pDirtyPrev==0 );
34452 pPage->pDirtyNext->pDirtyPrev = pPage;
34454 p->pDirty = pPage;
34455 if( !p->pDirtyTail ){
34456 p->pDirtyTail = pPage;
34458 if( !p->pSynced && 0==(pPage->flags&PGHDR_NEED_SYNC) ){
34459 p->pSynced = pPage;
34461 expensive_assert( pcacheCheckSynced(p) );
34465 ** Wrapper around the pluggable caches xUnpin method. If the cache is
34466 ** being used for an in-memory database, this function is a no-op.
34468 static void pcacheUnpin(PgHdr *p){
34469 PCache *pCache = p->pCache;
34470 if( pCache->bPurgeable ){
34471 if( p->pgno==1 ){
34472 pCache->pPage1 = 0;
34474 sqlite3GlobalConfig.pcache.xUnpin(pCache->pCache, p, 0);
34478 /*************************************************** General Interfaces ******
34480 ** Initialize and shutdown the page cache subsystem. Neither of these
34481 ** functions are threadsafe.
34483 SQLITE_PRIVATE int sqlite3PcacheInitialize(void){
34484 if( sqlite3GlobalConfig.pcache.xInit==0 ){
34485 /* IMPLEMENTATION-OF: R-26801-64137 If the xInit() method is NULL, then the
34486 ** built-in default page cache is used instead of the application defined
34487 ** page cache. */
34488 sqlite3PCacheSetDefault();
34490 return sqlite3GlobalConfig.pcache.xInit(sqlite3GlobalConfig.pcache.pArg);
34492 SQLITE_PRIVATE void sqlite3PcacheShutdown(void){
34493 if( sqlite3GlobalConfig.pcache.xShutdown ){
34494 /* IMPLEMENTATION-OF: R-26000-56589 The xShutdown() method may be NULL. */
34495 sqlite3GlobalConfig.pcache.xShutdown(sqlite3GlobalConfig.pcache.pArg);
34500 ** Return the size in bytes of a PCache object.
34502 SQLITE_PRIVATE int sqlite3PcacheSize(void){ return sizeof(PCache); }
34505 ** Create a new PCache object. Storage space to hold the object
34506 ** has already been allocated and is passed in as the p pointer.
34507 ** The caller discovers how much space needs to be allocated by
34508 ** calling sqlite3PcacheSize().
34510 SQLITE_PRIVATE void sqlite3PcacheOpen(
34511 int szPage, /* Size of every page */
34512 int szExtra, /* Extra space associated with each page */
34513 int bPurgeable, /* True if pages are on backing store */
34514 int (*xStress)(void*,PgHdr*),/* Call to try to make pages clean */
34515 void *pStress, /* Argument to xStress */
34516 PCache *p /* Preallocated space for the PCache */
34518 memset(p, 0, sizeof(PCache));
34519 p->szPage = szPage;
34520 p->szExtra = szExtra;
34521 p->bPurgeable = bPurgeable;
34522 p->xStress = xStress;
34523 p->pStress = pStress;
34524 p->nMax = 100;
34528 ** Change the page size for PCache object. The caller must ensure that there
34529 ** are no outstanding page references when this function is called.
34531 SQLITE_PRIVATE void sqlite3PcacheSetPageSize(PCache *pCache, int szPage){
34532 assert( pCache->nRef==0 && pCache->pDirty==0 );
34533 if( pCache->pCache ){
34534 sqlite3GlobalConfig.pcache.xDestroy(pCache->pCache);
34535 pCache->pCache = 0;
34536 pCache->pPage1 = 0;
34538 pCache->szPage = szPage;
34542 ** Try to obtain a page from the cache.
34544 SQLITE_PRIVATE int sqlite3PcacheFetch(
34545 PCache *pCache, /* Obtain the page from this cache */
34546 Pgno pgno, /* Page number to obtain */
34547 int createFlag, /* If true, create page if it does not exist already */
34548 PgHdr **ppPage /* Write the page here */
34550 PgHdr *pPage = 0;
34551 int eCreate;
34553 assert( pCache!=0 );
34554 assert( createFlag==1 || createFlag==0 );
34555 assert( pgno>0 );
34557 /* If the pluggable cache (sqlite3_pcache*) has not been allocated,
34558 ** allocate it now.
34560 if( !pCache->pCache && createFlag ){
34561 sqlite3_pcache *p;
34562 int nByte;
34563 nByte = pCache->szPage + pCache->szExtra + sizeof(PgHdr);
34564 p = sqlite3GlobalConfig.pcache.xCreate(nByte, pCache->bPurgeable);
34565 if( !p ){
34566 return SQLITE_NOMEM;
34568 sqlite3GlobalConfig.pcache.xCachesize(p, pCache->nMax);
34569 pCache->pCache = p;
34572 eCreate = createFlag * (1 + (!pCache->bPurgeable || !pCache->pDirty));
34573 if( pCache->pCache ){
34574 pPage = sqlite3GlobalConfig.pcache.xFetch(pCache->pCache, pgno, eCreate);
34577 if( !pPage && eCreate==1 ){
34578 PgHdr *pPg;
34580 /* Find a dirty page to write-out and recycle. First try to find a
34581 ** page that does not require a journal-sync (one with PGHDR_NEED_SYNC
34582 ** cleared), but if that is not possible settle for any other
34583 ** unreferenced dirty page.
34585 expensive_assert( pcacheCheckSynced(pCache) );
34586 for(pPg=pCache->pSynced;
34587 pPg && (pPg->nRef || (pPg->flags&PGHDR_NEED_SYNC));
34588 pPg=pPg->pDirtyPrev
34590 pCache->pSynced = pPg;
34591 if( !pPg ){
34592 for(pPg=pCache->pDirtyTail; pPg && pPg->nRef; pPg=pPg->pDirtyPrev);
34594 if( pPg ){
34595 int rc;
34596 rc = pCache->xStress(pCache->pStress, pPg);
34597 if( rc!=SQLITE_OK && rc!=SQLITE_BUSY ){
34598 return rc;
34602 pPage = sqlite3GlobalConfig.pcache.xFetch(pCache->pCache, pgno, 2);
34605 if( pPage ){
34606 if( !pPage->pData ){
34607 memset(pPage, 0, sizeof(PgHdr));
34608 pPage->pData = (void *)&pPage[1];
34609 pPage->pExtra = (void*)&((char *)pPage->pData)[pCache->szPage];
34610 memset(pPage->pExtra, 0, pCache->szExtra);
34611 pPage->pCache = pCache;
34612 pPage->pgno = pgno;
34614 assert( pPage->pCache==pCache );
34615 assert( pPage->pgno==pgno );
34616 assert( pPage->pData==(void *)&pPage[1] );
34617 assert( pPage->pExtra==(void *)&((char *)&pPage[1])[pCache->szPage] );
34619 if( 0==pPage->nRef ){
34620 pCache->nRef++;
34622 pPage->nRef++;
34623 if( pgno==1 ){
34624 pCache->pPage1 = pPage;
34627 *ppPage = pPage;
34628 return (pPage==0 && eCreate) ? SQLITE_NOMEM : SQLITE_OK;
34632 ** Decrement the reference count on a page. If the page is clean and the
34633 ** reference count drops to 0, then it is made elible for recycling.
34635 SQLITE_PRIVATE void sqlite3PcacheRelease(PgHdr *p){
34636 assert( p->nRef>0 );
34637 p->nRef--;
34638 if( p->nRef==0 ){
34639 PCache *pCache = p->pCache;
34640 pCache->nRef--;
34641 if( (p->flags&PGHDR_DIRTY)==0 ){
34642 pcacheUnpin(p);
34643 }else{
34644 /* Move the page to the head of the dirty list. */
34645 pcacheRemoveFromDirtyList(p);
34646 pcacheAddToDirtyList(p);
34652 ** Increase the reference count of a supplied page by 1.
34654 SQLITE_PRIVATE void sqlite3PcacheRef(PgHdr *p){
34655 assert(p->nRef>0);
34656 p->nRef++;
34660 ** Drop a page from the cache. There must be exactly one reference to the
34661 ** page. This function deletes that reference, so after it returns the
34662 ** page pointed to by p is invalid.
34664 SQLITE_PRIVATE void sqlite3PcacheDrop(PgHdr *p){
34665 PCache *pCache;
34666 assert( p->nRef==1 );
34667 if( p->flags&PGHDR_DIRTY ){
34668 pcacheRemoveFromDirtyList(p);
34670 pCache = p->pCache;
34671 pCache->nRef--;
34672 if( p->pgno==1 ){
34673 pCache->pPage1 = 0;
34675 sqlite3GlobalConfig.pcache.xUnpin(pCache->pCache, p, 1);
34679 ** Make sure the page is marked as dirty. If it isn't dirty already,
34680 ** make it so.
34682 SQLITE_PRIVATE void sqlite3PcacheMakeDirty(PgHdr *p){
34683 p->flags &= ~PGHDR_DONT_WRITE;
34684 assert( p->nRef>0 );
34685 if( 0==(p->flags & PGHDR_DIRTY) ){
34686 p->flags |= PGHDR_DIRTY;
34687 pcacheAddToDirtyList( p);
34692 ** Make sure the page is marked as clean. If it isn't clean already,
34693 ** make it so.
34695 SQLITE_PRIVATE void sqlite3PcacheMakeClean(PgHdr *p){
34696 if( (p->flags & PGHDR_DIRTY) ){
34697 pcacheRemoveFromDirtyList(p);
34698 p->flags &= ~(PGHDR_DIRTY|PGHDR_NEED_SYNC);
34699 if( p->nRef==0 ){
34700 pcacheUnpin(p);
34706 ** Make every page in the cache clean.
34708 SQLITE_PRIVATE void sqlite3PcacheCleanAll(PCache *pCache){
34709 PgHdr *p;
34710 while( (p = pCache->pDirty)!=0 ){
34711 sqlite3PcacheMakeClean(p);
34716 ** Clear the PGHDR_NEED_SYNC flag from all dirty pages.
34718 SQLITE_PRIVATE void sqlite3PcacheClearSyncFlags(PCache *pCache){
34719 PgHdr *p;
34720 for(p=pCache->pDirty; p; p=p->pDirtyNext){
34721 p->flags &= ~PGHDR_NEED_SYNC;
34723 pCache->pSynced = pCache->pDirtyTail;
34727 ** Change the page number of page p to newPgno.
34729 SQLITE_PRIVATE void sqlite3PcacheMove(PgHdr *p, Pgno newPgno){
34730 PCache *pCache = p->pCache;
34731 assert( p->nRef>0 );
34732 assert( newPgno>0 );
34733 sqlite3GlobalConfig.pcache.xRekey(pCache->pCache, p, p->pgno, newPgno);
34734 p->pgno = newPgno;
34735 if( (p->flags&PGHDR_DIRTY) && (p->flags&PGHDR_NEED_SYNC) ){
34736 pcacheRemoveFromDirtyList(p);
34737 pcacheAddToDirtyList(p);
34742 ** Drop every cache entry whose page number is greater than "pgno". The
34743 ** caller must ensure that there are no outstanding references to any pages
34744 ** other than page 1 with a page number greater than pgno.
34746 ** If there is a reference to page 1 and the pgno parameter passed to this
34747 ** function is 0, then the data area associated with page 1 is zeroed, but
34748 ** the page object is not dropped.
34750 SQLITE_PRIVATE void sqlite3PcacheTruncate(PCache *pCache, Pgno pgno){
34751 if( pCache->pCache ){
34752 PgHdr *p;
34753 PgHdr *pNext;
34754 for(p=pCache->pDirty; p; p=pNext){
34755 pNext = p->pDirtyNext;
34756 /* This routine never gets call with a positive pgno except right
34757 ** after sqlite3PcacheCleanAll(). So if there are dirty pages,
34758 ** it must be that pgno==0.
34760 assert( p->pgno>0 );
34761 if( ALWAYS(p->pgno>pgno) ){
34762 assert( p->flags&PGHDR_DIRTY );
34763 sqlite3PcacheMakeClean(p);
34766 if( pgno==0 && pCache->pPage1 ){
34767 memset(pCache->pPage1->pData, 0, pCache->szPage);
34768 pgno = 1;
34770 sqlite3GlobalConfig.pcache.xTruncate(pCache->pCache, pgno+1);
34775 ** Close a cache.
34777 SQLITE_PRIVATE void sqlite3PcacheClose(PCache *pCache){
34778 if( pCache->pCache ){
34779 sqlite3GlobalConfig.pcache.xDestroy(pCache->pCache);
34784 ** Discard the contents of the cache.
34786 SQLITE_PRIVATE void sqlite3PcacheClear(PCache *pCache){
34787 sqlite3PcacheTruncate(pCache, 0);
34791 ** Merge two lists of pages connected by pDirty and in pgno order.
34792 ** Do not both fixing the pDirtyPrev pointers.
34794 static PgHdr *pcacheMergeDirtyList(PgHdr *pA, PgHdr *pB){
34795 PgHdr result, *pTail;
34796 pTail = &result;
34797 while( pA && pB ){
34798 if( pA->pgno<pB->pgno ){
34799 pTail->pDirty = pA;
34800 pTail = pA;
34801 pA = pA->pDirty;
34802 }else{
34803 pTail->pDirty = pB;
34804 pTail = pB;
34805 pB = pB->pDirty;
34808 if( pA ){
34809 pTail->pDirty = pA;
34810 }else if( pB ){
34811 pTail->pDirty = pB;
34812 }else{
34813 pTail->pDirty = 0;
34815 return result.pDirty;
34819 ** Sort the list of pages in accending order by pgno. Pages are
34820 ** connected by pDirty pointers. The pDirtyPrev pointers are
34821 ** corrupted by this sort.
34823 ** Since there cannot be more than 2^31 distinct pages in a database,
34824 ** there cannot be more than 31 buckets required by the merge sorter.
34825 ** One extra bucket is added to catch overflow in case something
34826 ** ever changes to make the previous sentence incorrect.
34828 #define N_SORT_BUCKET 32
34829 static PgHdr *pcacheSortDirtyList(PgHdr *pIn){
34830 PgHdr *a[N_SORT_BUCKET], *p;
34831 int i;
34832 memset(a, 0, sizeof(a));
34833 while( pIn ){
34834 p = pIn;
34835 pIn = p->pDirty;
34836 p->pDirty = 0;
34837 for(i=0; ALWAYS(i<N_SORT_BUCKET-1); i++){
34838 if( a[i]==0 ){
34839 a[i] = p;
34840 break;
34841 }else{
34842 p = pcacheMergeDirtyList(a[i], p);
34843 a[i] = 0;
34846 if( NEVER(i==N_SORT_BUCKET-1) ){
34847 /* To get here, there need to be 2^(N_SORT_BUCKET) elements in
34848 ** the input list. But that is impossible.
34850 a[i] = pcacheMergeDirtyList(a[i], p);
34853 p = a[0];
34854 for(i=1; i<N_SORT_BUCKET; i++){
34855 p = pcacheMergeDirtyList(p, a[i]);
34857 return p;
34861 ** Return a list of all dirty pages in the cache, sorted by page number.
34863 SQLITE_PRIVATE PgHdr *sqlite3PcacheDirtyList(PCache *pCache){
34864 PgHdr *p;
34865 for(p=pCache->pDirty; p; p=p->pDirtyNext){
34866 p->pDirty = p->pDirtyNext;
34868 return pcacheSortDirtyList(pCache->pDirty);
34872 ** Return the total number of referenced pages held by the cache.
34874 SQLITE_PRIVATE int sqlite3PcacheRefCount(PCache *pCache){
34875 return pCache->nRef;
34879 ** Return the number of references to the page supplied as an argument.
34881 SQLITE_PRIVATE int sqlite3PcachePageRefcount(PgHdr *p){
34882 return p->nRef;
34886 ** Return the total number of pages in the cache.
34888 SQLITE_PRIVATE int sqlite3PcachePagecount(PCache *pCache){
34889 int nPage = 0;
34890 if( pCache->pCache ){
34891 nPage = sqlite3GlobalConfig.pcache.xPagecount(pCache->pCache);
34893 return nPage;
34897 ** Get the suggested cache-size value.
34899 SQLITE_PRIVATE int sqlite3PcacheGetCachesize(PCache *pCache){
34900 return pCache->nMax;
34904 ** Set the suggested cache-size value.
34906 SQLITE_PRIVATE void sqlite3PcacheSetCachesize(PCache *pCache, int mxPage){
34907 pCache->nMax = mxPage;
34908 if( pCache->pCache ){
34909 sqlite3GlobalConfig.pcache.xCachesize(pCache->pCache, mxPage);
34913 #if defined(SQLITE_CHECK_PAGES) || defined(SQLITE_DEBUG)
34915 ** For all dirty pages currently in the cache, invoke the specified
34916 ** callback. This is only used if the SQLITE_CHECK_PAGES macro is
34917 ** defined.
34919 SQLITE_PRIVATE void sqlite3PcacheIterateDirty(PCache *pCache, void (*xIter)(PgHdr *)){
34920 PgHdr *pDirty;
34921 for(pDirty=pCache->pDirty; pDirty; pDirty=pDirty->pDirtyNext){
34922 xIter(pDirty);
34925 #endif
34927 /************** End of pcache.c **********************************************/
34928 /************** Begin file pcache1.c *****************************************/
34930 ** 2008 November 05
34932 ** The author disclaims copyright to this source code. In place of
34933 ** a legal notice, here is a blessing:
34935 ** May you do good and not evil.
34936 ** May you find forgiveness for yourself and forgive others.
34937 ** May you share freely, never taking more than you give.
34939 *************************************************************************
34941 ** This file implements the default page cache implementation (the
34942 ** sqlite3_pcache interface). It also contains part of the implementation
34943 ** of the SQLITE_CONFIG_PAGECACHE and sqlite3_release_memory() features.
34944 ** If the default page cache implementation is overriden, then neither of
34945 ** these two features are available.
34949 typedef struct PCache1 PCache1;
34950 typedef struct PgHdr1 PgHdr1;
34951 typedef struct PgFreeslot PgFreeslot;
34952 typedef struct PGroup PGroup;
34954 /* Each page cache (or PCache) belongs to a PGroup. A PGroup is a set
34955 ** of one or more PCaches that are able to recycle each others unpinned
34956 ** pages when they are under memory pressure. A PGroup is an instance of
34957 ** the following object.
34959 ** This page cache implementation works in one of two modes:
34961 ** (1) Every PCache is the sole member of its own PGroup. There is
34962 ** one PGroup per PCache.
34964 ** (2) There is a single global PGroup that all PCaches are a member
34965 ** of.
34967 ** Mode 1 uses more memory (since PCache instances are not able to rob
34968 ** unused pages from other PCaches) but it also operates without a mutex,
34969 ** and is therefore often faster. Mode 2 requires a mutex in order to be
34970 ** threadsafe, but is able recycle pages more efficient.
34972 ** For mode (1), PGroup.mutex is NULL. For mode (2) there is only a single
34973 ** PGroup which is the pcache1.grp global variable and its mutex is
34974 ** SQLITE_MUTEX_STATIC_LRU.
34976 struct PGroup {
34977 sqlite3_mutex *mutex; /* MUTEX_STATIC_LRU or NULL */
34978 int nMaxPage; /* Sum of nMax for purgeable caches */
34979 int nMinPage; /* Sum of nMin for purgeable caches */
34980 int mxPinned; /* nMaxpage + 10 - nMinPage */
34981 int nCurrentPage; /* Number of purgeable pages allocated */
34982 PgHdr1 *pLruHead, *pLruTail; /* LRU list of unpinned pages */
34985 /* Each page cache is an instance of the following object. Every
34986 ** open database file (including each in-memory database and each
34987 ** temporary or transient database) has a single page cache which
34988 ** is an instance of this object.
34990 ** Pointers to structures of this type are cast and returned as
34991 ** opaque sqlite3_pcache* handles.
34993 struct PCache1 {
34994 /* Cache configuration parameters. Page size (szPage) and the purgeable
34995 ** flag (bPurgeable) are set when the cache is created. nMax may be
34996 ** modified at any time by a call to the pcache1CacheSize() method.
34997 ** The PGroup mutex must be held when accessing nMax.
34999 PGroup *pGroup; /* PGroup this cache belongs to */
35000 int szPage; /* Size of allocated pages in bytes */
35001 int bPurgeable; /* True if cache is purgeable */
35002 unsigned int nMin; /* Minimum number of pages reserved */
35003 unsigned int nMax; /* Configured "cache_size" value */
35004 unsigned int n90pct; /* nMax*9/10 */
35006 /* Hash table of all pages. The following variables may only be accessed
35007 ** when the accessor is holding the PGroup mutex.
35009 unsigned int nRecyclable; /* Number of pages in the LRU list */
35010 unsigned int nPage; /* Total number of pages in apHash */
35011 unsigned int nHash; /* Number of slots in apHash[] */
35012 PgHdr1 **apHash; /* Hash table for fast lookup by key */
35014 unsigned int iMaxKey; /* Largest key seen since xTruncate() */
35018 ** Each cache entry is represented by an instance of the following
35019 ** structure. A buffer of PgHdr1.pCache->szPage bytes is allocated
35020 ** directly before this structure in memory (see the PGHDR1_TO_PAGE()
35021 ** macro below).
35023 struct PgHdr1 {
35024 unsigned int iKey; /* Key value (page number) */
35025 PgHdr1 *pNext; /* Next in hash table chain */
35026 PCache1 *pCache; /* Cache that currently owns this page */
35027 PgHdr1 *pLruNext; /* Next in LRU list of unpinned pages */
35028 PgHdr1 *pLruPrev; /* Previous in LRU list of unpinned pages */
35032 ** Free slots in the allocator used to divide up the buffer provided using
35033 ** the SQLITE_CONFIG_PAGECACHE mechanism.
35035 struct PgFreeslot {
35036 PgFreeslot *pNext; /* Next free slot */
35040 ** Global data used by this cache.
35042 static SQLITE_WSD struct PCacheGlobal {
35043 PGroup grp; /* The global PGroup for mode (2) */
35045 /* Variables related to SQLITE_CONFIG_PAGECACHE settings. The
35046 ** szSlot, nSlot, pStart, pEnd, nReserve, and isInit values are all
35047 ** fixed at sqlite3_initialize() time and do not require mutex protection.
35048 ** The nFreeSlot and pFree values do require mutex protection.
35050 int isInit; /* True if initialized */
35051 int szSlot; /* Size of each free slot */
35052 int nSlot; /* The number of pcache slots */
35053 int nReserve; /* Try to keep nFreeSlot above this */
35054 void *pStart, *pEnd; /* Bounds of pagecache malloc range */
35055 /* Above requires no mutex. Use mutex below for variable that follow. */
35056 sqlite3_mutex *mutex; /* Mutex for accessing the following: */
35057 int nFreeSlot; /* Number of unused pcache slots */
35058 PgFreeslot *pFree; /* Free page blocks */
35059 /* The following value requires a mutex to change. We skip the mutex on
35060 ** reading because (1) most platforms read a 32-bit integer atomically and
35061 ** (2) even if an incorrect value is read, no great harm is done since this
35062 ** is really just an optimization. */
35063 int bUnderPressure; /* True if low on PAGECACHE memory */
35064 } pcache1_g;
35067 ** All code in this file should access the global structure above via the
35068 ** alias "pcache1". This ensures that the WSD emulation is used when
35069 ** compiling for systems that do not support real WSD.
35071 #define pcache1 (GLOBAL(struct PCacheGlobal, pcache1_g))
35074 ** When a PgHdr1 structure is allocated, the associated PCache1.szPage
35075 ** bytes of data are located directly before it in memory (i.e. the total
35076 ** size of the allocation is sizeof(PgHdr1)+PCache1.szPage byte). The
35077 ** PGHDR1_TO_PAGE() macro takes a pointer to a PgHdr1 structure as
35078 ** an argument and returns a pointer to the associated block of szPage
35079 ** bytes. The PAGE_TO_PGHDR1() macro does the opposite: its argument is
35080 ** a pointer to a block of szPage bytes of data and the return value is
35081 ** a pointer to the associated PgHdr1 structure.
35083 ** assert( PGHDR1_TO_PAGE(PAGE_TO_PGHDR1(pCache, X))==X );
35085 #define PGHDR1_TO_PAGE(p) (void*)(((char*)p) - p->pCache->szPage)
35086 #define PAGE_TO_PGHDR1(c, p) (PgHdr1*)(((char*)p) + c->szPage)
35089 ** Macros to enter and leave the PCache LRU mutex.
35091 #define pcache1EnterMutex(X) sqlite3_mutex_enter((X)->mutex)
35092 #define pcache1LeaveMutex(X) sqlite3_mutex_leave((X)->mutex)
35094 /******************************************************************************/
35095 /******** Page Allocation/SQLITE_CONFIG_PCACHE Related Functions **************/
35098 ** This function is called during initialization if a static buffer is
35099 ** supplied to use for the page-cache by passing the SQLITE_CONFIG_PAGECACHE
35100 ** verb to sqlite3_config(). Parameter pBuf points to an allocation large
35101 ** enough to contain 'n' buffers of 'sz' bytes each.
35103 ** This routine is called from sqlite3_initialize() and so it is guaranteed
35104 ** to be serialized already. There is no need for further mutexing.
35106 SQLITE_PRIVATE void sqlite3PCacheBufferSetup(void *pBuf, int sz, int n){
35107 if( pcache1.isInit ){
35108 PgFreeslot *p;
35109 sz = ROUNDDOWN8(sz);
35110 pcache1.szSlot = sz;
35111 pcache1.nSlot = pcache1.nFreeSlot = n;
35112 pcache1.nReserve = n>90 ? 10 : (n/10 + 1);
35113 pcache1.pStart = pBuf;
35114 pcache1.pFree = 0;
35115 pcache1.bUnderPressure = 0;
35116 while( n-- ){
35117 p = (PgFreeslot*)pBuf;
35118 p->pNext = pcache1.pFree;
35119 pcache1.pFree = p;
35120 pBuf = (void*)&((char*)pBuf)[sz];
35122 pcache1.pEnd = pBuf;
35127 ** Malloc function used within this file to allocate space from the buffer
35128 ** configured using sqlite3_config(SQLITE_CONFIG_PAGECACHE) option. If no
35129 ** such buffer exists or there is no space left in it, this function falls
35130 ** back to sqlite3Malloc().
35132 ** Multiple threads can run this routine at the same time. Global variables
35133 ** in pcache1 need to be protected via mutex.
35135 static void *pcache1Alloc(int nByte){
35136 void *p = 0;
35137 assert( sqlite3_mutex_notheld(pcache1.grp.mutex) );
35138 sqlite3StatusSet(SQLITE_STATUS_PAGECACHE_SIZE, nByte);
35139 if( nByte<=pcache1.szSlot ){
35140 sqlite3_mutex_enter(pcache1.mutex);
35141 p = (PgHdr1 *)pcache1.pFree;
35142 if( p ){
35143 pcache1.pFree = pcache1.pFree->pNext;
35144 pcache1.nFreeSlot--;
35145 pcache1.bUnderPressure = pcache1.nFreeSlot<pcache1.nReserve;
35146 assert( pcache1.nFreeSlot>=0 );
35147 sqlite3StatusAdd(SQLITE_STATUS_PAGECACHE_USED, 1);
35149 sqlite3_mutex_leave(pcache1.mutex);
35151 if( p==0 ){
35152 /* Memory is not available in the SQLITE_CONFIG_PAGECACHE pool. Get
35153 ** it from sqlite3Malloc instead.
35155 p = sqlite3Malloc(nByte);
35156 if( p ){
35157 int sz = sqlite3MallocSize(p);
35158 sqlite3_mutex_enter(pcache1.mutex);
35159 sqlite3StatusAdd(SQLITE_STATUS_PAGECACHE_OVERFLOW, sz);
35160 sqlite3_mutex_leave(pcache1.mutex);
35162 sqlite3MemdebugSetType(p, MEMTYPE_PCACHE);
35164 return p;
35168 ** Free an allocated buffer obtained from pcache1Alloc().
35170 static void pcache1Free(void *p){
35171 if( p==0 ) return;
35172 if( p>=pcache1.pStart && p<pcache1.pEnd ){
35173 PgFreeslot *pSlot;
35174 sqlite3_mutex_enter(pcache1.mutex);
35175 sqlite3StatusAdd(SQLITE_STATUS_PAGECACHE_USED, -1);
35176 pSlot = (PgFreeslot*)p;
35177 pSlot->pNext = pcache1.pFree;
35178 pcache1.pFree = pSlot;
35179 pcache1.nFreeSlot++;
35180 pcache1.bUnderPressure = pcache1.nFreeSlot<pcache1.nReserve;
35181 assert( pcache1.nFreeSlot<=pcache1.nSlot );
35182 sqlite3_mutex_leave(pcache1.mutex);
35183 }else{
35184 int iSize;
35185 assert( sqlite3MemdebugHasType(p, MEMTYPE_PCACHE) );
35186 sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
35187 iSize = sqlite3MallocSize(p);
35188 sqlite3_mutex_enter(pcache1.mutex);
35189 sqlite3StatusAdd(SQLITE_STATUS_PAGECACHE_OVERFLOW, -iSize);
35190 sqlite3_mutex_leave(pcache1.mutex);
35191 sqlite3_free(p);
35195 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
35197 ** Return the size of a pcache allocation
35199 static int pcache1MemSize(void *p){
35200 if( p>=pcache1.pStart && p<pcache1.pEnd ){
35201 return pcache1.szSlot;
35202 }else{
35203 int iSize;
35204 assert( sqlite3MemdebugHasType(p, MEMTYPE_PCACHE) );
35205 sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
35206 iSize = sqlite3MallocSize(p);
35207 sqlite3MemdebugSetType(p, MEMTYPE_PCACHE);
35208 return iSize;
35211 #endif /* SQLITE_ENABLE_MEMORY_MANAGEMENT */
35214 ** Allocate a new page object initially associated with cache pCache.
35216 static PgHdr1 *pcache1AllocPage(PCache1 *pCache){
35217 int nByte = sizeof(PgHdr1) + pCache->szPage;
35218 void *pPg = pcache1Alloc(nByte);
35219 PgHdr1 *p;
35220 if( pPg ){
35221 p = PAGE_TO_PGHDR1(pCache, pPg);
35222 if( pCache->bPurgeable ){
35223 pCache->pGroup->nCurrentPage++;
35225 }else{
35226 p = 0;
35228 return p;
35232 ** Free a page object allocated by pcache1AllocPage().
35234 ** The pointer is allowed to be NULL, which is prudent. But it turns out
35235 ** that the current implementation happens to never call this routine
35236 ** with a NULL pointer, so we mark the NULL test with ALWAYS().
35238 static void pcache1FreePage(PgHdr1 *p){
35239 if( ALWAYS(p) ){
35240 PCache1 *pCache = p->pCache;
35241 if( pCache->bPurgeable ){
35242 pCache->pGroup->nCurrentPage--;
35244 pcache1Free(PGHDR1_TO_PAGE(p));
35249 ** Malloc function used by SQLite to obtain space from the buffer configured
35250 ** using sqlite3_config(SQLITE_CONFIG_PAGECACHE) option. If no such buffer
35251 ** exists, this function falls back to sqlite3Malloc().
35253 SQLITE_PRIVATE void *sqlite3PageMalloc(int sz){
35254 return pcache1Alloc(sz);
35258 ** Free an allocated buffer obtained from sqlite3PageMalloc().
35260 SQLITE_PRIVATE void sqlite3PageFree(void *p){
35261 pcache1Free(p);
35266 ** Return true if it desirable to avoid allocating a new page cache
35267 ** entry.
35269 ** If memory was allocated specifically to the page cache using
35270 ** SQLITE_CONFIG_PAGECACHE but that memory has all been used, then
35271 ** it is desirable to avoid allocating a new page cache entry because
35272 ** presumably SQLITE_CONFIG_PAGECACHE was suppose to be sufficient
35273 ** for all page cache needs and we should not need to spill the
35274 ** allocation onto the heap.
35276 ** Or, the heap is used for all page cache memory put the heap is
35277 ** under memory pressure, then again it is desirable to avoid
35278 ** allocating a new page cache entry in order to avoid stressing
35279 ** the heap even further.
35281 static int pcache1UnderMemoryPressure(PCache1 *pCache){
35282 if( pcache1.nSlot && pCache->szPage<=pcache1.szSlot ){
35283 return pcache1.bUnderPressure;
35284 }else{
35285 return sqlite3HeapNearlyFull();
35289 /******************************************************************************/
35290 /******** General Implementation Functions ************************************/
35293 ** This function is used to resize the hash table used by the cache passed
35294 ** as the first argument.
35296 ** The PCache mutex must be held when this function is called.
35298 static int pcache1ResizeHash(PCache1 *p){
35299 PgHdr1 **apNew;
35300 unsigned int nNew;
35301 unsigned int i;
35303 assert( sqlite3_mutex_held(p->pGroup->mutex) );
35305 nNew = p->nHash*2;
35306 if( nNew<256 ){
35307 nNew = 256;
35310 pcache1LeaveMutex(p->pGroup);
35311 if( p->nHash ){ sqlite3BeginBenignMalloc(); }
35312 apNew = (PgHdr1 **)sqlite3_malloc(sizeof(PgHdr1 *)*nNew);
35313 if( p->nHash ){ sqlite3EndBenignMalloc(); }
35314 pcache1EnterMutex(p->pGroup);
35315 if( apNew ){
35316 memset(apNew, 0, sizeof(PgHdr1 *)*nNew);
35317 for(i=0; i<p->nHash; i++){
35318 PgHdr1 *pPage;
35319 PgHdr1 *pNext = p->apHash[i];
35320 while( (pPage = pNext)!=0 ){
35321 unsigned int h = pPage->iKey % nNew;
35322 pNext = pPage->pNext;
35323 pPage->pNext = apNew[h];
35324 apNew[h] = pPage;
35327 sqlite3_free(p->apHash);
35328 p->apHash = apNew;
35329 p->nHash = nNew;
35332 return (p->apHash ? SQLITE_OK : SQLITE_NOMEM);
35336 ** This function is used internally to remove the page pPage from the
35337 ** PGroup LRU list, if is part of it. If pPage is not part of the PGroup
35338 ** LRU list, then this function is a no-op.
35340 ** The PGroup mutex must be held when this function is called.
35342 ** If pPage is NULL then this routine is a no-op.
35344 static void pcache1PinPage(PgHdr1 *pPage){
35345 PCache1 *pCache;
35346 PGroup *pGroup;
35348 if( pPage==0 ) return;
35349 pCache = pPage->pCache;
35350 pGroup = pCache->pGroup;
35351 assert( sqlite3_mutex_held(pGroup->mutex) );
35352 if( pPage->pLruNext || pPage==pGroup->pLruTail ){
35353 if( pPage->pLruPrev ){
35354 pPage->pLruPrev->pLruNext = pPage->pLruNext;
35356 if( pPage->pLruNext ){
35357 pPage->pLruNext->pLruPrev = pPage->pLruPrev;
35359 if( pGroup->pLruHead==pPage ){
35360 pGroup->pLruHead = pPage->pLruNext;
35362 if( pGroup->pLruTail==pPage ){
35363 pGroup->pLruTail = pPage->pLruPrev;
35365 pPage->pLruNext = 0;
35366 pPage->pLruPrev = 0;
35367 pPage->pCache->nRecyclable--;
35373 ** Remove the page supplied as an argument from the hash table
35374 ** (PCache1.apHash structure) that it is currently stored in.
35376 ** The PGroup mutex must be held when this function is called.
35378 static void pcache1RemoveFromHash(PgHdr1 *pPage){
35379 unsigned int h;
35380 PCache1 *pCache = pPage->pCache;
35381 PgHdr1 **pp;
35383 assert( sqlite3_mutex_held(pCache->pGroup->mutex) );
35384 h = pPage->iKey % pCache->nHash;
35385 for(pp=&pCache->apHash[h]; (*pp)!=pPage; pp=&(*pp)->pNext);
35386 *pp = (*pp)->pNext;
35388 pCache->nPage--;
35392 ** If there are currently more than nMaxPage pages allocated, try
35393 ** to recycle pages to reduce the number allocated to nMaxPage.
35395 static void pcache1EnforceMaxPage(PGroup *pGroup){
35396 assert( sqlite3_mutex_held(pGroup->mutex) );
35397 while( pGroup->nCurrentPage>pGroup->nMaxPage && pGroup->pLruTail ){
35398 PgHdr1 *p = pGroup->pLruTail;
35399 assert( p->pCache->pGroup==pGroup );
35400 pcache1PinPage(p);
35401 pcache1RemoveFromHash(p);
35402 pcache1FreePage(p);
35407 ** Discard all pages from cache pCache with a page number (key value)
35408 ** greater than or equal to iLimit. Any pinned pages that meet this
35409 ** criteria are unpinned before they are discarded.
35411 ** The PCache mutex must be held when this function is called.
35413 static void pcache1TruncateUnsafe(
35414 PCache1 *pCache, /* The cache to truncate */
35415 unsigned int iLimit /* Drop pages with this pgno or larger */
35417 TESTONLY( unsigned int nPage = 0; ) /* To assert pCache->nPage is correct */
35418 unsigned int h;
35419 assert( sqlite3_mutex_held(pCache->pGroup->mutex) );
35420 for(h=0; h<pCache->nHash; h++){
35421 PgHdr1 **pp = &pCache->apHash[h];
35422 PgHdr1 *pPage;
35423 while( (pPage = *pp)!=0 ){
35424 if( pPage->iKey>=iLimit ){
35425 pCache->nPage--;
35426 *pp = pPage->pNext;
35427 pcache1PinPage(pPage);
35428 pcache1FreePage(pPage);
35429 }else{
35430 pp = &pPage->pNext;
35431 TESTONLY( nPage++; )
35435 assert( pCache->nPage==nPage );
35438 /******************************************************************************/
35439 /******** sqlite3_pcache Methods **********************************************/
35442 ** Implementation of the sqlite3_pcache.xInit method.
35444 static int pcache1Init(void *NotUsed){
35445 UNUSED_PARAMETER(NotUsed);
35446 assert( pcache1.isInit==0 );
35447 memset(&pcache1, 0, sizeof(pcache1));
35448 if( sqlite3GlobalConfig.bCoreMutex ){
35449 pcache1.grp.mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_LRU);
35450 pcache1.mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_PMEM);
35452 pcache1.grp.mxPinned = 10;
35453 pcache1.isInit = 1;
35454 return SQLITE_OK;
35458 ** Implementation of the sqlite3_pcache.xShutdown method.
35459 ** Note that the static mutex allocated in xInit does
35460 ** not need to be freed.
35462 static void pcache1Shutdown(void *NotUsed){
35463 UNUSED_PARAMETER(NotUsed);
35464 assert( pcache1.isInit!=0 );
35465 memset(&pcache1, 0, sizeof(pcache1));
35469 ** Implementation of the sqlite3_pcache.xCreate method.
35471 ** Allocate a new cache.
35473 static sqlite3_pcache *pcache1Create(int szPage, int bPurgeable){
35474 PCache1 *pCache; /* The newly created page cache */
35475 PGroup *pGroup; /* The group the new page cache will belong to */
35476 int sz; /* Bytes of memory required to allocate the new cache */
35479 ** The separateCache variable is true if each PCache has its own private
35480 ** PGroup. In other words, separateCache is true for mode (1) where no
35481 ** mutexing is required.
35483 ** * Always use separate caches (mode-1) if SQLITE_SEPARATE_CACHE_POOLS
35485 ** * Always use a unified cache (mode-2) if ENABLE_MEMORY_MANAGEMENT
35487 ** * Always use a unified cache in single-threaded applications
35489 ** * Otherwise (if multi-threaded and ENABLE_MEMORY_MANAGEMENT is off)
35490 ** use separate caches (mode-1)
35492 #ifdef SQLITE_SEPARATE_CACHE_POOLS
35493 const int separateCache = 1;
35494 #elif defined(SQLITE_ENABLE_MEMORY_MANAGEMENT) || SQLITE_THREADSAFE==0
35495 const int separateCache = 0;
35496 #else
35497 int separateCache = sqlite3GlobalConfig.bCoreMutex>0;
35498 #endif
35500 sz = sizeof(PCache1) + sizeof(PGroup)*separateCache;
35501 pCache = (PCache1 *)sqlite3_malloc(sz);
35502 if( pCache ){
35503 memset(pCache, 0, sz);
35504 if( separateCache ){
35505 pGroup = (PGroup*)&pCache[1];
35506 pGroup->mxPinned = 10;
35507 }else{
35508 pGroup = &pcache1_g.grp;
35510 pCache->pGroup = pGroup;
35511 pCache->szPage = szPage;
35512 pCache->bPurgeable = (bPurgeable ? 1 : 0);
35513 if( bPurgeable ){
35514 pCache->nMin = 10;
35515 pcache1EnterMutex(pGroup);
35516 pGroup->nMinPage += pCache->nMin;
35517 pGroup->mxPinned = pGroup->nMaxPage + 10 - pGroup->nMinPage;
35518 pcache1LeaveMutex(pGroup);
35521 return (sqlite3_pcache *)pCache;
35525 ** Implementation of the sqlite3_pcache.xCachesize method.
35527 ** Configure the cache_size limit for a cache.
35529 static void pcache1Cachesize(sqlite3_pcache *p, int nMax){
35530 PCache1 *pCache = (PCache1 *)p;
35531 if( pCache->bPurgeable ){
35532 PGroup *pGroup = pCache->pGroup;
35533 pcache1EnterMutex(pGroup);
35534 pGroup->nMaxPage += (nMax - pCache->nMax);
35535 pGroup->mxPinned = pGroup->nMaxPage + 10 - pGroup->nMinPage;
35536 pCache->nMax = nMax;
35537 pCache->n90pct = pCache->nMax*9/10;
35538 pcache1EnforceMaxPage(pGroup);
35539 pcache1LeaveMutex(pGroup);
35544 ** Implementation of the sqlite3_pcache.xPagecount method.
35546 static int pcache1Pagecount(sqlite3_pcache *p){
35547 int n;
35548 PCache1 *pCache = (PCache1*)p;
35549 pcache1EnterMutex(pCache->pGroup);
35550 n = pCache->nPage;
35551 pcache1LeaveMutex(pCache->pGroup);
35552 return n;
35556 ** Implementation of the sqlite3_pcache.xFetch method.
35558 ** Fetch a page by key value.
35560 ** Whether or not a new page may be allocated by this function depends on
35561 ** the value of the createFlag argument. 0 means do not allocate a new
35562 ** page. 1 means allocate a new page if space is easily available. 2
35563 ** means to try really hard to allocate a new page.
35565 ** For a non-purgeable cache (a cache used as the storage for an in-memory
35566 ** database) there is really no difference between createFlag 1 and 2. So
35567 ** the calling function (pcache.c) will never have a createFlag of 1 on
35568 ** a non-purgable cache.
35570 ** There are three different approaches to obtaining space for a page,
35571 ** depending on the value of parameter createFlag (which may be 0, 1 or 2).
35573 ** 1. Regardless of the value of createFlag, the cache is searched for a
35574 ** copy of the requested page. If one is found, it is returned.
35576 ** 2. If createFlag==0 and the page is not already in the cache, NULL is
35577 ** returned.
35579 ** 3. If createFlag is 1, and the page is not already in the cache, then
35580 ** return NULL (do not allocate a new page) if any of the following
35581 ** conditions are true:
35583 ** (a) the number of pages pinned by the cache is greater than
35584 ** PCache1.nMax, or
35586 ** (b) the number of pages pinned by the cache is greater than
35587 ** the sum of nMax for all purgeable caches, less the sum of
35588 ** nMin for all other purgeable caches, or
35590 ** 4. If none of the first three conditions apply and the cache is marked
35591 ** as purgeable, and if one of the following is true:
35593 ** (a) The number of pages allocated for the cache is already
35594 ** PCache1.nMax, or
35596 ** (b) The number of pages allocated for all purgeable caches is
35597 ** already equal to or greater than the sum of nMax for all
35598 ** purgeable caches,
35600 ** (c) The system is under memory pressure and wants to avoid
35601 ** unnecessary pages cache entry allocations
35603 ** then attempt to recycle a page from the LRU list. If it is the right
35604 ** size, return the recycled buffer. Otherwise, free the buffer and
35605 ** proceed to step 5.
35607 ** 5. Otherwise, allocate and return a new page buffer.
35609 static void *pcache1Fetch(sqlite3_pcache *p, unsigned int iKey, int createFlag){
35610 int nPinned;
35611 PCache1 *pCache = (PCache1 *)p;
35612 PGroup *pGroup;
35613 PgHdr1 *pPage = 0;
35615 assert( pCache->bPurgeable || createFlag!=1 );
35616 assert( pCache->bPurgeable || pCache->nMin==0 );
35617 assert( pCache->bPurgeable==0 || pCache->nMin==10 );
35618 assert( pCache->nMin==0 || pCache->bPurgeable );
35619 pcache1EnterMutex(pGroup = pCache->pGroup);
35621 /* Step 1: Search the hash table for an existing entry. */
35622 if( pCache->nHash>0 ){
35623 unsigned int h = iKey % pCache->nHash;
35624 for(pPage=pCache->apHash[h]; pPage&&pPage->iKey!=iKey; pPage=pPage->pNext);
35627 /* Step 2: Abort if no existing page is found and createFlag is 0 */
35628 if( pPage || createFlag==0 ){
35629 pcache1PinPage(pPage);
35630 goto fetch_out;
35633 /* The pGroup local variable will normally be initialized by the
35634 ** pcache1EnterMutex() macro above. But if SQLITE_MUTEX_OMIT is defined,
35635 ** then pcache1EnterMutex() is a no-op, so we have to initialize the
35636 ** local variable here. Delaying the initialization of pGroup is an
35637 ** optimization: The common case is to exit the module before reaching
35638 ** this point.
35640 #ifdef SQLITE_MUTEX_OMIT
35641 pGroup = pCache->pGroup;
35642 #endif
35645 /* Step 3: Abort if createFlag is 1 but the cache is nearly full */
35646 nPinned = pCache->nPage - pCache->nRecyclable;
35647 assert( nPinned>=0 );
35648 assert( pGroup->mxPinned == pGroup->nMaxPage + 10 - pGroup->nMinPage );
35649 assert( pCache->n90pct == pCache->nMax*9/10 );
35650 if( createFlag==1 && (
35651 nPinned>=pGroup->mxPinned
35652 || nPinned>=(int)pCache->n90pct
35653 || pcache1UnderMemoryPressure(pCache)
35655 goto fetch_out;
35658 if( pCache->nPage>=pCache->nHash && pcache1ResizeHash(pCache) ){
35659 goto fetch_out;
35662 /* Step 4. Try to recycle a page. */
35663 if( pCache->bPurgeable && pGroup->pLruTail && (
35664 (pCache->nPage+1>=pCache->nMax)
35665 || pGroup->nCurrentPage>=pGroup->nMaxPage
35666 || pcache1UnderMemoryPressure(pCache)
35668 PCache1 *pOtherCache;
35669 pPage = pGroup->pLruTail;
35670 pcache1RemoveFromHash(pPage);
35671 pcache1PinPage(pPage);
35672 if( (pOtherCache = pPage->pCache)->szPage!=pCache->szPage ){
35673 pcache1FreePage(pPage);
35674 pPage = 0;
35675 }else{
35676 pGroup->nCurrentPage -=
35677 (pOtherCache->bPurgeable - pCache->bPurgeable);
35681 /* Step 5. If a usable page buffer has still not been found,
35682 ** attempt to allocate a new one.
35684 if( !pPage ){
35685 if( createFlag==1 ) sqlite3BeginBenignMalloc();
35686 pcache1LeaveMutex(pGroup);
35687 pPage = pcache1AllocPage(pCache);
35688 pcache1EnterMutex(pGroup);
35689 if( createFlag==1 ) sqlite3EndBenignMalloc();
35692 if( pPage ){
35693 unsigned int h = iKey % pCache->nHash;
35694 pCache->nPage++;
35695 pPage->iKey = iKey;
35696 pPage->pNext = pCache->apHash[h];
35697 pPage->pCache = pCache;
35698 pPage->pLruPrev = 0;
35699 pPage->pLruNext = 0;
35700 *(void **)(PGHDR1_TO_PAGE(pPage)) = 0;
35701 pCache->apHash[h] = pPage;
35704 fetch_out:
35705 if( pPage && iKey>pCache->iMaxKey ){
35706 pCache->iMaxKey = iKey;
35708 pcache1LeaveMutex(pGroup);
35709 return (pPage ? PGHDR1_TO_PAGE(pPage) : 0);
35714 ** Implementation of the sqlite3_pcache.xUnpin method.
35716 ** Mark a page as unpinned (eligible for asynchronous recycling).
35718 static void pcache1Unpin(sqlite3_pcache *p, void *pPg, int reuseUnlikely){
35719 PCache1 *pCache = (PCache1 *)p;
35720 PgHdr1 *pPage = PAGE_TO_PGHDR1(pCache, pPg);
35721 PGroup *pGroup = pCache->pGroup;
35723 assert( pPage->pCache==pCache );
35724 pcache1EnterMutex(pGroup);
35726 /* It is an error to call this function if the page is already
35727 ** part of the PGroup LRU list.
35729 assert( pPage->pLruPrev==0 && pPage->pLruNext==0 );
35730 assert( pGroup->pLruHead!=pPage && pGroup->pLruTail!=pPage );
35732 if( reuseUnlikely || pGroup->nCurrentPage>pGroup->nMaxPage ){
35733 pcache1RemoveFromHash(pPage);
35734 pcache1FreePage(pPage);
35735 }else{
35736 /* Add the page to the PGroup LRU list. */
35737 if( pGroup->pLruHead ){
35738 pGroup->pLruHead->pLruPrev = pPage;
35739 pPage->pLruNext = pGroup->pLruHead;
35740 pGroup->pLruHead = pPage;
35741 }else{
35742 pGroup->pLruTail = pPage;
35743 pGroup->pLruHead = pPage;
35745 pCache->nRecyclable++;
35748 pcache1LeaveMutex(pCache->pGroup);
35752 ** Implementation of the sqlite3_pcache.xRekey method.
35754 static void pcache1Rekey(
35755 sqlite3_pcache *p,
35756 void *pPg,
35757 unsigned int iOld,
35758 unsigned int iNew
35760 PCache1 *pCache = (PCache1 *)p;
35761 PgHdr1 *pPage = PAGE_TO_PGHDR1(pCache, pPg);
35762 PgHdr1 **pp;
35763 unsigned int h;
35764 assert( pPage->iKey==iOld );
35765 assert( pPage->pCache==pCache );
35767 pcache1EnterMutex(pCache->pGroup);
35769 h = iOld%pCache->nHash;
35770 pp = &pCache->apHash[h];
35771 while( (*pp)!=pPage ){
35772 pp = &(*pp)->pNext;
35774 *pp = pPage->pNext;
35776 h = iNew%pCache->nHash;
35777 pPage->iKey = iNew;
35778 pPage->pNext = pCache->apHash[h];
35779 pCache->apHash[h] = pPage;
35780 if( iNew>pCache->iMaxKey ){
35781 pCache->iMaxKey = iNew;
35784 pcache1LeaveMutex(pCache->pGroup);
35788 ** Implementation of the sqlite3_pcache.xTruncate method.
35790 ** Discard all unpinned pages in the cache with a page number equal to
35791 ** or greater than parameter iLimit. Any pinned pages with a page number
35792 ** equal to or greater than iLimit are implicitly unpinned.
35794 static void pcache1Truncate(sqlite3_pcache *p, unsigned int iLimit){
35795 PCache1 *pCache = (PCache1 *)p;
35796 pcache1EnterMutex(pCache->pGroup);
35797 if( iLimit<=pCache->iMaxKey ){
35798 pcache1TruncateUnsafe(pCache, iLimit);
35799 pCache->iMaxKey = iLimit-1;
35801 pcache1LeaveMutex(pCache->pGroup);
35805 ** Implementation of the sqlite3_pcache.xDestroy method.
35807 ** Destroy a cache allocated using pcache1Create().
35809 static void pcache1Destroy(sqlite3_pcache *p){
35810 PCache1 *pCache = (PCache1 *)p;
35811 PGroup *pGroup = pCache->pGroup;
35812 assert( pCache->bPurgeable || (pCache->nMax==0 && pCache->nMin==0) );
35813 pcache1EnterMutex(pGroup);
35814 pcache1TruncateUnsafe(pCache, 0);
35815 pGroup->nMaxPage -= pCache->nMax;
35816 pGroup->nMinPage -= pCache->nMin;
35817 pGroup->mxPinned = pGroup->nMaxPage + 10 - pGroup->nMinPage;
35818 pcache1EnforceMaxPage(pGroup);
35819 pcache1LeaveMutex(pGroup);
35820 sqlite3_free(pCache->apHash);
35821 sqlite3_free(pCache);
35825 ** This function is called during initialization (sqlite3_initialize()) to
35826 ** install the default pluggable cache module, assuming the user has not
35827 ** already provided an alternative.
35829 SQLITE_PRIVATE void sqlite3PCacheSetDefault(void){
35830 static const sqlite3_pcache_methods defaultMethods = {
35831 0, /* pArg */
35832 pcache1Init, /* xInit */
35833 pcache1Shutdown, /* xShutdown */
35834 pcache1Create, /* xCreate */
35835 pcache1Cachesize, /* xCachesize */
35836 pcache1Pagecount, /* xPagecount */
35837 pcache1Fetch, /* xFetch */
35838 pcache1Unpin, /* xUnpin */
35839 pcache1Rekey, /* xRekey */
35840 pcache1Truncate, /* xTruncate */
35841 pcache1Destroy /* xDestroy */
35843 sqlite3_config(SQLITE_CONFIG_PCACHE, &defaultMethods);
35846 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
35848 ** This function is called to free superfluous dynamically allocated memory
35849 ** held by the pager system. Memory in use by any SQLite pager allocated
35850 ** by the current thread may be sqlite3_free()ed.
35852 ** nReq is the number of bytes of memory required. Once this much has
35853 ** been released, the function returns. The return value is the total number
35854 ** of bytes of memory released.
35856 SQLITE_PRIVATE int sqlite3PcacheReleaseMemory(int nReq){
35857 int nFree = 0;
35858 assert( sqlite3_mutex_notheld(pcache1.grp.mutex) );
35859 assert( sqlite3_mutex_notheld(pcache1.mutex) );
35860 if( pcache1.pStart==0 ){
35861 PgHdr1 *p;
35862 pcache1EnterMutex(&pcache1.grp);
35863 while( (nReq<0 || nFree<nReq) && ((p=pcache1.grp.pLruTail)!=0) ){
35864 nFree += pcache1MemSize(PGHDR1_TO_PAGE(p));
35865 pcache1PinPage(p);
35866 pcache1RemoveFromHash(p);
35867 pcache1FreePage(p);
35869 pcache1LeaveMutex(&pcache1.grp);
35871 return nFree;
35873 #endif /* SQLITE_ENABLE_MEMORY_MANAGEMENT */
35875 #ifdef SQLITE_TEST
35877 ** This function is used by test procedures to inspect the internal state
35878 ** of the global cache.
35880 SQLITE_PRIVATE void sqlite3PcacheStats(
35881 int *pnCurrent, /* OUT: Total number of pages cached */
35882 int *pnMax, /* OUT: Global maximum cache size */
35883 int *pnMin, /* OUT: Sum of PCache1.nMin for purgeable caches */
35884 int *pnRecyclable /* OUT: Total number of pages available for recycling */
35886 PgHdr1 *p;
35887 int nRecyclable = 0;
35888 for(p=pcache1.grp.pLruHead; p; p=p->pLruNext){
35889 nRecyclable++;
35891 *pnCurrent = pcache1.grp.nCurrentPage;
35892 *pnMax = pcache1.grp.nMaxPage;
35893 *pnMin = pcache1.grp.nMinPage;
35894 *pnRecyclable = nRecyclable;
35896 #endif
35898 /************** End of pcache1.c *********************************************/
35899 /************** Begin file rowset.c ******************************************/
35901 ** 2008 December 3
35903 ** The author disclaims copyright to this source code. In place of
35904 ** a legal notice, here is a blessing:
35906 ** May you do good and not evil.
35907 ** May you find forgiveness for yourself and forgive others.
35908 ** May you share freely, never taking more than you give.
35910 *************************************************************************
35912 ** This module implements an object we call a "RowSet".
35914 ** The RowSet object is a collection of rowids. Rowids
35915 ** are inserted into the RowSet in an arbitrary order. Inserts
35916 ** can be intermixed with tests to see if a given rowid has been
35917 ** previously inserted into the RowSet.
35919 ** After all inserts are finished, it is possible to extract the
35920 ** elements of the RowSet in sorted order. Once this extraction
35921 ** process has started, no new elements may be inserted.
35923 ** Hence, the primitive operations for a RowSet are:
35925 ** CREATE
35926 ** INSERT
35927 ** TEST
35928 ** SMALLEST
35929 ** DESTROY
35931 ** The CREATE and DESTROY primitives are the constructor and destructor,
35932 ** obviously. The INSERT primitive adds a new element to the RowSet.
35933 ** TEST checks to see if an element is already in the RowSet. SMALLEST
35934 ** extracts the least value from the RowSet.
35936 ** The INSERT primitive might allocate additional memory. Memory is
35937 ** allocated in chunks so most INSERTs do no allocation. There is an
35938 ** upper bound on the size of allocated memory. No memory is freed
35939 ** until DESTROY.
35941 ** The TEST primitive includes a "batch" number. The TEST primitive
35942 ** will only see elements that were inserted before the last change
35943 ** in the batch number. In other words, if an INSERT occurs between
35944 ** two TESTs where the TESTs have the same batch nubmer, then the
35945 ** value added by the INSERT will not be visible to the second TEST.
35946 ** The initial batch number is zero, so if the very first TEST contains
35947 ** a non-zero batch number, it will see all prior INSERTs.
35949 ** No INSERTs may occurs after a SMALLEST. An assertion will fail if
35950 ** that is attempted.
35952 ** The cost of an INSERT is roughly constant. (Sometime new memory
35953 ** has to be allocated on an INSERT.) The cost of a TEST with a new
35954 ** batch number is O(NlogN) where N is the number of elements in the RowSet.
35955 ** The cost of a TEST using the same batch number is O(logN). The cost
35956 ** of the first SMALLEST is O(NlogN). Second and subsequent SMALLEST
35957 ** primitives are constant time. The cost of DESTROY is O(N).
35959 ** There is an added cost of O(N) when switching between TEST and
35960 ** SMALLEST primitives.
35965 ** Target size for allocation chunks.
35967 #define ROWSET_ALLOCATION_SIZE 1024
35970 ** The number of rowset entries per allocation chunk.
35972 #define ROWSET_ENTRY_PER_CHUNK \
35973 ((ROWSET_ALLOCATION_SIZE-8)/sizeof(struct RowSetEntry))
35976 ** Each entry in a RowSet is an instance of the following object.
35978 struct RowSetEntry {
35979 i64 v; /* ROWID value for this entry */
35980 struct RowSetEntry *pRight; /* Right subtree (larger entries) or list */
35981 struct RowSetEntry *pLeft; /* Left subtree (smaller entries) */
35985 ** RowSetEntry objects are allocated in large chunks (instances of the
35986 ** following structure) to reduce memory allocation overhead. The
35987 ** chunks are kept on a linked list so that they can be deallocated
35988 ** when the RowSet is destroyed.
35990 struct RowSetChunk {
35991 struct RowSetChunk *pNextChunk; /* Next chunk on list of them all */
35992 struct RowSetEntry aEntry[ROWSET_ENTRY_PER_CHUNK]; /* Allocated entries */
35996 ** A RowSet in an instance of the following structure.
35998 ** A typedef of this structure if found in sqliteInt.h.
36000 struct RowSet {
36001 struct RowSetChunk *pChunk; /* List of all chunk allocations */
36002 sqlite3 *db; /* The database connection */
36003 struct RowSetEntry *pEntry; /* List of entries using pRight */
36004 struct RowSetEntry *pLast; /* Last entry on the pEntry list */
36005 struct RowSetEntry *pFresh; /* Source of new entry objects */
36006 struct RowSetEntry *pTree; /* Binary tree of entries */
36007 u16 nFresh; /* Number of objects on pFresh */
36008 u8 isSorted; /* True if pEntry is sorted */
36009 u8 iBatch; /* Current insert batch */
36013 ** Turn bulk memory into a RowSet object. N bytes of memory
36014 ** are available at pSpace. The db pointer is used as a memory context
36015 ** for any subsequent allocations that need to occur.
36016 ** Return a pointer to the new RowSet object.
36018 ** It must be the case that N is sufficient to make a Rowset. If not
36019 ** an assertion fault occurs.
36021 ** If N is larger than the minimum, use the surplus as an initial
36022 ** allocation of entries available to be filled.
36024 SQLITE_PRIVATE RowSet *sqlite3RowSetInit(sqlite3 *db, void *pSpace, unsigned int N){
36025 RowSet *p;
36026 assert( N >= ROUND8(sizeof(*p)) );
36027 p = pSpace;
36028 p->pChunk = 0;
36029 p->db = db;
36030 p->pEntry = 0;
36031 p->pLast = 0;
36032 p->pTree = 0;
36033 p->pFresh = (struct RowSetEntry*)(ROUND8(sizeof(*p)) + (char*)p);
36034 p->nFresh = (u16)((N - ROUND8(sizeof(*p)))/sizeof(struct RowSetEntry));
36035 p->isSorted = 1;
36036 p->iBatch = 0;
36037 return p;
36041 ** Deallocate all chunks from a RowSet. This frees all memory that
36042 ** the RowSet has allocated over its lifetime. This routine is
36043 ** the destructor for the RowSet.
36045 SQLITE_PRIVATE void sqlite3RowSetClear(RowSet *p){
36046 struct RowSetChunk *pChunk, *pNextChunk;
36047 for(pChunk=p->pChunk; pChunk; pChunk = pNextChunk){
36048 pNextChunk = pChunk->pNextChunk;
36049 sqlite3DbFree(p->db, pChunk);
36051 p->pChunk = 0;
36052 p->nFresh = 0;
36053 p->pEntry = 0;
36054 p->pLast = 0;
36055 p->pTree = 0;
36056 p->isSorted = 1;
36060 ** Insert a new value into a RowSet.
36062 ** The mallocFailed flag of the database connection is set if a
36063 ** memory allocation fails.
36065 SQLITE_PRIVATE void sqlite3RowSetInsert(RowSet *p, i64 rowid){
36066 struct RowSetEntry *pEntry; /* The new entry */
36067 struct RowSetEntry *pLast; /* The last prior entry */
36068 assert( p!=0 );
36069 if( p->nFresh==0 ){
36070 struct RowSetChunk *pNew;
36071 pNew = sqlite3DbMallocRaw(p->db, sizeof(*pNew));
36072 if( pNew==0 ){
36073 return;
36075 pNew->pNextChunk = p->pChunk;
36076 p->pChunk = pNew;
36077 p->pFresh = pNew->aEntry;
36078 p->nFresh = ROWSET_ENTRY_PER_CHUNK;
36080 pEntry = p->pFresh++;
36081 p->nFresh--;
36082 pEntry->v = rowid;
36083 pEntry->pRight = 0;
36084 pLast = p->pLast;
36085 if( pLast ){
36086 if( p->isSorted && rowid<=pLast->v ){
36087 p->isSorted = 0;
36089 pLast->pRight = pEntry;
36090 }else{
36091 assert( p->pEntry==0 ); /* Fires if INSERT after SMALLEST */
36092 p->pEntry = pEntry;
36094 p->pLast = pEntry;
36098 ** Merge two lists of RowSetEntry objects. Remove duplicates.
36100 ** The input lists are connected via pRight pointers and are
36101 ** assumed to each already be in sorted order.
36103 static struct RowSetEntry *rowSetMerge(
36104 struct RowSetEntry *pA, /* First sorted list to be merged */
36105 struct RowSetEntry *pB /* Second sorted list to be merged */
36107 struct RowSetEntry head;
36108 struct RowSetEntry *pTail;
36110 pTail = &head;
36111 while( pA && pB ){
36112 assert( pA->pRight==0 || pA->v<=pA->pRight->v );
36113 assert( pB->pRight==0 || pB->v<=pB->pRight->v );
36114 if( pA->v<pB->v ){
36115 pTail->pRight = pA;
36116 pA = pA->pRight;
36117 pTail = pTail->pRight;
36118 }else if( pB->v<pA->v ){
36119 pTail->pRight = pB;
36120 pB = pB->pRight;
36121 pTail = pTail->pRight;
36122 }else{
36123 pA = pA->pRight;
36126 if( pA ){
36127 assert( pA->pRight==0 || pA->v<=pA->pRight->v );
36128 pTail->pRight = pA;
36129 }else{
36130 assert( pB==0 || pB->pRight==0 || pB->v<=pB->pRight->v );
36131 pTail->pRight = pB;
36133 return head.pRight;
36137 ** Sort all elements on the pEntry list of the RowSet into ascending order.
36139 static void rowSetSort(RowSet *p){
36140 unsigned int i;
36141 struct RowSetEntry *pEntry;
36142 struct RowSetEntry *aBucket[40];
36144 assert( p->isSorted==0 );
36145 memset(aBucket, 0, sizeof(aBucket));
36146 while( p->pEntry ){
36147 pEntry = p->pEntry;
36148 p->pEntry = pEntry->pRight;
36149 pEntry->pRight = 0;
36150 for(i=0; aBucket[i]; i++){
36151 pEntry = rowSetMerge(aBucket[i], pEntry);
36152 aBucket[i] = 0;
36154 aBucket[i] = pEntry;
36156 pEntry = 0;
36157 for(i=0; i<sizeof(aBucket)/sizeof(aBucket[0]); i++){
36158 pEntry = rowSetMerge(pEntry, aBucket[i]);
36160 p->pEntry = pEntry;
36161 p->pLast = 0;
36162 p->isSorted = 1;
36167 ** The input, pIn, is a binary tree (or subtree) of RowSetEntry objects.
36168 ** Convert this tree into a linked list connected by the pRight pointers
36169 ** and return pointers to the first and last elements of the new list.
36171 static void rowSetTreeToList(
36172 struct RowSetEntry *pIn, /* Root of the input tree */
36173 struct RowSetEntry **ppFirst, /* Write head of the output list here */
36174 struct RowSetEntry **ppLast /* Write tail of the output list here */
36176 assert( pIn!=0 );
36177 if( pIn->pLeft ){
36178 struct RowSetEntry *p;
36179 rowSetTreeToList(pIn->pLeft, ppFirst, &p);
36180 p->pRight = pIn;
36181 }else{
36182 *ppFirst = pIn;
36184 if( pIn->pRight ){
36185 rowSetTreeToList(pIn->pRight, &pIn->pRight, ppLast);
36186 }else{
36187 *ppLast = pIn;
36189 assert( (*ppLast)->pRight==0 );
36194 ** Convert a sorted list of elements (connected by pRight) into a binary
36195 ** tree with depth of iDepth. A depth of 1 means the tree contains a single
36196 ** node taken from the head of *ppList. A depth of 2 means a tree with
36197 ** three nodes. And so forth.
36199 ** Use as many entries from the input list as required and update the
36200 ** *ppList to point to the unused elements of the list. If the input
36201 ** list contains too few elements, then construct an incomplete tree
36202 ** and leave *ppList set to NULL.
36204 ** Return a pointer to the root of the constructed binary tree.
36206 static struct RowSetEntry *rowSetNDeepTree(
36207 struct RowSetEntry **ppList,
36208 int iDepth
36210 struct RowSetEntry *p; /* Root of the new tree */
36211 struct RowSetEntry *pLeft; /* Left subtree */
36212 if( *ppList==0 ){
36213 return 0;
36215 if( iDepth==1 ){
36216 p = *ppList;
36217 *ppList = p->pRight;
36218 p->pLeft = p->pRight = 0;
36219 return p;
36221 pLeft = rowSetNDeepTree(ppList, iDepth-1);
36222 p = *ppList;
36223 if( p==0 ){
36224 return pLeft;
36226 p->pLeft = pLeft;
36227 *ppList = p->pRight;
36228 p->pRight = rowSetNDeepTree(ppList, iDepth-1);
36229 return p;
36233 ** Convert a sorted list of elements into a binary tree. Make the tree
36234 ** as deep as it needs to be in order to contain the entire list.
36236 static struct RowSetEntry *rowSetListToTree(struct RowSetEntry *pList){
36237 int iDepth; /* Depth of the tree so far */
36238 struct RowSetEntry *p; /* Current tree root */
36239 struct RowSetEntry *pLeft; /* Left subtree */
36241 assert( pList!=0 );
36242 p = pList;
36243 pList = p->pRight;
36244 p->pLeft = p->pRight = 0;
36245 for(iDepth=1; pList; iDepth++){
36246 pLeft = p;
36247 p = pList;
36248 pList = p->pRight;
36249 p->pLeft = pLeft;
36250 p->pRight = rowSetNDeepTree(&pList, iDepth);
36252 return p;
36256 ** Convert the list in p->pEntry into a sorted list if it is not
36257 ** sorted already. If there is a binary tree on p->pTree, then
36258 ** convert it into a list too and merge it into the p->pEntry list.
36260 static void rowSetToList(RowSet *p){
36261 if( !p->isSorted ){
36262 rowSetSort(p);
36264 if( p->pTree ){
36265 struct RowSetEntry *pHead, *pTail;
36266 rowSetTreeToList(p->pTree, &pHead, &pTail);
36267 p->pTree = 0;
36268 p->pEntry = rowSetMerge(p->pEntry, pHead);
36273 ** Extract the smallest element from the RowSet.
36274 ** Write the element into *pRowid. Return 1 on success. Return
36275 ** 0 if the RowSet is already empty.
36277 ** After this routine has been called, the sqlite3RowSetInsert()
36278 ** routine may not be called again.
36280 SQLITE_PRIVATE int sqlite3RowSetNext(RowSet *p, i64 *pRowid){
36281 rowSetToList(p);
36282 if( p->pEntry ){
36283 *pRowid = p->pEntry->v;
36284 p->pEntry = p->pEntry->pRight;
36285 if( p->pEntry==0 ){
36286 sqlite3RowSetClear(p);
36288 return 1;
36289 }else{
36290 return 0;
36295 ** Check to see if element iRowid was inserted into the the rowset as
36296 ** part of any insert batch prior to iBatch. Return 1 or 0.
36298 SQLITE_PRIVATE int sqlite3RowSetTest(RowSet *pRowSet, u8 iBatch, sqlite3_int64 iRowid){
36299 struct RowSetEntry *p;
36300 if( iBatch!=pRowSet->iBatch ){
36301 if( pRowSet->pEntry ){
36302 rowSetToList(pRowSet);
36303 pRowSet->pTree = rowSetListToTree(pRowSet->pEntry);
36304 pRowSet->pEntry = 0;
36305 pRowSet->pLast = 0;
36307 pRowSet->iBatch = iBatch;
36309 p = pRowSet->pTree;
36310 while( p ){
36311 if( p->v<iRowid ){
36312 p = p->pRight;
36313 }else if( p->v>iRowid ){
36314 p = p->pLeft;
36315 }else{
36316 return 1;
36319 return 0;
36322 /************** End of rowset.c **********************************************/
36323 /************** Begin file pager.c *******************************************/
36325 ** 2001 September 15
36327 ** The author disclaims copyright to this source code. In place of
36328 ** a legal notice, here is a blessing:
36330 ** May you do good and not evil.
36331 ** May you find forgiveness for yourself and forgive others.
36332 ** May you share freely, never taking more than you give.
36334 *************************************************************************
36335 ** This is the implementation of the page cache subsystem or "pager".
36337 ** The pager is used to access a database disk file. It implements
36338 ** atomic commit and rollback through the use of a journal file that
36339 ** is separate from the database file. The pager also implements file
36340 ** locking to prevent two processes from writing the same database
36341 ** file simultaneously, or one process from reading the database while
36342 ** another is writing.
36344 #ifndef SQLITE_OMIT_DISKIO
36345 /************** Include wal.h in the middle of pager.c ***********************/
36346 /************** Begin file wal.h *********************************************/
36348 ** 2010 February 1
36350 ** The author disclaims copyright to this source code. In place of
36351 ** a legal notice, here is a blessing:
36353 ** May you do good and not evil.
36354 ** May you find forgiveness for yourself and forgive others.
36355 ** May you share freely, never taking more than you give.
36357 *************************************************************************
36358 ** This header file defines the interface to the write-ahead logging
36359 ** system. Refer to the comments below and the header comment attached to
36360 ** the implementation of each function in log.c for further details.
36363 #ifndef _WAL_H_
36364 #define _WAL_H_
36367 #ifdef SQLITE_OMIT_WAL
36368 # define sqlite3WalOpen(x,y,z) 0
36369 # define sqlite3WalClose(w,x,y,z) 0
36370 # define sqlite3WalBeginReadTransaction(y,z) 0
36371 # define sqlite3WalEndReadTransaction(z)
36372 # define sqlite3WalRead(v,w,x,y,z) 0
36373 # define sqlite3WalDbsize(y) 0
36374 # define sqlite3WalBeginWriteTransaction(y) 0
36375 # define sqlite3WalEndWriteTransaction(x) 0
36376 # define sqlite3WalUndo(x,y,z) 0
36377 # define sqlite3WalSavepoint(y,z)
36378 # define sqlite3WalSavepointUndo(y,z) 0
36379 # define sqlite3WalFrames(u,v,w,x,y,z) 0
36380 # define sqlite3WalCheckpoint(r,s,t,u,v,w,x,y,z) 0
36381 # define sqlite3WalCallback(z) 0
36382 # define sqlite3WalExclusiveMode(y,z) 0
36383 # define sqlite3WalHeapMemory(z) 0
36384 #else
36386 #define WAL_SAVEPOINT_NDATA 4
36388 /* Connection to a write-ahead log (WAL) file.
36389 ** There is one object of this type for each pager.
36391 typedef struct Wal Wal;
36393 /* Open and close a connection to a write-ahead log. */
36394 SQLITE_PRIVATE int sqlite3WalOpen(sqlite3_vfs*, sqlite3_file*, const char *zName, int, Wal**);
36395 SQLITE_PRIVATE int sqlite3WalClose(Wal *pWal, int sync_flags, int, u8 *);
36397 /* Used by readers to open (lock) and close (unlock) a snapshot. A
36398 ** snapshot is like a read-transaction. It is the state of the database
36399 ** at an instant in time. sqlite3WalOpenSnapshot gets a read lock and
36400 ** preserves the current state even if the other threads or processes
36401 ** write to or checkpoint the WAL. sqlite3WalCloseSnapshot() closes the
36402 ** transaction and releases the lock.
36404 SQLITE_PRIVATE int sqlite3WalBeginReadTransaction(Wal *pWal, int *);
36405 SQLITE_PRIVATE void sqlite3WalEndReadTransaction(Wal *pWal);
36407 /* Read a page from the write-ahead log, if it is present. */
36408 SQLITE_PRIVATE int sqlite3WalRead(Wal *pWal, Pgno pgno, int *pInWal, int nOut, u8 *pOut);
36410 /* If the WAL is not empty, return the size of the database. */
36411 SQLITE_PRIVATE Pgno sqlite3WalDbsize(Wal *pWal);
36413 /* Obtain or release the WRITER lock. */
36414 SQLITE_PRIVATE int sqlite3WalBeginWriteTransaction(Wal *pWal);
36415 SQLITE_PRIVATE int sqlite3WalEndWriteTransaction(Wal *pWal);
36417 /* Undo any frames written (but not committed) to the log */
36418 SQLITE_PRIVATE int sqlite3WalUndo(Wal *pWal, int (*xUndo)(void *, Pgno), void *pUndoCtx);
36420 /* Return an integer that records the current (uncommitted) write
36421 ** position in the WAL */
36422 SQLITE_PRIVATE void sqlite3WalSavepoint(Wal *pWal, u32 *aWalData);
36424 /* Move the write position of the WAL back to iFrame. Called in
36425 ** response to a ROLLBACK TO command. */
36426 SQLITE_PRIVATE int sqlite3WalSavepointUndo(Wal *pWal, u32 *aWalData);
36428 /* Write a frame or frames to the log. */
36429 SQLITE_PRIVATE int sqlite3WalFrames(Wal *pWal, int, PgHdr *, Pgno, int, int);
36431 /* Copy pages from the log to the database file */
36432 SQLITE_PRIVATE int sqlite3WalCheckpoint(
36433 Wal *pWal, /* Write-ahead log connection */
36434 int eMode, /* One of PASSIVE, FULL and RESTART */
36435 int (*xBusy)(void*), /* Function to call when busy */
36436 void *pBusyArg, /* Context argument for xBusyHandler */
36437 int sync_flags, /* Flags to sync db file with (or 0) */
36438 int nBuf, /* Size of buffer nBuf */
36439 u8 *zBuf, /* Temporary buffer to use */
36440 int *pnLog, /* OUT: Number of frames in WAL */
36441 int *pnCkpt /* OUT: Number of backfilled frames in WAL */
36444 /* Return the value to pass to a sqlite3_wal_hook callback, the
36445 ** number of frames in the WAL at the point of the last commit since
36446 ** sqlite3WalCallback() was called. If no commits have occurred since
36447 ** the last call, then return 0.
36449 SQLITE_PRIVATE int sqlite3WalCallback(Wal *pWal);
36451 /* Tell the wal layer that an EXCLUSIVE lock has been obtained (or released)
36452 ** by the pager layer on the database file.
36454 SQLITE_PRIVATE int sqlite3WalExclusiveMode(Wal *pWal, int op);
36456 /* Return true if the argument is non-NULL and the WAL module is using
36457 ** heap-memory for the wal-index. Otherwise, if the argument is NULL or the
36458 ** WAL module is using shared-memory, return false.
36460 SQLITE_PRIVATE int sqlite3WalHeapMemory(Wal *pWal);
36462 #endif /* ifndef SQLITE_OMIT_WAL */
36463 #endif /* _WAL_H_ */
36465 /************** End of wal.h *************************************************/
36466 /************** Continuing where we left off in pager.c **********************/
36469 /******************* NOTES ON THE DESIGN OF THE PAGER ************************
36471 ** This comment block describes invariants that hold when using a rollback
36472 ** journal. These invariants do not apply for journal_mode=WAL,
36473 ** journal_mode=MEMORY, or journal_mode=OFF.
36475 ** Within this comment block, a page is deemed to have been synced
36476 ** automatically as soon as it is written when PRAGMA synchronous=OFF.
36477 ** Otherwise, the page is not synced until the xSync method of the VFS
36478 ** is called successfully on the file containing the page.
36480 ** Definition: A page of the database file is said to be "overwriteable" if
36481 ** one or more of the following are true about the page:
36483 ** (a) The original content of the page as it was at the beginning of
36484 ** the transaction has been written into the rollback journal and
36485 ** synced.
36487 ** (b) The page was a freelist leaf page at the start of the transaction.
36489 ** (c) The page number is greater than the largest page that existed in
36490 ** the database file at the start of the transaction.
36492 ** (1) A page of the database file is never overwritten unless one of the
36493 ** following are true:
36495 ** (a) The page and all other pages on the same sector are overwriteable.
36497 ** (b) The atomic page write optimization is enabled, and the entire
36498 ** transaction other than the update of the transaction sequence
36499 ** number consists of a single page change.
36501 ** (2) The content of a page written into the rollback journal exactly matches
36502 ** both the content in the database when the rollback journal was written
36503 ** and the content in the database at the beginning of the current
36504 ** transaction.
36506 ** (3) Writes to the database file are an integer multiple of the page size
36507 ** in length and are aligned on a page boundary.
36509 ** (4) Reads from the database file are either aligned on a page boundary and
36510 ** an integer multiple of the page size in length or are taken from the
36511 ** first 100 bytes of the database file.
36513 ** (5) All writes to the database file are synced prior to the rollback journal
36514 ** being deleted, truncated, or zeroed.
36516 ** (6) If a master journal file is used, then all writes to the database file
36517 ** are synced prior to the master journal being deleted.
36519 ** Definition: Two databases (or the same database at two points it time)
36520 ** are said to be "logically equivalent" if they give the same answer to
36521 ** all queries. Note in particular the the content of freelist leaf
36522 ** pages can be changed arbitarily without effecting the logical equivalence
36523 ** of the database.
36525 ** (7) At any time, if any subset, including the empty set and the total set,
36526 ** of the unsynced changes to a rollback journal are removed and the
36527 ** journal is rolled back, the resulting database file will be logical
36528 ** equivalent to the database file at the beginning of the transaction.
36530 ** (8) When a transaction is rolled back, the xTruncate method of the VFS
36531 ** is called to restore the database file to the same size it was at
36532 ** the beginning of the transaction. (In some VFSes, the xTruncate
36533 ** method is a no-op, but that does not change the fact the SQLite will
36534 ** invoke it.)
36536 ** (9) Whenever the database file is modified, at least one bit in the range
36537 ** of bytes from 24 through 39 inclusive will be changed prior to releasing
36538 ** the EXCLUSIVE lock, thus signaling other connections on the same
36539 ** database to flush their caches.
36541 ** (10) The pattern of bits in bytes 24 through 39 shall not repeat in less
36542 ** than one billion transactions.
36544 ** (11) A database file is well-formed at the beginning and at the conclusion
36545 ** of every transaction.
36547 ** (12) An EXCLUSIVE lock is held on the database file when writing to
36548 ** the database file.
36550 ** (13) A SHARED lock is held on the database file while reading any
36551 ** content out of the database file.
36553 ******************************************************************************/
36556 ** Macros for troubleshooting. Normally turned off
36558 #if 0
36559 int sqlite3PagerTrace=1; /* True to enable tracing */
36560 #define sqlite3DebugPrintf printf
36561 #define PAGERTRACE(X) if( sqlite3PagerTrace ){ sqlite3DebugPrintf X; }
36562 #else
36563 #define PAGERTRACE(X)
36564 #endif
36567 ** The following two macros are used within the PAGERTRACE() macros above
36568 ** to print out file-descriptors.
36570 ** PAGERID() takes a pointer to a Pager struct as its argument. The
36571 ** associated file-descriptor is returned. FILEHANDLEID() takes an sqlite3_file
36572 ** struct as its argument.
36574 #define PAGERID(p) ((int)(p->fd))
36575 #define FILEHANDLEID(fd) ((int)fd)
36578 ** The Pager.eState variable stores the current 'state' of a pager. A
36579 ** pager may be in any one of the seven states shown in the following
36580 ** state diagram.
36582 ** OPEN <------+------+
36583 ** | | |
36584 ** V | |
36585 ** +---------> READER-------+ |
36586 ** | | |
36587 ** | V |
36588 ** |<-------WRITER_LOCKED------> ERROR
36589 ** | | ^
36590 ** | V |
36591 ** |<------WRITER_CACHEMOD-------->|
36592 ** | | |
36593 ** | V |
36594 ** |<-------WRITER_DBMOD---------->|
36595 ** | | |
36596 ** | V |
36597 ** +<------WRITER_FINISHED-------->+
36600 ** List of state transitions and the C [function] that performs each:
36602 ** OPEN -> READER [sqlite3PagerSharedLock]
36603 ** READER -> OPEN [pager_unlock]
36605 ** READER -> WRITER_LOCKED [sqlite3PagerBegin]
36606 ** WRITER_LOCKED -> WRITER_CACHEMOD [pager_open_journal]
36607 ** WRITER_CACHEMOD -> WRITER_DBMOD [syncJournal]
36608 ** WRITER_DBMOD -> WRITER_FINISHED [sqlite3PagerCommitPhaseOne]
36609 ** WRITER_*** -> READER [pager_end_transaction]
36611 ** WRITER_*** -> ERROR [pager_error]
36612 ** ERROR -> OPEN [pager_unlock]
36615 ** OPEN:
36617 ** The pager starts up in this state. Nothing is guaranteed in this
36618 ** state - the file may or may not be locked and the database size is
36619 ** unknown. The database may not be read or written.
36621 ** * No read or write transaction is active.
36622 ** * Any lock, or no lock at all, may be held on the database file.
36623 ** * The dbSize, dbOrigSize and dbFileSize variables may not be trusted.
36625 ** READER:
36627 ** In this state all the requirements for reading the database in
36628 ** rollback (non-WAL) mode are met. Unless the pager is (or recently
36629 ** was) in exclusive-locking mode, a user-level read transaction is
36630 ** open. The database size is known in this state.
36632 ** A connection running with locking_mode=normal enters this state when
36633 ** it opens a read-transaction on the database and returns to state
36634 ** OPEN after the read-transaction is completed. However a connection
36635 ** running in locking_mode=exclusive (including temp databases) remains in
36636 ** this state even after the read-transaction is closed. The only way
36637 ** a locking_mode=exclusive connection can transition from READER to OPEN
36638 ** is via the ERROR state (see below).
36640 ** * A read transaction may be active (but a write-transaction cannot).
36641 ** * A SHARED or greater lock is held on the database file.
36642 ** * The dbSize variable may be trusted (even if a user-level read
36643 ** transaction is not active). The dbOrigSize and dbFileSize variables
36644 ** may not be trusted at this point.
36645 ** * If the database is a WAL database, then the WAL connection is open.
36646 ** * Even if a read-transaction is not open, it is guaranteed that
36647 ** there is no hot-journal in the file-system.
36649 ** WRITER_LOCKED:
36651 ** The pager moves to this state from READER when a write-transaction
36652 ** is first opened on the database. In WRITER_LOCKED state, all locks
36653 ** required to start a write-transaction are held, but no actual
36654 ** modifications to the cache or database have taken place.
36656 ** In rollback mode, a RESERVED or (if the transaction was opened with
36657 ** BEGIN EXCLUSIVE) EXCLUSIVE lock is obtained on the database file when
36658 ** moving to this state, but the journal file is not written to or opened
36659 ** to in this state. If the transaction is committed or rolled back while
36660 ** in WRITER_LOCKED state, all that is required is to unlock the database
36661 ** file.
36663 ** IN WAL mode, WalBeginWriteTransaction() is called to lock the log file.
36664 ** If the connection is running with locking_mode=exclusive, an attempt
36665 ** is made to obtain an EXCLUSIVE lock on the database file.
36667 ** * A write transaction is active.
36668 ** * If the connection is open in rollback-mode, a RESERVED or greater
36669 ** lock is held on the database file.
36670 ** * If the connection is open in WAL-mode, a WAL write transaction
36671 ** is open (i.e. sqlite3WalBeginWriteTransaction() has been successfully
36672 ** called).
36673 ** * The dbSize, dbOrigSize and dbFileSize variables are all valid.
36674 ** * The contents of the pager cache have not been modified.
36675 ** * The journal file may or may not be open.
36676 ** * Nothing (not even the first header) has been written to the journal.
36678 ** WRITER_CACHEMOD:
36680 ** A pager moves from WRITER_LOCKED state to this state when a page is
36681 ** first modified by the upper layer. In rollback mode the journal file
36682 ** is opened (if it is not already open) and a header written to the
36683 ** start of it. The database file on disk has not been modified.
36685 ** * A write transaction is active.
36686 ** * A RESERVED or greater lock is held on the database file.
36687 ** * The journal file is open and the first header has been written
36688 ** to it, but the header has not been synced to disk.
36689 ** * The contents of the page cache have been modified.
36691 ** WRITER_DBMOD:
36693 ** The pager transitions from WRITER_CACHEMOD into WRITER_DBMOD state
36694 ** when it modifies the contents of the database file. WAL connections
36695 ** never enter this state (since they do not modify the database file,
36696 ** just the log file).
36698 ** * A write transaction is active.
36699 ** * An EXCLUSIVE or greater lock is held on the database file.
36700 ** * The journal file is open and the first header has been written
36701 ** and synced to disk.
36702 ** * The contents of the page cache have been modified (and possibly
36703 ** written to disk).
36705 ** WRITER_FINISHED:
36707 ** It is not possible for a WAL connection to enter this state.
36709 ** A rollback-mode pager changes to WRITER_FINISHED state from WRITER_DBMOD
36710 ** state after the entire transaction has been successfully written into the
36711 ** database file. In this state the transaction may be committed simply
36712 ** by finalizing the journal file. Once in WRITER_FINISHED state, it is
36713 ** not possible to modify the database further. At this point, the upper
36714 ** layer must either commit or rollback the transaction.
36716 ** * A write transaction is active.
36717 ** * An EXCLUSIVE or greater lock is held on the database file.
36718 ** * All writing and syncing of journal and database data has finished.
36719 ** If no error occured, all that remains is to finalize the journal to
36720 ** commit the transaction. If an error did occur, the caller will need
36721 ** to rollback the transaction.
36723 ** ERROR:
36725 ** The ERROR state is entered when an IO or disk-full error (including
36726 ** SQLITE_IOERR_NOMEM) occurs at a point in the code that makes it
36727 ** difficult to be sure that the in-memory pager state (cache contents,
36728 ** db size etc.) are consistent with the contents of the file-system.
36730 ** Temporary pager files may enter the ERROR state, but in-memory pagers
36731 ** cannot.
36733 ** For example, if an IO error occurs while performing a rollback,
36734 ** the contents of the page-cache may be left in an inconsistent state.
36735 ** At this point it would be dangerous to change back to READER state
36736 ** (as usually happens after a rollback). Any subsequent readers might
36737 ** report database corruption (due to the inconsistent cache), and if
36738 ** they upgrade to writers, they may inadvertently corrupt the database
36739 ** file. To avoid this hazard, the pager switches into the ERROR state
36740 ** instead of READER following such an error.
36742 ** Once it has entered the ERROR state, any attempt to use the pager
36743 ** to read or write data returns an error. Eventually, once all
36744 ** outstanding transactions have been abandoned, the pager is able to
36745 ** transition back to OPEN state, discarding the contents of the
36746 ** page-cache and any other in-memory state at the same time. Everything
36747 ** is reloaded from disk (and, if necessary, hot-journal rollback peformed)
36748 ** when a read-transaction is next opened on the pager (transitioning
36749 ** the pager into READER state). At that point the system has recovered
36750 ** from the error.
36752 ** Specifically, the pager jumps into the ERROR state if:
36754 ** 1. An error occurs while attempting a rollback. This happens in
36755 ** function sqlite3PagerRollback().
36757 ** 2. An error occurs while attempting to finalize a journal file
36758 ** following a commit in function sqlite3PagerCommitPhaseTwo().
36760 ** 3. An error occurs while attempting to write to the journal or
36761 ** database file in function pagerStress() in order to free up
36762 ** memory.
36764 ** In other cases, the error is returned to the b-tree layer. The b-tree
36765 ** layer then attempts a rollback operation. If the error condition
36766 ** persists, the pager enters the ERROR state via condition (1) above.
36768 ** Condition (3) is necessary because it can be triggered by a read-only
36769 ** statement executed within a transaction. In this case, if the error
36770 ** code were simply returned to the user, the b-tree layer would not
36771 ** automatically attempt a rollback, as it assumes that an error in a
36772 ** read-only statement cannot leave the pager in an internally inconsistent
36773 ** state.
36775 ** * The Pager.errCode variable is set to something other than SQLITE_OK.
36776 ** * There are one or more outstanding references to pages (after the
36777 ** last reference is dropped the pager should move back to OPEN state).
36778 ** * The pager is not an in-memory pager.
36781 ** Notes:
36783 ** * A pager is never in WRITER_DBMOD or WRITER_FINISHED state if the
36784 ** connection is open in WAL mode. A WAL connection is always in one
36785 ** of the first four states.
36787 ** * Normally, a connection open in exclusive mode is never in PAGER_OPEN
36788 ** state. There are two exceptions: immediately after exclusive-mode has
36789 ** been turned on (and before any read or write transactions are
36790 ** executed), and when the pager is leaving the "error state".
36792 ** * See also: assert_pager_state().
36794 #define PAGER_OPEN 0
36795 #define PAGER_READER 1
36796 #define PAGER_WRITER_LOCKED 2
36797 #define PAGER_WRITER_CACHEMOD 3
36798 #define PAGER_WRITER_DBMOD 4
36799 #define PAGER_WRITER_FINISHED 5
36800 #define PAGER_ERROR 6
36803 ** The Pager.eLock variable is almost always set to one of the
36804 ** following locking-states, according to the lock currently held on
36805 ** the database file: NO_LOCK, SHARED_LOCK, RESERVED_LOCK or EXCLUSIVE_LOCK.
36806 ** This variable is kept up to date as locks are taken and released by
36807 ** the pagerLockDb() and pagerUnlockDb() wrappers.
36809 ** If the VFS xLock() or xUnlock() returns an error other than SQLITE_BUSY
36810 ** (i.e. one of the SQLITE_IOERR subtypes), it is not clear whether or not
36811 ** the operation was successful. In these circumstances pagerLockDb() and
36812 ** pagerUnlockDb() take a conservative approach - eLock is always updated
36813 ** when unlocking the file, and only updated when locking the file if the
36814 ** VFS call is successful. This way, the Pager.eLock variable may be set
36815 ** to a less exclusive (lower) value than the lock that is actually held
36816 ** at the system level, but it is never set to a more exclusive value.
36818 ** This is usually safe. If an xUnlock fails or appears to fail, there may
36819 ** be a few redundant xLock() calls or a lock may be held for longer than
36820 ** required, but nothing really goes wrong.
36822 ** The exception is when the database file is unlocked as the pager moves
36823 ** from ERROR to OPEN state. At this point there may be a hot-journal file
36824 ** in the file-system that needs to be rolled back (as part of a OPEN->SHARED
36825 ** transition, by the same pager or any other). If the call to xUnlock()
36826 ** fails at this point and the pager is left holding an EXCLUSIVE lock, this
36827 ** can confuse the call to xCheckReservedLock() call made later as part
36828 ** of hot-journal detection.
36830 ** xCheckReservedLock() is defined as returning true "if there is a RESERVED
36831 ** lock held by this process or any others". So xCheckReservedLock may
36832 ** return true because the caller itself is holding an EXCLUSIVE lock (but
36833 ** doesn't know it because of a previous error in xUnlock). If this happens
36834 ** a hot-journal may be mistaken for a journal being created by an active
36835 ** transaction in another process, causing SQLite to read from the database
36836 ** without rolling it back.
36838 ** To work around this, if a call to xUnlock() fails when unlocking the
36839 ** database in the ERROR state, Pager.eLock is set to UNKNOWN_LOCK. It
36840 ** is only changed back to a real locking state after a successful call
36841 ** to xLock(EXCLUSIVE). Also, the code to do the OPEN->SHARED state transition
36842 ** omits the check for a hot-journal if Pager.eLock is set to UNKNOWN_LOCK
36843 ** lock. Instead, it assumes a hot-journal exists and obtains an EXCLUSIVE
36844 ** lock on the database file before attempting to roll it back. See function
36845 ** PagerSharedLock() for more detail.
36847 ** Pager.eLock may only be set to UNKNOWN_LOCK when the pager is in
36848 ** PAGER_OPEN state.
36850 #define UNKNOWN_LOCK (EXCLUSIVE_LOCK+1)
36853 ** A macro used for invoking the codec if there is one
36855 #ifdef SQLITE_HAS_CODEC
36856 # define CODEC1(P,D,N,X,E) \
36857 if( P->xCodec && P->xCodec(P->pCodec,D,N,X)==0 ){ E; }
36858 # define CODEC2(P,D,N,X,E,O) \
36859 if( P->xCodec==0 ){ O=(char*)D; }else \
36860 if( (O=(char*)(P->xCodec(P->pCodec,D,N,X)))==0 ){ E; }
36861 #else
36862 # define CODEC1(P,D,N,X,E) /* NO-OP */
36863 # define CODEC2(P,D,N,X,E,O) O=(char*)D
36864 #endif
36867 ** The maximum allowed sector size. 64KiB. If the xSectorsize() method
36868 ** returns a value larger than this, then MAX_SECTOR_SIZE is used instead.
36869 ** This could conceivably cause corruption following a power failure on
36870 ** such a system. This is currently an undocumented limit.
36872 #define MAX_SECTOR_SIZE 0x10000
36875 ** An instance of the following structure is allocated for each active
36876 ** savepoint and statement transaction in the system. All such structures
36877 ** are stored in the Pager.aSavepoint[] array, which is allocated and
36878 ** resized using sqlite3Realloc().
36880 ** When a savepoint is created, the PagerSavepoint.iHdrOffset field is
36881 ** set to 0. If a journal-header is written into the main journal while
36882 ** the savepoint is active, then iHdrOffset is set to the byte offset
36883 ** immediately following the last journal record written into the main
36884 ** journal before the journal-header. This is required during savepoint
36885 ** rollback (see pagerPlaybackSavepoint()).
36887 typedef struct PagerSavepoint PagerSavepoint;
36888 struct PagerSavepoint {
36889 i64 iOffset; /* Starting offset in main journal */
36890 i64 iHdrOffset; /* See above */
36891 Bitvec *pInSavepoint; /* Set of pages in this savepoint */
36892 Pgno nOrig; /* Original number of pages in file */
36893 Pgno iSubRec; /* Index of first record in sub-journal */
36894 #ifndef SQLITE_OMIT_WAL
36895 u32 aWalData[WAL_SAVEPOINT_NDATA]; /* WAL savepoint context */
36896 #endif
36900 ** A open page cache is an instance of struct Pager. A description of
36901 ** some of the more important member variables follows:
36903 ** eState
36905 ** The current 'state' of the pager object. See the comment and state
36906 ** diagram above for a description of the pager state.
36908 ** eLock
36910 ** For a real on-disk database, the current lock held on the database file -
36911 ** NO_LOCK, SHARED_LOCK, RESERVED_LOCK or EXCLUSIVE_LOCK.
36913 ** For a temporary or in-memory database (neither of which require any
36914 ** locks), this variable is always set to EXCLUSIVE_LOCK. Since such
36915 ** databases always have Pager.exclusiveMode==1, this tricks the pager
36916 ** logic into thinking that it already has all the locks it will ever
36917 ** need (and no reason to release them).
36919 ** In some (obscure) circumstances, this variable may also be set to
36920 ** UNKNOWN_LOCK. See the comment above the #define of UNKNOWN_LOCK for
36921 ** details.
36923 ** changeCountDone
36925 ** This boolean variable is used to make sure that the change-counter
36926 ** (the 4-byte header field at byte offset 24 of the database file) is
36927 ** not updated more often than necessary.
36929 ** It is set to true when the change-counter field is updated, which
36930 ** can only happen if an exclusive lock is held on the database file.
36931 ** It is cleared (set to false) whenever an exclusive lock is
36932 ** relinquished on the database file. Each time a transaction is committed,
36933 ** The changeCountDone flag is inspected. If it is true, the work of
36934 ** updating the change-counter is omitted for the current transaction.
36936 ** This mechanism means that when running in exclusive mode, a connection
36937 ** need only update the change-counter once, for the first transaction
36938 ** committed.
36940 ** setMaster
36942 ** When PagerCommitPhaseOne() is called to commit a transaction, it may
36943 ** (or may not) specify a master-journal name to be written into the
36944 ** journal file before it is synced to disk.
36946 ** Whether or not a journal file contains a master-journal pointer affects
36947 ** the way in which the journal file is finalized after the transaction is
36948 ** committed or rolled back when running in "journal_mode=PERSIST" mode.
36949 ** If a journal file does not contain a master-journal pointer, it is
36950 ** finalized by overwriting the first journal header with zeroes. If
36951 ** it does contain a master-journal pointer the journal file is finalized
36952 ** by truncating it to zero bytes, just as if the connection were
36953 ** running in "journal_mode=truncate" mode.
36955 ** Journal files that contain master journal pointers cannot be finalized
36956 ** simply by overwriting the first journal-header with zeroes, as the
36957 ** master journal pointer could interfere with hot-journal rollback of any
36958 ** subsequently interrupted transaction that reuses the journal file.
36960 ** The flag is cleared as soon as the journal file is finalized (either
36961 ** by PagerCommitPhaseTwo or PagerRollback). If an IO error prevents the
36962 ** journal file from being successfully finalized, the setMaster flag
36963 ** is cleared anyway (and the pager will move to ERROR state).
36965 ** doNotSpill, doNotSyncSpill
36967 ** These two boolean variables control the behaviour of cache-spills
36968 ** (calls made by the pcache module to the pagerStress() routine to
36969 ** write cached data to the file-system in order to free up memory).
36971 ** When doNotSpill is non-zero, writing to the database from pagerStress()
36972 ** is disabled altogether. This is done in a very obscure case that
36973 ** comes up during savepoint rollback that requires the pcache module
36974 ** to allocate a new page to prevent the journal file from being written
36975 ** while it is being traversed by code in pager_playback().
36977 ** If doNotSyncSpill is non-zero, writing to the database from pagerStress()
36978 ** is permitted, but syncing the journal file is not. This flag is set
36979 ** by sqlite3PagerWrite() when the file-system sector-size is larger than
36980 ** the database page-size in order to prevent a journal sync from happening
36981 ** in between the journalling of two pages on the same sector.
36983 ** subjInMemory
36985 ** This is a boolean variable. If true, then any required sub-journal
36986 ** is opened as an in-memory journal file. If false, then in-memory
36987 ** sub-journals are only used for in-memory pager files.
36989 ** This variable is updated by the upper layer each time a new
36990 ** write-transaction is opened.
36992 ** dbSize, dbOrigSize, dbFileSize
36994 ** Variable dbSize is set to the number of pages in the database file.
36995 ** It is valid in PAGER_READER and higher states (all states except for
36996 ** OPEN and ERROR).
36998 ** dbSize is set based on the size of the database file, which may be
36999 ** larger than the size of the database (the value stored at offset
37000 ** 28 of the database header by the btree). If the size of the file
37001 ** is not an integer multiple of the page-size, the value stored in
37002 ** dbSize is rounded down (i.e. a 5KB file with 2K page-size has dbSize==2).
37003 ** Except, any file that is greater than 0 bytes in size is considered
37004 ** to have at least one page. (i.e. a 1KB file with 2K page-size leads
37005 ** to dbSize==1).
37007 ** During a write-transaction, if pages with page-numbers greater than
37008 ** dbSize are modified in the cache, dbSize is updated accordingly.
37009 ** Similarly, if the database is truncated using PagerTruncateImage(),
37010 ** dbSize is updated.
37012 ** Variables dbOrigSize and dbFileSize are valid in states
37013 ** PAGER_WRITER_LOCKED and higher. dbOrigSize is a copy of the dbSize
37014 ** variable at the start of the transaction. It is used during rollback,
37015 ** and to determine whether or not pages need to be journalled before
37016 ** being modified.
37018 ** Throughout a write-transaction, dbFileSize contains the size of
37019 ** the file on disk in pages. It is set to a copy of dbSize when the
37020 ** write-transaction is first opened, and updated when VFS calls are made
37021 ** to write or truncate the database file on disk.
37023 ** The only reason the dbFileSize variable is required is to suppress
37024 ** unnecessary calls to xTruncate() after committing a transaction. If,
37025 ** when a transaction is committed, the dbFileSize variable indicates
37026 ** that the database file is larger than the database image (Pager.dbSize),
37027 ** pager_truncate() is called. The pager_truncate() call uses xFilesize()
37028 ** to measure the database file on disk, and then truncates it if required.
37029 ** dbFileSize is not used when rolling back a transaction. In this case
37030 ** pager_truncate() is called unconditionally (which means there may be
37031 ** a call to xFilesize() that is not strictly required). In either case,
37032 ** pager_truncate() may cause the file to become smaller or larger.
37034 ** dbHintSize
37036 ** The dbHintSize variable is used to limit the number of calls made to
37037 ** the VFS xFileControl(FCNTL_SIZE_HINT) method.
37039 ** dbHintSize is set to a copy of the dbSize variable when a
37040 ** write-transaction is opened (at the same time as dbFileSize and
37041 ** dbOrigSize). If the xFileControl(FCNTL_SIZE_HINT) method is called,
37042 ** dbHintSize is increased to the number of pages that correspond to the
37043 ** size-hint passed to the method call. See pager_write_pagelist() for
37044 ** details.
37046 ** errCode
37048 ** The Pager.errCode variable is only ever used in PAGER_ERROR state. It
37049 ** is set to zero in all other states. In PAGER_ERROR state, Pager.errCode
37050 ** is always set to SQLITE_FULL, SQLITE_IOERR or one of the SQLITE_IOERR_XXX
37051 ** sub-codes.
37053 struct Pager {
37054 sqlite3_vfs *pVfs; /* OS functions to use for IO */
37055 u8 exclusiveMode; /* Boolean. True if locking_mode==EXCLUSIVE */
37056 u8 journalMode; /* One of the PAGER_JOURNALMODE_* values */
37057 u8 useJournal; /* Use a rollback journal on this file */
37058 u8 noReadlock; /* Do not bother to obtain readlocks */
37059 u8 noSync; /* Do not sync the journal if true */
37060 u8 fullSync; /* Do extra syncs of the journal for robustness */
37061 u8 ckptSyncFlags; /* SYNC_NORMAL or SYNC_FULL for checkpoint */
37062 u8 syncFlags; /* SYNC_NORMAL or SYNC_FULL otherwise */
37063 u8 tempFile; /* zFilename is a temporary file */
37064 u8 readOnly; /* True for a read-only database */
37065 u8 memDb; /* True to inhibit all file I/O */
37067 /**************************************************************************
37068 ** The following block contains those class members that change during
37069 ** routine opertion. Class members not in this block are either fixed
37070 ** when the pager is first created or else only change when there is a
37071 ** significant mode change (such as changing the page_size, locking_mode,
37072 ** or the journal_mode). From another view, these class members describe
37073 ** the "state" of the pager, while other class members describe the
37074 ** "configuration" of the pager.
37076 u8 eState; /* Pager state (OPEN, READER, WRITER_LOCKED..) */
37077 u8 eLock; /* Current lock held on database file */
37078 u8 changeCountDone; /* Set after incrementing the change-counter */
37079 u8 setMaster; /* True if a m-j name has been written to jrnl */
37080 u8 doNotSpill; /* Do not spill the cache when non-zero */
37081 u8 doNotSyncSpill; /* Do not do a spill that requires jrnl sync */
37082 u8 subjInMemory; /* True to use in-memory sub-journals */
37083 Pgno dbSize; /* Number of pages in the database */
37084 Pgno dbOrigSize; /* dbSize before the current transaction */
37085 Pgno dbFileSize; /* Number of pages in the database file */
37086 Pgno dbHintSize; /* Value passed to FCNTL_SIZE_HINT call */
37087 int errCode; /* One of several kinds of errors */
37088 int nRec; /* Pages journalled since last j-header written */
37089 u32 cksumInit; /* Quasi-random value added to every checksum */
37090 u32 nSubRec; /* Number of records written to sub-journal */
37091 Bitvec *pInJournal; /* One bit for each page in the database file */
37092 sqlite3_file *fd; /* File descriptor for database */
37093 sqlite3_file *jfd; /* File descriptor for main journal */
37094 sqlite3_file *sjfd; /* File descriptor for sub-journal */
37095 i64 journalOff; /* Current write offset in the journal file */
37096 i64 journalHdr; /* Byte offset to previous journal header */
37097 sqlite3_backup *pBackup; /* Pointer to list of ongoing backup processes */
37098 PagerSavepoint *aSavepoint; /* Array of active savepoints */
37099 int nSavepoint; /* Number of elements in aSavepoint[] */
37100 char dbFileVers[16]; /* Changes whenever database file changes */
37102 ** End of the routinely-changing class members
37103 ***************************************************************************/
37105 u16 nExtra; /* Add this many bytes to each in-memory page */
37106 i16 nReserve; /* Number of unused bytes at end of each page */
37107 u32 vfsFlags; /* Flags for sqlite3_vfs.xOpen() */
37108 u32 sectorSize; /* Assumed sector size during rollback */
37109 int pageSize; /* Number of bytes in a page */
37110 Pgno mxPgno; /* Maximum allowed size of the database */
37111 i64 journalSizeLimit; /* Size limit for persistent journal files */
37112 char *zFilename; /* Name of the database file */
37113 char *zJournal; /* Name of the journal file */
37114 int (*xBusyHandler)(void*); /* Function to call when busy */
37115 void *pBusyHandlerArg; /* Context argument for xBusyHandler */
37116 #ifdef SQLITE_TEST
37117 int nHit, nMiss; /* Cache hits and missing */
37118 int nRead, nWrite; /* Database pages read/written */
37119 #endif
37120 void (*xReiniter)(DbPage*); /* Call this routine when reloading pages */
37121 #ifdef SQLITE_HAS_CODEC
37122 void *(*xCodec)(void*,void*,Pgno,int); /* Routine for en/decoding data */
37123 void (*xCodecSizeChng)(void*,int,int); /* Notify of page size changes */
37124 void (*xCodecFree)(void*); /* Destructor for the codec */
37125 void *pCodec; /* First argument to xCodec... methods */
37126 #endif
37127 char *pTmpSpace; /* Pager.pageSize bytes of space for tmp use */
37128 PCache *pPCache; /* Pointer to page cache object */
37129 #ifndef SQLITE_OMIT_WAL
37130 Wal *pWal; /* Write-ahead log used by "journal_mode=wal" */
37131 char *zWal; /* File name for write-ahead log */
37132 #endif
37136 ** The following global variables hold counters used for
37137 ** testing purposes only. These variables do not exist in
37138 ** a non-testing build. These variables are not thread-safe.
37140 #ifdef SQLITE_TEST
37141 SQLITE_API int sqlite3_pager_readdb_count = 0; /* Number of full pages read from DB */
37142 SQLITE_API int sqlite3_pager_writedb_count = 0; /* Number of full pages written to DB */
37143 SQLITE_API int sqlite3_pager_writej_count = 0; /* Number of pages written to journal */
37144 # define PAGER_INCR(v) v++
37145 #else
37146 # define PAGER_INCR(v)
37147 #endif
37152 ** Journal files begin with the following magic string. The data
37153 ** was obtained from /dev/random. It is used only as a sanity check.
37155 ** Since version 2.8.0, the journal format contains additional sanity
37156 ** checking information. If the power fails while the journal is being
37157 ** written, semi-random garbage data might appear in the journal
37158 ** file after power is restored. If an attempt is then made
37159 ** to roll the journal back, the database could be corrupted. The additional
37160 ** sanity checking data is an attempt to discover the garbage in the
37161 ** journal and ignore it.
37163 ** The sanity checking information for the new journal format consists
37164 ** of a 32-bit checksum on each page of data. The checksum covers both
37165 ** the page number and the pPager->pageSize bytes of data for the page.
37166 ** This cksum is initialized to a 32-bit random value that appears in the
37167 ** journal file right after the header. The random initializer is important,
37168 ** because garbage data that appears at the end of a journal is likely
37169 ** data that was once in other files that have now been deleted. If the
37170 ** garbage data came from an obsolete journal file, the checksums might
37171 ** be correct. But by initializing the checksum to random value which
37172 ** is different for every journal, we minimize that risk.
37174 static const unsigned char aJournalMagic[] = {
37175 0xd9, 0xd5, 0x05, 0xf9, 0x20, 0xa1, 0x63, 0xd7,
37179 ** The size of the of each page record in the journal is given by
37180 ** the following macro.
37182 #define JOURNAL_PG_SZ(pPager) ((pPager->pageSize) + 8)
37185 ** The journal header size for this pager. This is usually the same
37186 ** size as a single disk sector. See also setSectorSize().
37188 #define JOURNAL_HDR_SZ(pPager) (pPager->sectorSize)
37191 ** The macro MEMDB is true if we are dealing with an in-memory database.
37192 ** We do this as a macro so that if the SQLITE_OMIT_MEMORYDB macro is set,
37193 ** the value of MEMDB will be a constant and the compiler will optimize
37194 ** out code that would never execute.
37196 #ifdef SQLITE_OMIT_MEMORYDB
37197 # define MEMDB 0
37198 #else
37199 # define MEMDB pPager->memDb
37200 #endif
37203 ** The maximum legal page number is (2^31 - 1).
37205 #define PAGER_MAX_PGNO 2147483647
37208 ** The argument to this macro is a file descriptor (type sqlite3_file*).
37209 ** Return 0 if it is not open, or non-zero (but not 1) if it is.
37211 ** This is so that expressions can be written as:
37213 ** if( isOpen(pPager->jfd) ){ ...
37215 ** instead of
37217 ** if( pPager->jfd->pMethods ){ ...
37219 #define isOpen(pFd) ((pFd)->pMethods)
37222 ** Return true if this pager uses a write-ahead log instead of the usual
37223 ** rollback journal. Otherwise false.
37225 #ifndef SQLITE_OMIT_WAL
37226 static int pagerUseWal(Pager *pPager){
37227 return (pPager->pWal!=0);
37229 #else
37230 # define pagerUseWal(x) 0
37231 # define pagerRollbackWal(x) 0
37232 # define pagerWalFrames(v,w,x,y,z) 0
37233 # define pagerOpenWalIfPresent(z) SQLITE_OK
37234 # define pagerBeginReadTransaction(z) SQLITE_OK
37235 #endif
37237 /* Begin preload-cache.patch for Chromium */
37238 /* See comments above the definition. */
37239 SQLITE_PRIVATE int sqlite3PagerAcquire2(
37240 Pager *pPager,
37241 Pgno pgno,
37242 DbPage **ppPage,
37243 int noContent,
37244 unsigned char *pDataToFill);
37245 /* End preload-cache.patch for Chromium */
37247 #ifndef NDEBUG
37249 ** Usage:
37251 ** assert( assert_pager_state(pPager) );
37253 ** This function runs many asserts to try to find inconsistencies in
37254 ** the internal state of the Pager object.
37256 static int assert_pager_state(Pager *p){
37257 Pager *pPager = p;
37259 /* State must be valid. */
37260 assert( p->eState==PAGER_OPEN
37261 || p->eState==PAGER_READER
37262 || p->eState==PAGER_WRITER_LOCKED
37263 || p->eState==PAGER_WRITER_CACHEMOD
37264 || p->eState==PAGER_WRITER_DBMOD
37265 || p->eState==PAGER_WRITER_FINISHED
37266 || p->eState==PAGER_ERROR
37269 /* Regardless of the current state, a temp-file connection always behaves
37270 ** as if it has an exclusive lock on the database file. It never updates
37271 ** the change-counter field, so the changeCountDone flag is always set.
37273 assert( p->tempFile==0 || p->eLock==EXCLUSIVE_LOCK );
37274 assert( p->tempFile==0 || pPager->changeCountDone );
37276 /* If the useJournal flag is clear, the journal-mode must be "OFF".
37277 ** And if the journal-mode is "OFF", the journal file must not be open.
37279 assert( p->journalMode==PAGER_JOURNALMODE_OFF || p->useJournal );
37280 assert( p->journalMode!=PAGER_JOURNALMODE_OFF || !isOpen(p->jfd) );
37282 /* Check that MEMDB implies noSync. And an in-memory journal. Since
37283 ** this means an in-memory pager performs no IO at all, it cannot encounter
37284 ** either SQLITE_IOERR or SQLITE_FULL during rollback or while finalizing
37285 ** a journal file. (although the in-memory journal implementation may
37286 ** return SQLITE_IOERR_NOMEM while the journal file is being written). It
37287 ** is therefore not possible for an in-memory pager to enter the ERROR
37288 ** state.
37290 if( MEMDB ){
37291 assert( p->noSync );
37292 assert( p->journalMode==PAGER_JOURNALMODE_OFF
37293 || p->journalMode==PAGER_JOURNALMODE_MEMORY
37295 assert( p->eState!=PAGER_ERROR && p->eState!=PAGER_OPEN );
37296 assert( pagerUseWal(p)==0 );
37299 /* If changeCountDone is set, a RESERVED lock or greater must be held
37300 ** on the file.
37302 assert( pPager->changeCountDone==0 || pPager->eLock>=RESERVED_LOCK );
37303 assert( p->eLock!=PENDING_LOCK );
37305 switch( p->eState ){
37306 case PAGER_OPEN:
37307 assert( !MEMDB );
37308 assert( pPager->errCode==SQLITE_OK );
37309 assert( sqlite3PcacheRefCount(pPager->pPCache)==0 || pPager->tempFile );
37310 break;
37312 case PAGER_READER:
37313 assert( pPager->errCode==SQLITE_OK );
37314 assert( p->eLock!=UNKNOWN_LOCK );
37315 assert( p->eLock>=SHARED_LOCK || p->noReadlock );
37316 break;
37318 case PAGER_WRITER_LOCKED:
37319 assert( p->eLock!=UNKNOWN_LOCK );
37320 assert( pPager->errCode==SQLITE_OK );
37321 if( !pagerUseWal(pPager) ){
37322 assert( p->eLock>=RESERVED_LOCK );
37324 assert( pPager->dbSize==pPager->dbOrigSize );
37325 assert( pPager->dbOrigSize==pPager->dbFileSize );
37326 assert( pPager->dbOrigSize==pPager->dbHintSize );
37327 assert( pPager->setMaster==0 );
37328 break;
37330 case PAGER_WRITER_CACHEMOD:
37331 assert( p->eLock!=UNKNOWN_LOCK );
37332 assert( pPager->errCode==SQLITE_OK );
37333 if( !pagerUseWal(pPager) ){
37334 /* It is possible that if journal_mode=wal here that neither the
37335 ** journal file nor the WAL file are open. This happens during
37336 ** a rollback transaction that switches from journal_mode=off
37337 ** to journal_mode=wal.
37339 assert( p->eLock>=RESERVED_LOCK );
37340 assert( isOpen(p->jfd)
37341 || p->journalMode==PAGER_JOURNALMODE_OFF
37342 || p->journalMode==PAGER_JOURNALMODE_WAL
37345 assert( pPager->dbOrigSize==pPager->dbFileSize );
37346 assert( pPager->dbOrigSize==pPager->dbHintSize );
37347 break;
37349 case PAGER_WRITER_DBMOD:
37350 assert( p->eLock==EXCLUSIVE_LOCK );
37351 assert( pPager->errCode==SQLITE_OK );
37352 assert( !pagerUseWal(pPager) );
37353 assert( p->eLock>=EXCLUSIVE_LOCK );
37354 assert( isOpen(p->jfd)
37355 || p->journalMode==PAGER_JOURNALMODE_OFF
37356 || p->journalMode==PAGER_JOURNALMODE_WAL
37358 assert( pPager->dbOrigSize<=pPager->dbHintSize );
37359 break;
37361 case PAGER_WRITER_FINISHED:
37362 assert( p->eLock==EXCLUSIVE_LOCK );
37363 assert( pPager->errCode==SQLITE_OK );
37364 assert( !pagerUseWal(pPager) );
37365 assert( isOpen(p->jfd)
37366 || p->journalMode==PAGER_JOURNALMODE_OFF
37367 || p->journalMode==PAGER_JOURNALMODE_WAL
37369 break;
37371 case PAGER_ERROR:
37372 /* There must be at least one outstanding reference to the pager if
37373 ** in ERROR state. Otherwise the pager should have already dropped
37374 ** back to OPEN state.
37376 assert( pPager->errCode!=SQLITE_OK );
37377 assert( sqlite3PcacheRefCount(pPager->pPCache)>0 );
37378 break;
37381 return 1;
37383 #endif /* ifndef NDEBUG */
37385 #ifdef SQLITE_DEBUG
37387 ** Return a pointer to a human readable string in a static buffer
37388 ** containing the state of the Pager object passed as an argument. This
37389 ** is intended to be used within debuggers. For example, as an alternative
37390 ** to "print *pPager" in gdb:
37392 ** (gdb) printf "%s", print_pager_state(pPager)
37394 static char *print_pager_state(Pager *p){
37395 static char zRet[1024];
37397 sqlite3_snprintf(1024, zRet,
37398 "Filename: %s\n"
37399 "State: %s errCode=%d\n"
37400 "Lock: %s\n"
37401 "Locking mode: locking_mode=%s\n"
37402 "Journal mode: journal_mode=%s\n"
37403 "Backing store: tempFile=%d memDb=%d useJournal=%d\n"
37404 "Journal: journalOff=%lld journalHdr=%lld\n"
37405 "Size: dbsize=%d dbOrigSize=%d dbFileSize=%d\n"
37406 , p->zFilename
37407 , p->eState==PAGER_OPEN ? "OPEN" :
37408 p->eState==PAGER_READER ? "READER" :
37409 p->eState==PAGER_WRITER_LOCKED ? "WRITER_LOCKED" :
37410 p->eState==PAGER_WRITER_CACHEMOD ? "WRITER_CACHEMOD" :
37411 p->eState==PAGER_WRITER_DBMOD ? "WRITER_DBMOD" :
37412 p->eState==PAGER_WRITER_FINISHED ? "WRITER_FINISHED" :
37413 p->eState==PAGER_ERROR ? "ERROR" : "?error?"
37414 , (int)p->errCode
37415 , p->eLock==NO_LOCK ? "NO_LOCK" :
37416 p->eLock==RESERVED_LOCK ? "RESERVED" :
37417 p->eLock==EXCLUSIVE_LOCK ? "EXCLUSIVE" :
37418 p->eLock==SHARED_LOCK ? "SHARED" :
37419 p->eLock==UNKNOWN_LOCK ? "UNKNOWN" : "?error?"
37420 , p->exclusiveMode ? "exclusive" : "normal"
37421 , p->journalMode==PAGER_JOURNALMODE_MEMORY ? "memory" :
37422 p->journalMode==PAGER_JOURNALMODE_OFF ? "off" :
37423 p->journalMode==PAGER_JOURNALMODE_DELETE ? "delete" :
37424 p->journalMode==PAGER_JOURNALMODE_PERSIST ? "persist" :
37425 p->journalMode==PAGER_JOURNALMODE_TRUNCATE ? "truncate" :
37426 p->journalMode==PAGER_JOURNALMODE_WAL ? "wal" : "?error?"
37427 , (int)p->tempFile, (int)p->memDb, (int)p->useJournal
37428 , p->journalOff, p->journalHdr
37429 , (int)p->dbSize, (int)p->dbOrigSize, (int)p->dbFileSize
37432 return zRet;
37434 #endif
37437 ** Return true if it is necessary to write page *pPg into the sub-journal.
37438 ** A page needs to be written into the sub-journal if there exists one
37439 ** or more open savepoints for which:
37441 ** * The page-number is less than or equal to PagerSavepoint.nOrig, and
37442 ** * The bit corresponding to the page-number is not set in
37443 ** PagerSavepoint.pInSavepoint.
37445 static int subjRequiresPage(PgHdr *pPg){
37446 Pgno pgno = pPg->pgno;
37447 Pager *pPager = pPg->pPager;
37448 int i;
37449 for(i=0; i<pPager->nSavepoint; i++){
37450 PagerSavepoint *p = &pPager->aSavepoint[i];
37451 if( p->nOrig>=pgno && 0==sqlite3BitvecTest(p->pInSavepoint, pgno) ){
37452 return 1;
37455 return 0;
37459 ** Return true if the page is already in the journal file.
37461 static int pageInJournal(PgHdr *pPg){
37462 return sqlite3BitvecTest(pPg->pPager->pInJournal, pPg->pgno);
37466 ** Read a 32-bit integer from the given file descriptor. Store the integer
37467 ** that is read in *pRes. Return SQLITE_OK if everything worked, or an
37468 ** error code is something goes wrong.
37470 ** All values are stored on disk as big-endian.
37472 static int read32bits(sqlite3_file *fd, i64 offset, u32 *pRes){
37473 unsigned char ac[4];
37474 int rc = sqlite3OsRead(fd, ac, sizeof(ac), offset);
37475 if( rc==SQLITE_OK ){
37476 *pRes = sqlite3Get4byte(ac);
37478 return rc;
37482 ** Write a 32-bit integer into a string buffer in big-endian byte order.
37484 #define put32bits(A,B) sqlite3Put4byte((u8*)A,B)
37488 ** Write a 32-bit integer into the given file descriptor. Return SQLITE_OK
37489 ** on success or an error code is something goes wrong.
37491 static int write32bits(sqlite3_file *fd, i64 offset, u32 val){
37492 char ac[4];
37493 put32bits(ac, val);
37494 return sqlite3OsWrite(fd, ac, 4, offset);
37498 ** Unlock the database file to level eLock, which must be either NO_LOCK
37499 ** or SHARED_LOCK. Regardless of whether or not the call to xUnlock()
37500 ** succeeds, set the Pager.eLock variable to match the (attempted) new lock.
37502 ** Except, if Pager.eLock is set to UNKNOWN_LOCK when this function is
37503 ** called, do not modify it. See the comment above the #define of
37504 ** UNKNOWN_LOCK for an explanation of this.
37506 static int pagerUnlockDb(Pager *pPager, int eLock){
37507 int rc = SQLITE_OK;
37509 assert( !pPager->exclusiveMode || pPager->eLock==eLock );
37510 assert( eLock==NO_LOCK || eLock==SHARED_LOCK );
37511 assert( eLock!=NO_LOCK || pagerUseWal(pPager)==0 );
37512 if( isOpen(pPager->fd) ){
37513 assert( pPager->eLock>=eLock );
37514 rc = sqlite3OsUnlock(pPager->fd, eLock);
37515 if( pPager->eLock!=UNKNOWN_LOCK ){
37516 pPager->eLock = (u8)eLock;
37518 IOTRACE(("UNLOCK %p %d\n", pPager, eLock))
37520 return rc;
37524 ** Lock the database file to level eLock, which must be either SHARED_LOCK,
37525 ** RESERVED_LOCK or EXCLUSIVE_LOCK. If the caller is successful, set the
37526 ** Pager.eLock variable to the new locking state.
37528 ** Except, if Pager.eLock is set to UNKNOWN_LOCK when this function is
37529 ** called, do not modify it unless the new locking state is EXCLUSIVE_LOCK.
37530 ** See the comment above the #define of UNKNOWN_LOCK for an explanation
37531 ** of this.
37533 static int pagerLockDb(Pager *pPager, int eLock){
37534 int rc = SQLITE_OK;
37536 assert( eLock==SHARED_LOCK || eLock==RESERVED_LOCK || eLock==EXCLUSIVE_LOCK );
37537 if( pPager->eLock<eLock || pPager->eLock==UNKNOWN_LOCK ){
37538 rc = sqlite3OsLock(pPager->fd, eLock);
37539 if( rc==SQLITE_OK && (pPager->eLock!=UNKNOWN_LOCK||eLock==EXCLUSIVE_LOCK) ){
37540 pPager->eLock = (u8)eLock;
37541 IOTRACE(("LOCK %p %d\n", pPager, eLock))
37544 return rc;
37548 ** This function determines whether or not the atomic-write optimization
37549 ** can be used with this pager. The optimization can be used if:
37551 ** (a) the value returned by OsDeviceCharacteristics() indicates that
37552 ** a database page may be written atomically, and
37553 ** (b) the value returned by OsSectorSize() is less than or equal
37554 ** to the page size.
37556 ** The optimization is also always enabled for temporary files. It is
37557 ** an error to call this function if pPager is opened on an in-memory
37558 ** database.
37560 ** If the optimization cannot be used, 0 is returned. If it can be used,
37561 ** then the value returned is the size of the journal file when it
37562 ** contains rollback data for exactly one page.
37564 #ifdef SQLITE_ENABLE_ATOMIC_WRITE
37565 static int jrnlBufferSize(Pager *pPager){
37566 assert( !MEMDB );
37567 if( !pPager->tempFile ){
37568 int dc; /* Device characteristics */
37569 int nSector; /* Sector size */
37570 int szPage; /* Page size */
37572 assert( isOpen(pPager->fd) );
37573 dc = sqlite3OsDeviceCharacteristics(pPager->fd);
37574 nSector = pPager->sectorSize;
37575 szPage = pPager->pageSize;
37577 assert(SQLITE_IOCAP_ATOMIC512==(512>>8));
37578 assert(SQLITE_IOCAP_ATOMIC64K==(65536>>8));
37579 if( 0==(dc&(SQLITE_IOCAP_ATOMIC|(szPage>>8)) || nSector>szPage) ){
37580 return 0;
37584 return JOURNAL_HDR_SZ(pPager) + JOURNAL_PG_SZ(pPager);
37586 #endif
37589 ** If SQLITE_CHECK_PAGES is defined then we do some sanity checking
37590 ** on the cache using a hash function. This is used for testing
37591 ** and debugging only.
37593 #ifdef SQLITE_CHECK_PAGES
37595 ** Return a 32-bit hash of the page data for pPage.
37597 static u32 pager_datahash(int nByte, unsigned char *pData){
37598 u32 hash = 0;
37599 int i;
37600 for(i=0; i<nByte; i++){
37601 hash = (hash*1039) + pData[i];
37603 return hash;
37605 static u32 pager_pagehash(PgHdr *pPage){
37606 return pager_datahash(pPage->pPager->pageSize, (unsigned char *)pPage->pData);
37608 static void pager_set_pagehash(PgHdr *pPage){
37609 pPage->pageHash = pager_pagehash(pPage);
37613 ** The CHECK_PAGE macro takes a PgHdr* as an argument. If SQLITE_CHECK_PAGES
37614 ** is defined, and NDEBUG is not defined, an assert() statement checks
37615 ** that the page is either dirty or still matches the calculated page-hash.
37617 #define CHECK_PAGE(x) checkPage(x)
37618 static void checkPage(PgHdr *pPg){
37619 Pager *pPager = pPg->pPager;
37620 assert( pPager->eState!=PAGER_ERROR );
37621 assert( (pPg->flags&PGHDR_DIRTY) || pPg->pageHash==pager_pagehash(pPg) );
37624 #else
37625 #define pager_datahash(X,Y) 0
37626 #define pager_pagehash(X) 0
37627 #define pager_set_pagehash(X)
37628 #define CHECK_PAGE(x)
37629 #endif /* SQLITE_CHECK_PAGES */
37632 ** When this is called the journal file for pager pPager must be open.
37633 ** This function attempts to read a master journal file name from the
37634 ** end of the file and, if successful, copies it into memory supplied
37635 ** by the caller. See comments above writeMasterJournal() for the format
37636 ** used to store a master journal file name at the end of a journal file.
37638 ** zMaster must point to a buffer of at least nMaster bytes allocated by
37639 ** the caller. This should be sqlite3_vfs.mxPathname+1 (to ensure there is
37640 ** enough space to write the master journal name). If the master journal
37641 ** name in the journal is longer than nMaster bytes (including a
37642 ** nul-terminator), then this is handled as if no master journal name
37643 ** were present in the journal.
37645 ** If a master journal file name is present at the end of the journal
37646 ** file, then it is copied into the buffer pointed to by zMaster. A
37647 ** nul-terminator byte is appended to the buffer following the master
37648 ** journal file name.
37650 ** If it is determined that no master journal file name is present
37651 ** zMaster[0] is set to 0 and SQLITE_OK returned.
37653 ** If an error occurs while reading from the journal file, an SQLite
37654 ** error code is returned.
37656 static int readMasterJournal(sqlite3_file *pJrnl, char *zMaster, u32 nMaster){
37657 int rc; /* Return code */
37658 u32 len; /* Length in bytes of master journal name */
37659 i64 szJ; /* Total size in bytes of journal file pJrnl */
37660 u32 cksum; /* MJ checksum value read from journal */
37661 u32 u; /* Unsigned loop counter */
37662 unsigned char aMagic[8]; /* A buffer to hold the magic header */
37663 zMaster[0] = '\0';
37665 if( SQLITE_OK!=(rc = sqlite3OsFileSize(pJrnl, &szJ))
37666 || szJ<16
37667 || SQLITE_OK!=(rc = read32bits(pJrnl, szJ-16, &len))
37668 || len>=nMaster
37669 || SQLITE_OK!=(rc = read32bits(pJrnl, szJ-12, &cksum))
37670 || SQLITE_OK!=(rc = sqlite3OsRead(pJrnl, aMagic, 8, szJ-8))
37671 || memcmp(aMagic, aJournalMagic, 8)
37672 || SQLITE_OK!=(rc = sqlite3OsRead(pJrnl, zMaster, len, szJ-16-len))
37674 return rc;
37677 /* See if the checksum matches the master journal name */
37678 for(u=0; u<len; u++){
37679 cksum -= zMaster[u];
37681 if( cksum ){
37682 /* If the checksum doesn't add up, then one or more of the disk sectors
37683 ** containing the master journal filename is corrupted. This means
37684 ** definitely roll back, so just return SQLITE_OK and report a (nul)
37685 ** master-journal filename.
37687 len = 0;
37689 zMaster[len] = '\0';
37691 return SQLITE_OK;
37695 ** Return the offset of the sector boundary at or immediately
37696 ** following the value in pPager->journalOff, assuming a sector
37697 ** size of pPager->sectorSize bytes.
37699 ** i.e for a sector size of 512:
37701 ** Pager.journalOff Return value
37702 ** ---------------------------------------
37703 ** 0 0
37704 ** 512 512
37705 ** 100 512
37706 ** 2000 2048
37709 static i64 journalHdrOffset(Pager *pPager){
37710 i64 offset = 0;
37711 i64 c = pPager->journalOff;
37712 if( c ){
37713 offset = ((c-1)/JOURNAL_HDR_SZ(pPager) + 1) * JOURNAL_HDR_SZ(pPager);
37715 assert( offset%JOURNAL_HDR_SZ(pPager)==0 );
37716 assert( offset>=c );
37717 assert( (offset-c)<JOURNAL_HDR_SZ(pPager) );
37718 return offset;
37722 ** The journal file must be open when this function is called.
37724 ** This function is a no-op if the journal file has not been written to
37725 ** within the current transaction (i.e. if Pager.journalOff==0).
37727 ** If doTruncate is non-zero or the Pager.journalSizeLimit variable is
37728 ** set to 0, then truncate the journal file to zero bytes in size. Otherwise,
37729 ** zero the 28-byte header at the start of the journal file. In either case,
37730 ** if the pager is not in no-sync mode, sync the journal file immediately
37731 ** after writing or truncating it.
37733 ** If Pager.journalSizeLimit is set to a positive, non-zero value, and
37734 ** following the truncation or zeroing described above the size of the
37735 ** journal file in bytes is larger than this value, then truncate the
37736 ** journal file to Pager.journalSizeLimit bytes. The journal file does
37737 ** not need to be synced following this operation.
37739 ** If an IO error occurs, abandon processing and return the IO error code.
37740 ** Otherwise, return SQLITE_OK.
37742 static int zeroJournalHdr(Pager *pPager, int doTruncate){
37743 int rc = SQLITE_OK; /* Return code */
37744 assert( isOpen(pPager->jfd) );
37745 if( pPager->journalOff ){
37746 const i64 iLimit = pPager->journalSizeLimit; /* Local cache of jsl */
37748 IOTRACE(("JZEROHDR %p\n", pPager))
37749 if( doTruncate || iLimit==0 ){
37750 rc = sqlite3OsTruncate(pPager->jfd, 0);
37751 }else{
37752 static const char zeroHdr[28] = {0};
37753 rc = sqlite3OsWrite(pPager->jfd, zeroHdr, sizeof(zeroHdr), 0);
37755 if( rc==SQLITE_OK && !pPager->noSync ){
37756 rc = sqlite3OsSync(pPager->jfd, SQLITE_SYNC_DATAONLY|pPager->syncFlags);
37759 /* At this point the transaction is committed but the write lock
37760 ** is still held on the file. If there is a size limit configured for
37761 ** the persistent journal and the journal file currently consumes more
37762 ** space than that limit allows for, truncate it now. There is no need
37763 ** to sync the file following this operation.
37765 if( rc==SQLITE_OK && iLimit>0 ){
37766 i64 sz;
37767 rc = sqlite3OsFileSize(pPager->jfd, &sz);
37768 if( rc==SQLITE_OK && sz>iLimit ){
37769 rc = sqlite3OsTruncate(pPager->jfd, iLimit);
37773 return rc;
37777 ** The journal file must be open when this routine is called. A journal
37778 ** header (JOURNAL_HDR_SZ bytes) is written into the journal file at the
37779 ** current location.
37781 ** The format for the journal header is as follows:
37782 ** - 8 bytes: Magic identifying journal format.
37783 ** - 4 bytes: Number of records in journal, or -1 no-sync mode is on.
37784 ** - 4 bytes: Random number used for page hash.
37785 ** - 4 bytes: Initial database page count.
37786 ** - 4 bytes: Sector size used by the process that wrote this journal.
37787 ** - 4 bytes: Database page size.
37789 ** Followed by (JOURNAL_HDR_SZ - 28) bytes of unused space.
37791 static int writeJournalHdr(Pager *pPager){
37792 int rc = SQLITE_OK; /* Return code */
37793 char *zHeader = pPager->pTmpSpace; /* Temporary space used to build header */
37794 u32 nHeader = (u32)pPager->pageSize;/* Size of buffer pointed to by zHeader */
37795 u32 nWrite; /* Bytes of header sector written */
37796 int ii; /* Loop counter */
37798 assert( isOpen(pPager->jfd) ); /* Journal file must be open. */
37800 if( nHeader>JOURNAL_HDR_SZ(pPager) ){
37801 nHeader = JOURNAL_HDR_SZ(pPager);
37804 /* If there are active savepoints and any of them were created
37805 ** since the most recent journal header was written, update the
37806 ** PagerSavepoint.iHdrOffset fields now.
37808 for(ii=0; ii<pPager->nSavepoint; ii++){
37809 if( pPager->aSavepoint[ii].iHdrOffset==0 ){
37810 pPager->aSavepoint[ii].iHdrOffset = pPager->journalOff;
37814 pPager->journalHdr = pPager->journalOff = journalHdrOffset(pPager);
37817 ** Write the nRec Field - the number of page records that follow this
37818 ** journal header. Normally, zero is written to this value at this time.
37819 ** After the records are added to the journal (and the journal synced,
37820 ** if in full-sync mode), the zero is overwritten with the true number
37821 ** of records (see syncJournal()).
37823 ** A faster alternative is to write 0xFFFFFFFF to the nRec field. When
37824 ** reading the journal this value tells SQLite to assume that the
37825 ** rest of the journal file contains valid page records. This assumption
37826 ** is dangerous, as if a failure occurred whilst writing to the journal
37827 ** file it may contain some garbage data. There are two scenarios
37828 ** where this risk can be ignored:
37830 ** * When the pager is in no-sync mode. Corruption can follow a
37831 ** power failure in this case anyway.
37833 ** * When the SQLITE_IOCAP_SAFE_APPEND flag is set. This guarantees
37834 ** that garbage data is never appended to the journal file.
37836 assert( isOpen(pPager->fd) || pPager->noSync );
37837 if( pPager->noSync || (pPager->journalMode==PAGER_JOURNALMODE_MEMORY)
37838 || (sqlite3OsDeviceCharacteristics(pPager->fd)&SQLITE_IOCAP_SAFE_APPEND)
37840 memcpy(zHeader, aJournalMagic, sizeof(aJournalMagic));
37841 put32bits(&zHeader[sizeof(aJournalMagic)], 0xffffffff);
37842 }else{
37843 memset(zHeader, 0, sizeof(aJournalMagic)+4);
37846 /* The random check-hash initialiser */
37847 sqlite3_randomness(sizeof(pPager->cksumInit), &pPager->cksumInit);
37848 put32bits(&zHeader[sizeof(aJournalMagic)+4], pPager->cksumInit);
37849 /* The initial database size */
37850 put32bits(&zHeader[sizeof(aJournalMagic)+8], pPager->dbOrigSize);
37851 /* The assumed sector size for this process */
37852 put32bits(&zHeader[sizeof(aJournalMagic)+12], pPager->sectorSize);
37854 /* The page size */
37855 put32bits(&zHeader[sizeof(aJournalMagic)+16], pPager->pageSize);
37857 /* Initializing the tail of the buffer is not necessary. Everything
37858 ** works find if the following memset() is omitted. But initializing
37859 ** the memory prevents valgrind from complaining, so we are willing to
37860 ** take the performance hit.
37862 memset(&zHeader[sizeof(aJournalMagic)+20], 0,
37863 nHeader-(sizeof(aJournalMagic)+20));
37865 /* In theory, it is only necessary to write the 28 bytes that the
37866 ** journal header consumes to the journal file here. Then increment the
37867 ** Pager.journalOff variable by JOURNAL_HDR_SZ so that the next
37868 ** record is written to the following sector (leaving a gap in the file
37869 ** that will be implicitly filled in by the OS).
37871 ** However it has been discovered that on some systems this pattern can
37872 ** be significantly slower than contiguously writing data to the file,
37873 ** even if that means explicitly writing data to the block of
37874 ** (JOURNAL_HDR_SZ - 28) bytes that will not be used. So that is what
37875 ** is done.
37877 ** The loop is required here in case the sector-size is larger than the
37878 ** database page size. Since the zHeader buffer is only Pager.pageSize
37879 ** bytes in size, more than one call to sqlite3OsWrite() may be required
37880 ** to populate the entire journal header sector.
37882 for(nWrite=0; rc==SQLITE_OK&&nWrite<JOURNAL_HDR_SZ(pPager); nWrite+=nHeader){
37883 IOTRACE(("JHDR %p %lld %d\n", pPager, pPager->journalHdr, nHeader))
37884 rc = sqlite3OsWrite(pPager->jfd, zHeader, nHeader, pPager->journalOff);
37885 assert( pPager->journalHdr <= pPager->journalOff );
37886 pPager->journalOff += nHeader;
37889 return rc;
37893 ** The journal file must be open when this is called. A journal header file
37894 ** (JOURNAL_HDR_SZ bytes) is read from the current location in the journal
37895 ** file. The current location in the journal file is given by
37896 ** pPager->journalOff. See comments above function writeJournalHdr() for
37897 ** a description of the journal header format.
37899 ** If the header is read successfully, *pNRec is set to the number of
37900 ** page records following this header and *pDbSize is set to the size of the
37901 ** database before the transaction began, in pages. Also, pPager->cksumInit
37902 ** is set to the value read from the journal header. SQLITE_OK is returned
37903 ** in this case.
37905 ** If the journal header file appears to be corrupted, SQLITE_DONE is
37906 ** returned and *pNRec and *PDbSize are undefined. If JOURNAL_HDR_SZ bytes
37907 ** cannot be read from the journal file an error code is returned.
37909 static int readJournalHdr(
37910 Pager *pPager, /* Pager object */
37911 int isHot,
37912 i64 journalSize, /* Size of the open journal file in bytes */
37913 u32 *pNRec, /* OUT: Value read from the nRec field */
37914 u32 *pDbSize /* OUT: Value of original database size field */
37916 int rc; /* Return code */
37917 unsigned char aMagic[8]; /* A buffer to hold the magic header */
37918 i64 iHdrOff; /* Offset of journal header being read */
37920 assert( isOpen(pPager->jfd) ); /* Journal file must be open. */
37922 /* Advance Pager.journalOff to the start of the next sector. If the
37923 ** journal file is too small for there to be a header stored at this
37924 ** point, return SQLITE_DONE.
37926 pPager->journalOff = journalHdrOffset(pPager);
37927 if( pPager->journalOff+JOURNAL_HDR_SZ(pPager) > journalSize ){
37928 return SQLITE_DONE;
37930 iHdrOff = pPager->journalOff;
37932 /* Read in the first 8 bytes of the journal header. If they do not match
37933 ** the magic string found at the start of each journal header, return
37934 ** SQLITE_DONE. If an IO error occurs, return an error code. Otherwise,
37935 ** proceed.
37937 if( isHot || iHdrOff!=pPager->journalHdr ){
37938 rc = sqlite3OsRead(pPager->jfd, aMagic, sizeof(aMagic), iHdrOff);
37939 if( rc ){
37940 return rc;
37942 if( memcmp(aMagic, aJournalMagic, sizeof(aMagic))!=0 ){
37943 return SQLITE_DONE;
37947 /* Read the first three 32-bit fields of the journal header: The nRec
37948 ** field, the checksum-initializer and the database size at the start
37949 ** of the transaction. Return an error code if anything goes wrong.
37951 if( SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+8, pNRec))
37952 || SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+12, &pPager->cksumInit))
37953 || SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+16, pDbSize))
37955 return rc;
37958 if( pPager->journalOff==0 ){
37959 u32 iPageSize; /* Page-size field of journal header */
37960 u32 iSectorSize; /* Sector-size field of journal header */
37962 /* Read the page-size and sector-size journal header fields. */
37963 if( SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+20, &iSectorSize))
37964 || SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+24, &iPageSize))
37966 return rc;
37969 /* Versions of SQLite prior to 3.5.8 set the page-size field of the
37970 ** journal header to zero. In this case, assume that the Pager.pageSize
37971 ** variable is already set to the correct page size.
37973 if( iPageSize==0 ){
37974 iPageSize = pPager->pageSize;
37977 /* Check that the values read from the page-size and sector-size fields
37978 ** are within range. To be 'in range', both values need to be a power
37979 ** of two greater than or equal to 512 or 32, and not greater than their
37980 ** respective compile time maximum limits.
37982 if( iPageSize<512 || iSectorSize<32
37983 || iPageSize>SQLITE_MAX_PAGE_SIZE || iSectorSize>MAX_SECTOR_SIZE
37984 || ((iPageSize-1)&iPageSize)!=0 || ((iSectorSize-1)&iSectorSize)!=0
37986 /* If the either the page-size or sector-size in the journal-header is
37987 ** invalid, then the process that wrote the journal-header must have
37988 ** crashed before the header was synced. In this case stop reading
37989 ** the journal file here.
37991 return SQLITE_DONE;
37994 /* Update the page-size to match the value read from the journal.
37995 ** Use a testcase() macro to make sure that malloc failure within
37996 ** PagerSetPagesize() is tested.
37998 rc = sqlite3PagerSetPagesize(pPager, &iPageSize, -1);
37999 testcase( rc!=SQLITE_OK );
38001 /* Update the assumed sector-size to match the value used by
38002 ** the process that created this journal. If this journal was
38003 ** created by a process other than this one, then this routine
38004 ** is being called from within pager_playback(). The local value
38005 ** of Pager.sectorSize is restored at the end of that routine.
38007 pPager->sectorSize = iSectorSize;
38010 pPager->journalOff += JOURNAL_HDR_SZ(pPager);
38011 return rc;
38016 ** Write the supplied master journal name into the journal file for pager
38017 ** pPager at the current location. The master journal name must be the last
38018 ** thing written to a journal file. If the pager is in full-sync mode, the
38019 ** journal file descriptor is advanced to the next sector boundary before
38020 ** anything is written. The format is:
38022 ** + 4 bytes: PAGER_MJ_PGNO.
38023 ** + N bytes: Master journal filename in utf-8.
38024 ** + 4 bytes: N (length of master journal name in bytes, no nul-terminator).
38025 ** + 4 bytes: Master journal name checksum.
38026 ** + 8 bytes: aJournalMagic[].
38028 ** The master journal page checksum is the sum of the bytes in the master
38029 ** journal name, where each byte is interpreted as a signed 8-bit integer.
38031 ** If zMaster is a NULL pointer (occurs for a single database transaction),
38032 ** this call is a no-op.
38034 static int writeMasterJournal(Pager *pPager, const char *zMaster){
38035 int rc; /* Return code */
38036 int nMaster; /* Length of string zMaster */
38037 i64 iHdrOff; /* Offset of header in journal file */
38038 i64 jrnlSize; /* Size of journal file on disk */
38039 u32 cksum = 0; /* Checksum of string zMaster */
38041 assert( pPager->setMaster==0 );
38042 assert( !pagerUseWal(pPager) );
38044 if( !zMaster
38045 || pPager->journalMode==PAGER_JOURNALMODE_MEMORY
38046 || pPager->journalMode==PAGER_JOURNALMODE_OFF
38048 return SQLITE_OK;
38050 pPager->setMaster = 1;
38051 assert( isOpen(pPager->jfd) );
38052 assert( pPager->journalHdr <= pPager->journalOff );
38054 /* Calculate the length in bytes and the checksum of zMaster */
38055 for(nMaster=0; zMaster[nMaster]; nMaster++){
38056 cksum += zMaster[nMaster];
38059 /* If in full-sync mode, advance to the next disk sector before writing
38060 ** the master journal name. This is in case the previous page written to
38061 ** the journal has already been synced.
38063 if( pPager->fullSync ){
38064 pPager->journalOff = journalHdrOffset(pPager);
38066 iHdrOff = pPager->journalOff;
38068 /* Write the master journal data to the end of the journal file. If
38069 ** an error occurs, return the error code to the caller.
38071 if( (0 != (rc = write32bits(pPager->jfd, iHdrOff, PAGER_MJ_PGNO(pPager))))
38072 || (0 != (rc = sqlite3OsWrite(pPager->jfd, zMaster, nMaster, iHdrOff+4)))
38073 || (0 != (rc = write32bits(pPager->jfd, iHdrOff+4+nMaster, nMaster)))
38074 || (0 != (rc = write32bits(pPager->jfd, iHdrOff+4+nMaster+4, cksum)))
38075 || (0 != (rc = sqlite3OsWrite(pPager->jfd, aJournalMagic, 8, iHdrOff+4+nMaster+8)))
38077 return rc;
38079 pPager->journalOff += (nMaster+20);
38081 /* If the pager is in peristent-journal mode, then the physical
38082 ** journal-file may extend past the end of the master-journal name
38083 ** and 8 bytes of magic data just written to the file. This is
38084 ** dangerous because the code to rollback a hot-journal file
38085 ** will not be able to find the master-journal name to determine
38086 ** whether or not the journal is hot.
38088 ** Easiest thing to do in this scenario is to truncate the journal
38089 ** file to the required size.
38091 if( SQLITE_OK==(rc = sqlite3OsFileSize(pPager->jfd, &jrnlSize))
38092 && jrnlSize>pPager->journalOff
38094 rc = sqlite3OsTruncate(pPager->jfd, pPager->journalOff);
38096 return rc;
38100 ** Find a page in the hash table given its page number. Return
38101 ** a pointer to the page or NULL if the requested page is not
38102 ** already in memory.
38104 static PgHdr *pager_lookup(Pager *pPager, Pgno pgno){
38105 PgHdr *p; /* Return value */
38107 /* It is not possible for a call to PcacheFetch() with createFlag==0 to
38108 ** fail, since no attempt to allocate dynamic memory will be made.
38110 (void)sqlite3PcacheFetch(pPager->pPCache, pgno, 0, &p);
38111 return p;
38115 ** Discard the entire contents of the in-memory page-cache.
38117 static void pager_reset(Pager *pPager){
38118 sqlite3BackupRestart(pPager->pBackup);
38119 sqlite3PcacheClear(pPager->pPCache);
38123 ** Free all structures in the Pager.aSavepoint[] array and set both
38124 ** Pager.aSavepoint and Pager.nSavepoint to zero. Close the sub-journal
38125 ** if it is open and the pager is not in exclusive mode.
38127 static void releaseAllSavepoints(Pager *pPager){
38128 int ii; /* Iterator for looping through Pager.aSavepoint */
38129 for(ii=0; ii<pPager->nSavepoint; ii++){
38130 sqlite3BitvecDestroy(pPager->aSavepoint[ii].pInSavepoint);
38132 if( !pPager->exclusiveMode || sqlite3IsMemJournal(pPager->sjfd) ){
38133 sqlite3OsClose(pPager->sjfd);
38135 sqlite3_free(pPager->aSavepoint);
38136 pPager->aSavepoint = 0;
38137 pPager->nSavepoint = 0;
38138 pPager->nSubRec = 0;
38142 ** Set the bit number pgno in the PagerSavepoint.pInSavepoint
38143 ** bitvecs of all open savepoints. Return SQLITE_OK if successful
38144 ** or SQLITE_NOMEM if a malloc failure occurs.
38146 static int addToSavepointBitvecs(Pager *pPager, Pgno pgno){
38147 int ii; /* Loop counter */
38148 int rc = SQLITE_OK; /* Result code */
38150 for(ii=0; ii<pPager->nSavepoint; ii++){
38151 PagerSavepoint *p = &pPager->aSavepoint[ii];
38152 if( pgno<=p->nOrig ){
38153 rc |= sqlite3BitvecSet(p->pInSavepoint, pgno);
38154 testcase( rc==SQLITE_NOMEM );
38155 assert( rc==SQLITE_OK || rc==SQLITE_NOMEM );
38158 return rc;
38162 ** This function is a no-op if the pager is in exclusive mode and not
38163 ** in the ERROR state. Otherwise, it switches the pager to PAGER_OPEN
38164 ** state.
38166 ** If the pager is not in exclusive-access mode, the database file is
38167 ** completely unlocked. If the file is unlocked and the file-system does
38168 ** not exhibit the UNDELETABLE_WHEN_OPEN property, the journal file is
38169 ** closed (if it is open).
38171 ** If the pager is in ERROR state when this function is called, the
38172 ** contents of the pager cache are discarded before switching back to
38173 ** the OPEN state. Regardless of whether the pager is in exclusive-mode
38174 ** or not, any journal file left in the file-system will be treated
38175 ** as a hot-journal and rolled back the next time a read-transaction
38176 ** is opened (by this or by any other connection).
38178 static void pager_unlock(Pager *pPager){
38180 assert( pPager->eState==PAGER_READER
38181 || pPager->eState==PAGER_OPEN
38182 || pPager->eState==PAGER_ERROR
38185 sqlite3BitvecDestroy(pPager->pInJournal);
38186 pPager->pInJournal = 0;
38187 releaseAllSavepoints(pPager);
38189 if( pagerUseWal(pPager) ){
38190 assert( !isOpen(pPager->jfd) );
38191 sqlite3WalEndReadTransaction(pPager->pWal);
38192 pPager->eState = PAGER_OPEN;
38193 }else if( !pPager->exclusiveMode ){
38194 int rc; /* Error code returned by pagerUnlockDb() */
38195 int iDc = isOpen(pPager->fd)?sqlite3OsDeviceCharacteristics(pPager->fd):0;
38197 /* If the operating system support deletion of open files, then
38198 ** close the journal file when dropping the database lock. Otherwise
38199 ** another connection with journal_mode=delete might delete the file
38200 ** out from under us.
38202 assert( (PAGER_JOURNALMODE_MEMORY & 5)!=1 );
38203 assert( (PAGER_JOURNALMODE_OFF & 5)!=1 );
38204 assert( (PAGER_JOURNALMODE_WAL & 5)!=1 );
38205 assert( (PAGER_JOURNALMODE_DELETE & 5)!=1 );
38206 assert( (PAGER_JOURNALMODE_TRUNCATE & 5)==1 );
38207 assert( (PAGER_JOURNALMODE_PERSIST & 5)==1 );
38208 if( 0==(iDc & SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN)
38209 || 1!=(pPager->journalMode & 5)
38211 sqlite3OsClose(pPager->jfd);
38214 /* If the pager is in the ERROR state and the call to unlock the database
38215 ** file fails, set the current lock to UNKNOWN_LOCK. See the comment
38216 ** above the #define for UNKNOWN_LOCK for an explanation of why this
38217 ** is necessary.
38219 rc = pagerUnlockDb(pPager, NO_LOCK);
38220 if( rc!=SQLITE_OK && pPager->eState==PAGER_ERROR ){
38221 pPager->eLock = UNKNOWN_LOCK;
38224 /* The pager state may be changed from PAGER_ERROR to PAGER_OPEN here
38225 ** without clearing the error code. This is intentional - the error
38226 ** code is cleared and the cache reset in the block below.
38228 assert( pPager->errCode || pPager->eState!=PAGER_ERROR );
38229 pPager->changeCountDone = 0;
38230 pPager->eState = PAGER_OPEN;
38233 /* If Pager.errCode is set, the contents of the pager cache cannot be
38234 ** trusted. Now that there are no outstanding references to the pager,
38235 ** it can safely move back to PAGER_OPEN state. This happens in both
38236 ** normal and exclusive-locking mode.
38238 if( pPager->errCode ){
38239 assert( !MEMDB );
38240 pager_reset(pPager);
38241 pPager->changeCountDone = pPager->tempFile;
38242 pPager->eState = PAGER_OPEN;
38243 pPager->errCode = SQLITE_OK;
38246 pPager->journalOff = 0;
38247 pPager->journalHdr = 0;
38248 pPager->setMaster = 0;
38252 ** This function is called whenever an IOERR or FULL error that requires
38253 ** the pager to transition into the ERROR state may ahve occurred.
38254 ** The first argument is a pointer to the pager structure, the second
38255 ** the error-code about to be returned by a pager API function. The
38256 ** value returned is a copy of the second argument to this function.
38258 ** If the second argument is SQLITE_FULL, SQLITE_IOERR or one of the
38259 ** IOERR sub-codes, the pager enters the ERROR state and the error code
38260 ** is stored in Pager.errCode. While the pager remains in the ERROR state,
38261 ** all major API calls on the Pager will immediately return Pager.errCode.
38263 ** The ERROR state indicates that the contents of the pager-cache
38264 ** cannot be trusted. This state can be cleared by completely discarding
38265 ** the contents of the pager-cache. If a transaction was active when
38266 ** the persistent error occurred, then the rollback journal may need
38267 ** to be replayed to restore the contents of the database file (as if
38268 ** it were a hot-journal).
38270 static int pager_error(Pager *pPager, int rc){
38271 int rc2 = rc & 0xff;
38272 assert( rc==SQLITE_OK || !MEMDB );
38273 assert(
38274 pPager->errCode==SQLITE_FULL ||
38275 pPager->errCode==SQLITE_OK ||
38276 (pPager->errCode & 0xff)==SQLITE_IOERR
38278 if( rc2==SQLITE_FULL || rc2==SQLITE_IOERR ){
38279 pPager->errCode = rc;
38280 pPager->eState = PAGER_ERROR;
38282 return rc;
38286 ** This routine ends a transaction. A transaction is usually ended by
38287 ** either a COMMIT or a ROLLBACK operation. This routine may be called
38288 ** after rollback of a hot-journal, or if an error occurs while opening
38289 ** the journal file or writing the very first journal-header of a
38290 ** database transaction.
38292 ** This routine is never called in PAGER_ERROR state. If it is called
38293 ** in PAGER_NONE or PAGER_SHARED state and the lock held is less
38294 ** exclusive than a RESERVED lock, it is a no-op.
38296 ** Otherwise, any active savepoints are released.
38298 ** If the journal file is open, then it is "finalized". Once a journal
38299 ** file has been finalized it is not possible to use it to roll back a
38300 ** transaction. Nor will it be considered to be a hot-journal by this
38301 ** or any other database connection. Exactly how a journal is finalized
38302 ** depends on whether or not the pager is running in exclusive mode and
38303 ** the current journal-mode (Pager.journalMode value), as follows:
38305 ** journalMode==MEMORY
38306 ** Journal file descriptor is simply closed. This destroys an
38307 ** in-memory journal.
38309 ** journalMode==TRUNCATE
38310 ** Journal file is truncated to zero bytes in size.
38312 ** journalMode==PERSIST
38313 ** The first 28 bytes of the journal file are zeroed. This invalidates
38314 ** the first journal header in the file, and hence the entire journal
38315 ** file. An invalid journal file cannot be rolled back.
38317 ** journalMode==DELETE
38318 ** The journal file is closed and deleted using sqlite3OsDelete().
38320 ** If the pager is running in exclusive mode, this method of finalizing
38321 ** the journal file is never used. Instead, if the journalMode is
38322 ** DELETE and the pager is in exclusive mode, the method described under
38323 ** journalMode==PERSIST is used instead.
38325 ** After the journal is finalized, the pager moves to PAGER_READER state.
38326 ** If running in non-exclusive rollback mode, the lock on the file is
38327 ** downgraded to a SHARED_LOCK.
38329 ** SQLITE_OK is returned if no error occurs. If an error occurs during
38330 ** any of the IO operations to finalize the journal file or unlock the
38331 ** database then the IO error code is returned to the user. If the
38332 ** operation to finalize the journal file fails, then the code still
38333 ** tries to unlock the database file if not in exclusive mode. If the
38334 ** unlock operation fails as well, then the first error code related
38335 ** to the first error encountered (the journal finalization one) is
38336 ** returned.
38338 static int pager_end_transaction(Pager *pPager, int hasMaster){
38339 int rc = SQLITE_OK; /* Error code from journal finalization operation */
38340 int rc2 = SQLITE_OK; /* Error code from db file unlock operation */
38342 /* Do nothing if the pager does not have an open write transaction
38343 ** or at least a RESERVED lock. This function may be called when there
38344 ** is no write-transaction active but a RESERVED or greater lock is
38345 ** held under two circumstances:
38347 ** 1. After a successful hot-journal rollback, it is called with
38348 ** eState==PAGER_NONE and eLock==EXCLUSIVE_LOCK.
38350 ** 2. If a connection with locking_mode=exclusive holding an EXCLUSIVE
38351 ** lock switches back to locking_mode=normal and then executes a
38352 ** read-transaction, this function is called with eState==PAGER_READER
38353 ** and eLock==EXCLUSIVE_LOCK when the read-transaction is closed.
38355 assert( assert_pager_state(pPager) );
38356 assert( pPager->eState!=PAGER_ERROR );
38357 if( pPager->eState<PAGER_WRITER_LOCKED && pPager->eLock<RESERVED_LOCK ){
38358 return SQLITE_OK;
38361 releaseAllSavepoints(pPager);
38362 assert( isOpen(pPager->jfd) || pPager->pInJournal==0 );
38363 if( isOpen(pPager->jfd) ){
38364 assert( !pagerUseWal(pPager) );
38366 /* Finalize the journal file. */
38367 if( sqlite3IsMemJournal(pPager->jfd) ){
38368 assert( pPager->journalMode==PAGER_JOURNALMODE_MEMORY );
38369 sqlite3OsClose(pPager->jfd);
38370 }else if( pPager->journalMode==PAGER_JOURNALMODE_TRUNCATE ){
38371 if( pPager->journalOff==0 ){
38372 rc = SQLITE_OK;
38373 }else{
38374 rc = sqlite3OsTruncate(pPager->jfd, 0);
38376 pPager->journalOff = 0;
38377 }else if( pPager->journalMode==PAGER_JOURNALMODE_PERSIST
38378 || (pPager->exclusiveMode && pPager->journalMode!=PAGER_JOURNALMODE_WAL)
38380 rc = zeroJournalHdr(pPager, hasMaster);
38381 pPager->journalOff = 0;
38382 }else{
38383 /* This branch may be executed with Pager.journalMode==MEMORY if
38384 ** a hot-journal was just rolled back. In this case the journal
38385 ** file should be closed and deleted. If this connection writes to
38386 ** the database file, it will do so using an in-memory journal.
38388 assert( pPager->journalMode==PAGER_JOURNALMODE_DELETE
38389 || pPager->journalMode==PAGER_JOURNALMODE_MEMORY
38390 || pPager->journalMode==PAGER_JOURNALMODE_WAL
38392 sqlite3OsClose(pPager->jfd);
38393 if( !pPager->tempFile ){
38394 rc = sqlite3OsDelete(pPager->pVfs, pPager->zJournal, 0);
38399 #ifdef SQLITE_CHECK_PAGES
38400 sqlite3PcacheIterateDirty(pPager->pPCache, pager_set_pagehash);
38401 if( pPager->dbSize==0 && sqlite3PcacheRefCount(pPager->pPCache)>0 ){
38402 PgHdr *p = pager_lookup(pPager, 1);
38403 if( p ){
38404 p->pageHash = 0;
38405 sqlite3PagerUnref(p);
38408 #endif
38410 sqlite3BitvecDestroy(pPager->pInJournal);
38411 pPager->pInJournal = 0;
38412 pPager->nRec = 0;
38413 sqlite3PcacheCleanAll(pPager->pPCache);
38414 sqlite3PcacheTruncate(pPager->pPCache, pPager->dbSize);
38416 if( pagerUseWal(pPager) ){
38417 /* Drop the WAL write-lock, if any. Also, if the connection was in
38418 ** locking_mode=exclusive mode but is no longer, drop the EXCLUSIVE
38419 ** lock held on the database file.
38421 rc2 = sqlite3WalEndWriteTransaction(pPager->pWal);
38422 assert( rc2==SQLITE_OK );
38424 if( !pPager->exclusiveMode
38425 && (!pagerUseWal(pPager) || sqlite3WalExclusiveMode(pPager->pWal, 0))
38427 rc2 = pagerUnlockDb(pPager, SHARED_LOCK);
38428 pPager->changeCountDone = 0;
38430 pPager->eState = PAGER_READER;
38431 pPager->setMaster = 0;
38433 return (rc==SQLITE_OK?rc2:rc);
38437 ** Execute a rollback if a transaction is active and unlock the
38438 ** database file.
38440 ** If the pager has already entered the ERROR state, do not attempt
38441 ** the rollback at this time. Instead, pager_unlock() is called. The
38442 ** call to pager_unlock() will discard all in-memory pages, unlock
38443 ** the database file and move the pager back to OPEN state. If this
38444 ** means that there is a hot-journal left in the file-system, the next
38445 ** connection to obtain a shared lock on the pager (which may be this one)
38446 ** will roll it back.
38448 ** If the pager has not already entered the ERROR state, but an IO or
38449 ** malloc error occurs during a rollback, then this will itself cause
38450 ** the pager to enter the ERROR state. Which will be cleared by the
38451 ** call to pager_unlock(), as described above.
38453 static void pagerUnlockAndRollback(Pager *pPager){
38454 if( pPager->eState!=PAGER_ERROR && pPager->eState!=PAGER_OPEN ){
38455 assert( assert_pager_state(pPager) );
38456 if( pPager->eState>=PAGER_WRITER_LOCKED ){
38457 sqlite3BeginBenignMalloc();
38458 sqlite3PagerRollback(pPager);
38459 sqlite3EndBenignMalloc();
38460 }else if( !pPager->exclusiveMode ){
38461 assert( pPager->eState==PAGER_READER );
38462 pager_end_transaction(pPager, 0);
38465 pager_unlock(pPager);
38469 ** Parameter aData must point to a buffer of pPager->pageSize bytes
38470 ** of data. Compute and return a checksum based ont the contents of the
38471 ** page of data and the current value of pPager->cksumInit.
38473 ** This is not a real checksum. It is really just the sum of the
38474 ** random initial value (pPager->cksumInit) and every 200th byte
38475 ** of the page data, starting with byte offset (pPager->pageSize%200).
38476 ** Each byte is interpreted as an 8-bit unsigned integer.
38478 ** Changing the formula used to compute this checksum results in an
38479 ** incompatible journal file format.
38481 ** If journal corruption occurs due to a power failure, the most likely
38482 ** scenario is that one end or the other of the record will be changed.
38483 ** It is much less likely that the two ends of the journal record will be
38484 ** correct and the middle be corrupt. Thus, this "checksum" scheme,
38485 ** though fast and simple, catches the mostly likely kind of corruption.
38487 static u32 pager_cksum(Pager *pPager, const u8 *aData){
38488 u32 cksum = pPager->cksumInit; /* Checksum value to return */
38489 int i = pPager->pageSize-200; /* Loop counter */
38490 while( i>0 ){
38491 cksum += aData[i];
38492 i -= 200;
38494 return cksum;
38498 ** Report the current page size and number of reserved bytes back
38499 ** to the codec.
38501 #ifdef SQLITE_HAS_CODEC
38502 static void pagerReportSize(Pager *pPager){
38503 if( pPager->xCodecSizeChng ){
38504 pPager->xCodecSizeChng(pPager->pCodec, pPager->pageSize,
38505 (int)pPager->nReserve);
38508 #else
38509 # define pagerReportSize(X) /* No-op if we do not support a codec */
38510 #endif
38513 ** Read a single page from either the journal file (if isMainJrnl==1) or
38514 ** from the sub-journal (if isMainJrnl==0) and playback that page.
38515 ** The page begins at offset *pOffset into the file. The *pOffset
38516 ** value is increased to the start of the next page in the journal.
38518 ** The main rollback journal uses checksums - the statement journal does
38519 ** not.
38521 ** If the page number of the page record read from the (sub-)journal file
38522 ** is greater than the current value of Pager.dbSize, then playback is
38523 ** skipped and SQLITE_OK is returned.
38525 ** If pDone is not NULL, then it is a record of pages that have already
38526 ** been played back. If the page at *pOffset has already been played back
38527 ** (if the corresponding pDone bit is set) then skip the playback.
38528 ** Make sure the pDone bit corresponding to the *pOffset page is set
38529 ** prior to returning.
38531 ** If the page record is successfully read from the (sub-)journal file
38532 ** and played back, then SQLITE_OK is returned. If an IO error occurs
38533 ** while reading the record from the (sub-)journal file or while writing
38534 ** to the database file, then the IO error code is returned. If data
38535 ** is successfully read from the (sub-)journal file but appears to be
38536 ** corrupted, SQLITE_DONE is returned. Data is considered corrupted in
38537 ** two circumstances:
38539 ** * If the record page-number is illegal (0 or PAGER_MJ_PGNO), or
38540 ** * If the record is being rolled back from the main journal file
38541 ** and the checksum field does not match the record content.
38543 ** Neither of these two scenarios are possible during a savepoint rollback.
38545 ** If this is a savepoint rollback, then memory may have to be dynamically
38546 ** allocated by this function. If this is the case and an allocation fails,
38547 ** SQLITE_NOMEM is returned.
38549 static int pager_playback_one_page(
38550 Pager *pPager, /* The pager being played back */
38551 i64 *pOffset, /* Offset of record to playback */
38552 Bitvec *pDone, /* Bitvec of pages already played back */
38553 int isMainJrnl, /* 1 -> main journal. 0 -> sub-journal. */
38554 int isSavepnt /* True for a savepoint rollback */
38556 int rc;
38557 PgHdr *pPg; /* An existing page in the cache */
38558 Pgno pgno; /* The page number of a page in journal */
38559 u32 cksum; /* Checksum used for sanity checking */
38560 char *aData; /* Temporary storage for the page */
38561 sqlite3_file *jfd; /* The file descriptor for the journal file */
38562 int isSynced; /* True if journal page is synced */
38564 assert( (isMainJrnl&~1)==0 ); /* isMainJrnl is 0 or 1 */
38565 assert( (isSavepnt&~1)==0 ); /* isSavepnt is 0 or 1 */
38566 assert( isMainJrnl || pDone ); /* pDone always used on sub-journals */
38567 assert( isSavepnt || pDone==0 ); /* pDone never used on non-savepoint */
38569 aData = pPager->pTmpSpace;
38570 assert( aData ); /* Temp storage must have already been allocated */
38571 assert( pagerUseWal(pPager)==0 || (!isMainJrnl && isSavepnt) );
38573 /* Either the state is greater than PAGER_WRITER_CACHEMOD (a transaction
38574 ** or savepoint rollback done at the request of the caller) or this is
38575 ** a hot-journal rollback. If it is a hot-journal rollback, the pager
38576 ** is in state OPEN and holds an EXCLUSIVE lock. Hot-journal rollback
38577 ** only reads from the main journal, not the sub-journal.
38579 assert( pPager->eState>=PAGER_WRITER_CACHEMOD
38580 || (pPager->eState==PAGER_OPEN && pPager->eLock==EXCLUSIVE_LOCK)
38582 assert( pPager->eState>=PAGER_WRITER_CACHEMOD || isMainJrnl );
38584 /* Read the page number and page data from the journal or sub-journal
38585 ** file. Return an error code to the caller if an IO error occurs.
38587 jfd = isMainJrnl ? pPager->jfd : pPager->sjfd;
38588 rc = read32bits(jfd, *pOffset, &pgno);
38589 if( rc!=SQLITE_OK ) return rc;
38590 rc = sqlite3OsRead(jfd, (u8*)aData, pPager->pageSize, (*pOffset)+4);
38591 if( rc!=SQLITE_OK ) return rc;
38592 *pOffset += pPager->pageSize + 4 + isMainJrnl*4;
38594 /* Sanity checking on the page. This is more important that I originally
38595 ** thought. If a power failure occurs while the journal is being written,
38596 ** it could cause invalid data to be written into the journal. We need to
38597 ** detect this invalid data (with high probability) and ignore it.
38599 if( pgno==0 || pgno==PAGER_MJ_PGNO(pPager) ){
38600 assert( !isSavepnt );
38601 return SQLITE_DONE;
38603 if( pgno>(Pgno)pPager->dbSize || sqlite3BitvecTest(pDone, pgno) ){
38604 return SQLITE_OK;
38606 if( isMainJrnl ){
38607 rc = read32bits(jfd, (*pOffset)-4, &cksum);
38608 if( rc ) return rc;
38609 if( !isSavepnt && pager_cksum(pPager, (u8*)aData)!=cksum ){
38610 return SQLITE_DONE;
38614 /* If this page has already been played by before during the current
38615 ** rollback, then don't bother to play it back again.
38617 if( pDone && (rc = sqlite3BitvecSet(pDone, pgno))!=SQLITE_OK ){
38618 return rc;
38621 /* When playing back page 1, restore the nReserve setting
38623 if( pgno==1 && pPager->nReserve!=((u8*)aData)[20] ){
38624 pPager->nReserve = ((u8*)aData)[20];
38625 pagerReportSize(pPager);
38628 /* If the pager is in CACHEMOD state, then there must be a copy of this
38629 ** page in the pager cache. In this case just update the pager cache,
38630 ** not the database file. The page is left marked dirty in this case.
38632 ** An exception to the above rule: If the database is in no-sync mode
38633 ** and a page is moved during an incremental vacuum then the page may
38634 ** not be in the pager cache. Later: if a malloc() or IO error occurs
38635 ** during a Movepage() call, then the page may not be in the cache
38636 ** either. So the condition described in the above paragraph is not
38637 ** assert()able.
38639 ** If in WRITER_DBMOD, WRITER_FINISHED or OPEN state, then we update the
38640 ** pager cache if it exists and the main file. The page is then marked
38641 ** not dirty. Since this code is only executed in PAGER_OPEN state for
38642 ** a hot-journal rollback, it is guaranteed that the page-cache is empty
38643 ** if the pager is in OPEN state.
38645 ** Ticket #1171: The statement journal might contain page content that is
38646 ** different from the page content at the start of the transaction.
38647 ** This occurs when a page is changed prior to the start of a statement
38648 ** then changed again within the statement. When rolling back such a
38649 ** statement we must not write to the original database unless we know
38650 ** for certain that original page contents are synced into the main rollback
38651 ** journal. Otherwise, a power loss might leave modified data in the
38652 ** database file without an entry in the rollback journal that can
38653 ** restore the database to its original form. Two conditions must be
38654 ** met before writing to the database files. (1) the database must be
38655 ** locked. (2) we know that the original page content is fully synced
38656 ** in the main journal either because the page is not in cache or else
38657 ** the page is marked as needSync==0.
38659 ** 2008-04-14: When attempting to vacuum a corrupt database file, it
38660 ** is possible to fail a statement on a database that does not yet exist.
38661 ** Do not attempt to write if database file has never been opened.
38663 if( pagerUseWal(pPager) ){
38664 pPg = 0;
38665 }else{
38666 pPg = pager_lookup(pPager, pgno);
38668 assert( pPg || !MEMDB );
38669 assert( pPager->eState!=PAGER_OPEN || pPg==0 );
38670 PAGERTRACE(("PLAYBACK %d page %d hash(%08x) %s\n",
38671 PAGERID(pPager), pgno, pager_datahash(pPager->pageSize, (u8*)aData),
38672 (isMainJrnl?"main-journal":"sub-journal")
38674 if( isMainJrnl ){
38675 isSynced = pPager->noSync || (*pOffset <= pPager->journalHdr);
38676 }else{
38677 isSynced = (pPg==0 || 0==(pPg->flags & PGHDR_NEED_SYNC));
38679 if( isOpen(pPager->fd)
38680 && (pPager->eState>=PAGER_WRITER_DBMOD || pPager->eState==PAGER_OPEN)
38681 && isSynced
38683 i64 ofst = (pgno-1)*(i64)pPager->pageSize;
38684 testcase( !isSavepnt && pPg!=0 && (pPg->flags&PGHDR_NEED_SYNC)!=0 );
38685 assert( !pagerUseWal(pPager) );
38686 rc = sqlite3OsWrite(pPager->fd, (u8*)aData, pPager->pageSize, ofst);
38687 if( pgno>pPager->dbFileSize ){
38688 pPager->dbFileSize = pgno;
38690 if( pPager->pBackup ){
38691 CODEC1(pPager, aData, pgno, 3, rc=SQLITE_NOMEM);
38692 sqlite3BackupUpdate(pPager->pBackup, pgno, (u8*)aData);
38693 CODEC2(pPager, aData, pgno, 7, rc=SQLITE_NOMEM, aData);
38695 }else if( !isMainJrnl && pPg==0 ){
38696 /* If this is a rollback of a savepoint and data was not written to
38697 ** the database and the page is not in-memory, there is a potential
38698 ** problem. When the page is next fetched by the b-tree layer, it
38699 ** will be read from the database file, which may or may not be
38700 ** current.
38702 ** There are a couple of different ways this can happen. All are quite
38703 ** obscure. When running in synchronous mode, this can only happen
38704 ** if the page is on the free-list at the start of the transaction, then
38705 ** populated, then moved using sqlite3PagerMovepage().
38707 ** The solution is to add an in-memory page to the cache containing
38708 ** the data just read from the sub-journal. Mark the page as dirty
38709 ** and if the pager requires a journal-sync, then mark the page as
38710 ** requiring a journal-sync before it is written.
38712 assert( isSavepnt );
38713 assert( pPager->doNotSpill==0 );
38714 pPager->doNotSpill++;
38715 rc = sqlite3PagerAcquire(pPager, pgno, &pPg, 1);
38716 assert( pPager->doNotSpill==1 );
38717 pPager->doNotSpill--;
38718 if( rc!=SQLITE_OK ) return rc;
38719 pPg->flags &= ~PGHDR_NEED_READ;
38720 sqlite3PcacheMakeDirty(pPg);
38722 if( pPg ){
38723 /* No page should ever be explicitly rolled back that is in use, except
38724 ** for page 1 which is held in use in order to keep the lock on the
38725 ** database active. However such a page may be rolled back as a result
38726 ** of an internal error resulting in an automatic call to
38727 ** sqlite3PagerRollback().
38729 void *pData;
38730 pData = pPg->pData;
38731 memcpy(pData, (u8*)aData, pPager->pageSize);
38732 pPager->xReiniter(pPg);
38733 if( isMainJrnl && (!isSavepnt || *pOffset<=pPager->journalHdr) ){
38734 /* If the contents of this page were just restored from the main
38735 ** journal file, then its content must be as they were when the
38736 ** transaction was first opened. In this case we can mark the page
38737 ** as clean, since there will be no need to write it out to the
38738 ** database.
38740 ** There is one exception to this rule. If the page is being rolled
38741 ** back as part of a savepoint (or statement) rollback from an
38742 ** unsynced portion of the main journal file, then it is not safe
38743 ** to mark the page as clean. This is because marking the page as
38744 ** clean will clear the PGHDR_NEED_SYNC flag. Since the page is
38745 ** already in the journal file (recorded in Pager.pInJournal) and
38746 ** the PGHDR_NEED_SYNC flag is cleared, if the page is written to
38747 ** again within this transaction, it will be marked as dirty but
38748 ** the PGHDR_NEED_SYNC flag will not be set. It could then potentially
38749 ** be written out into the database file before its journal file
38750 ** segment is synced. If a crash occurs during or following this,
38751 ** database corruption may ensue.
38753 assert( !pagerUseWal(pPager) );
38754 sqlite3PcacheMakeClean(pPg);
38756 pager_set_pagehash(pPg);
38758 /* If this was page 1, then restore the value of Pager.dbFileVers.
38759 ** Do this before any decoding. */
38760 if( pgno==1 ){
38761 memcpy(&pPager->dbFileVers, &((u8*)pData)[24],sizeof(pPager->dbFileVers));
38764 /* Decode the page just read from disk */
38765 CODEC1(pPager, pData, pPg->pgno, 3, rc=SQLITE_NOMEM);
38766 sqlite3PcacheRelease(pPg);
38768 return rc;
38772 ** Parameter zMaster is the name of a master journal file. A single journal
38773 ** file that referred to the master journal file has just been rolled back.
38774 ** This routine checks if it is possible to delete the master journal file,
38775 ** and does so if it is.
38777 ** Argument zMaster may point to Pager.pTmpSpace. So that buffer is not
38778 ** available for use within this function.
38780 ** When a master journal file is created, it is populated with the names
38781 ** of all of its child journals, one after another, formatted as utf-8
38782 ** encoded text. The end of each child journal file is marked with a
38783 ** nul-terminator byte (0x00). i.e. the entire contents of a master journal
38784 ** file for a transaction involving two databases might be:
38786 ** "/home/bill/a.db-journal\x00/home/bill/b.db-journal\x00"
38788 ** A master journal file may only be deleted once all of its child
38789 ** journals have been rolled back.
38791 ** This function reads the contents of the master-journal file into
38792 ** memory and loops through each of the child journal names. For
38793 ** each child journal, it checks if:
38795 ** * if the child journal exists, and if so
38796 ** * if the child journal contains a reference to master journal
38797 ** file zMaster
38799 ** If a child journal can be found that matches both of the criteria
38800 ** above, this function returns without doing anything. Otherwise, if
38801 ** no such child journal can be found, file zMaster is deleted from
38802 ** the file-system using sqlite3OsDelete().
38804 ** If an IO error within this function, an error code is returned. This
38805 ** function allocates memory by calling sqlite3Malloc(). If an allocation
38806 ** fails, SQLITE_NOMEM is returned. Otherwise, if no IO or malloc errors
38807 ** occur, SQLITE_OK is returned.
38809 ** TODO: This function allocates a single block of memory to load
38810 ** the entire contents of the master journal file. This could be
38811 ** a couple of kilobytes or so - potentially larger than the page
38812 ** size.
38814 static int pager_delmaster(Pager *pPager, const char *zMaster){
38815 sqlite3_vfs *pVfs = pPager->pVfs;
38816 int rc; /* Return code */
38817 sqlite3_file *pMaster; /* Malloc'd master-journal file descriptor */
38818 sqlite3_file *pJournal; /* Malloc'd child-journal file descriptor */
38819 char *zMasterJournal = 0; /* Contents of master journal file */
38820 i64 nMasterJournal; /* Size of master journal file */
38821 char *zJournal; /* Pointer to one journal within MJ file */
38822 char *zMasterPtr; /* Space to hold MJ filename from a journal file */
38823 int nMasterPtr; /* Amount of space allocated to zMasterPtr[] */
38825 /* Allocate space for both the pJournal and pMaster file descriptors.
38826 ** If successful, open the master journal file for reading.
38828 pMaster = (sqlite3_file *)sqlite3MallocZero(pVfs->szOsFile * 2);
38829 pJournal = (sqlite3_file *)(((u8 *)pMaster) + pVfs->szOsFile);
38830 if( !pMaster ){
38831 rc = SQLITE_NOMEM;
38832 }else{
38833 const int flags = (SQLITE_OPEN_READONLY|SQLITE_OPEN_MASTER_JOURNAL);
38834 rc = sqlite3OsOpen(pVfs, zMaster, pMaster, flags, 0);
38836 if( rc!=SQLITE_OK ) goto delmaster_out;
38838 /* Load the entire master journal file into space obtained from
38839 ** sqlite3_malloc() and pointed to by zMasterJournal. Also obtain
38840 ** sufficient space (in zMasterPtr) to hold the names of master
38841 ** journal files extracted from regular rollback-journals.
38843 rc = sqlite3OsFileSize(pMaster, &nMasterJournal);
38844 if( rc!=SQLITE_OK ) goto delmaster_out;
38845 nMasterPtr = pVfs->mxPathname+1;
38846 zMasterJournal = sqlite3Malloc((int)nMasterJournal + nMasterPtr + 1);
38847 if( !zMasterJournal ){
38848 rc = SQLITE_NOMEM;
38849 goto delmaster_out;
38851 zMasterPtr = &zMasterJournal[nMasterJournal+1];
38852 rc = sqlite3OsRead(pMaster, zMasterJournal, (int)nMasterJournal, 0);
38853 if( rc!=SQLITE_OK ) goto delmaster_out;
38854 zMasterJournal[nMasterJournal] = 0;
38856 zJournal = zMasterJournal;
38857 while( (zJournal-zMasterJournal)<nMasterJournal ){
38858 int exists;
38859 rc = sqlite3OsAccess(pVfs, zJournal, SQLITE_ACCESS_EXISTS, &exists);
38860 if( rc!=SQLITE_OK ){
38861 goto delmaster_out;
38863 if( exists ){
38864 /* One of the journals pointed to by the master journal exists.
38865 ** Open it and check if it points at the master journal. If
38866 ** so, return without deleting the master journal file.
38868 int c;
38869 int flags = (SQLITE_OPEN_READONLY|SQLITE_OPEN_MAIN_JOURNAL);
38870 rc = sqlite3OsOpen(pVfs, zJournal, pJournal, flags, 0);
38871 if( rc!=SQLITE_OK ){
38872 goto delmaster_out;
38875 rc = readMasterJournal(pJournal, zMasterPtr, nMasterPtr);
38876 sqlite3OsClose(pJournal);
38877 if( rc!=SQLITE_OK ){
38878 goto delmaster_out;
38881 c = zMasterPtr[0]!=0 && strcmp(zMasterPtr, zMaster)==0;
38882 if( c ){
38883 /* We have a match. Do not delete the master journal file. */
38884 goto delmaster_out;
38887 zJournal += (sqlite3Strlen30(zJournal)+1);
38890 sqlite3OsClose(pMaster);
38891 rc = sqlite3OsDelete(pVfs, zMaster, 0);
38893 delmaster_out:
38894 sqlite3_free(zMasterJournal);
38895 if( pMaster ){
38896 sqlite3OsClose(pMaster);
38897 assert( !isOpen(pJournal) );
38898 sqlite3_free(pMaster);
38900 return rc;
38905 ** This function is used to change the actual size of the database
38906 ** file in the file-system. This only happens when committing a transaction,
38907 ** or rolling back a transaction (including rolling back a hot-journal).
38909 ** If the main database file is not open, or the pager is not in either
38910 ** DBMOD or OPEN state, this function is a no-op. Otherwise, the size
38911 ** of the file is changed to nPage pages (nPage*pPager->pageSize bytes).
38912 ** If the file on disk is currently larger than nPage pages, then use the VFS
38913 ** xTruncate() method to truncate it.
38915 ** Or, it might might be the case that the file on disk is smaller than
38916 ** nPage pages. Some operating system implementations can get confused if
38917 ** you try to truncate a file to some size that is larger than it
38918 ** currently is, so detect this case and write a single zero byte to
38919 ** the end of the new file instead.
38921 ** If successful, return SQLITE_OK. If an IO error occurs while modifying
38922 ** the database file, return the error code to the caller.
38924 static int pager_truncate(Pager *pPager, Pgno nPage){
38925 int rc = SQLITE_OK;
38926 assert( pPager->eState!=PAGER_ERROR );
38927 assert( pPager->eState!=PAGER_READER );
38929 if( isOpen(pPager->fd)
38930 && (pPager->eState>=PAGER_WRITER_DBMOD || pPager->eState==PAGER_OPEN)
38932 i64 currentSize, newSize;
38933 int szPage = pPager->pageSize;
38934 assert( pPager->eLock==EXCLUSIVE_LOCK );
38935 /* TODO: Is it safe to use Pager.dbFileSize here? */
38936 rc = sqlite3OsFileSize(pPager->fd, &currentSize);
38937 newSize = szPage*(i64)nPage;
38938 if( rc==SQLITE_OK && currentSize!=newSize ){
38939 if( currentSize>newSize ){
38940 rc = sqlite3OsTruncate(pPager->fd, newSize);
38941 }else{
38942 char *pTmp = pPager->pTmpSpace;
38943 memset(pTmp, 0, szPage);
38944 testcase( (newSize-szPage) < currentSize );
38945 testcase( (newSize-szPage) == currentSize );
38946 testcase( (newSize-szPage) > currentSize );
38947 rc = sqlite3OsWrite(pPager->fd, pTmp, szPage, newSize-szPage);
38949 if( rc==SQLITE_OK ){
38950 pPager->dbFileSize = nPage;
38954 return rc;
38958 ** Set the value of the Pager.sectorSize variable for the given
38959 ** pager based on the value returned by the xSectorSize method
38960 ** of the open database file. The sector size will be used used
38961 ** to determine the size and alignment of journal header and
38962 ** master journal pointers within created journal files.
38964 ** For temporary files the effective sector size is always 512 bytes.
38966 ** Otherwise, for non-temporary files, the effective sector size is
38967 ** the value returned by the xSectorSize() method rounded up to 32 if
38968 ** it is less than 32, or rounded down to MAX_SECTOR_SIZE if it
38969 ** is greater than MAX_SECTOR_SIZE.
38971 static void setSectorSize(Pager *pPager){
38972 assert( isOpen(pPager->fd) || pPager->tempFile );
38974 if( !pPager->tempFile ){
38975 /* Sector size doesn't matter for temporary files. Also, the file
38976 ** may not have been opened yet, in which case the OsSectorSize()
38977 ** call will segfault.
38979 pPager->sectorSize = sqlite3OsSectorSize(pPager->fd);
38981 if( pPager->sectorSize<32 ){
38982 pPager->sectorSize = 512;
38984 if( pPager->sectorSize>MAX_SECTOR_SIZE ){
38985 assert( MAX_SECTOR_SIZE>=512 );
38986 pPager->sectorSize = MAX_SECTOR_SIZE;
38991 ** Playback the journal and thus restore the database file to
38992 ** the state it was in before we started making changes.
38994 ** The journal file format is as follows:
38996 ** (1) 8 byte prefix. A copy of aJournalMagic[].
38997 ** (2) 4 byte big-endian integer which is the number of valid page records
38998 ** in the journal. If this value is 0xffffffff, then compute the
38999 ** number of page records from the journal size.
39000 ** (3) 4 byte big-endian integer which is the initial value for the
39001 ** sanity checksum.
39002 ** (4) 4 byte integer which is the number of pages to truncate the
39003 ** database to during a rollback.
39004 ** (5) 4 byte big-endian integer which is the sector size. The header
39005 ** is this many bytes in size.
39006 ** (6) 4 byte big-endian integer which is the page size.
39007 ** (7) zero padding out to the next sector size.
39008 ** (8) Zero or more pages instances, each as follows:
39009 ** + 4 byte page number.
39010 ** + pPager->pageSize bytes of data.
39011 ** + 4 byte checksum
39013 ** When we speak of the journal header, we mean the first 7 items above.
39014 ** Each entry in the journal is an instance of the 8th item.
39016 ** Call the value from the second bullet "nRec". nRec is the number of
39017 ** valid page entries in the journal. In most cases, you can compute the
39018 ** value of nRec from the size of the journal file. But if a power
39019 ** failure occurred while the journal was being written, it could be the
39020 ** case that the size of the journal file had already been increased but
39021 ** the extra entries had not yet made it safely to disk. In such a case,
39022 ** the value of nRec computed from the file size would be too large. For
39023 ** that reason, we always use the nRec value in the header.
39025 ** If the nRec value is 0xffffffff it means that nRec should be computed
39026 ** from the file size. This value is used when the user selects the
39027 ** no-sync option for the journal. A power failure could lead to corruption
39028 ** in this case. But for things like temporary table (which will be
39029 ** deleted when the power is restored) we don't care.
39031 ** If the file opened as the journal file is not a well-formed
39032 ** journal file then all pages up to the first corrupted page are rolled
39033 ** back (or no pages if the journal header is corrupted). The journal file
39034 ** is then deleted and SQLITE_OK returned, just as if no corruption had
39035 ** been encountered.
39037 ** If an I/O or malloc() error occurs, the journal-file is not deleted
39038 ** and an error code is returned.
39040 ** The isHot parameter indicates that we are trying to rollback a journal
39041 ** that might be a hot journal. Or, it could be that the journal is
39042 ** preserved because of JOURNALMODE_PERSIST or JOURNALMODE_TRUNCATE.
39043 ** If the journal really is hot, reset the pager cache prior rolling
39044 ** back any content. If the journal is merely persistent, no reset is
39045 ** needed.
39047 static int pager_playback(Pager *pPager, int isHot){
39048 sqlite3_vfs *pVfs = pPager->pVfs;
39049 i64 szJ; /* Size of the journal file in bytes */
39050 u32 nRec; /* Number of Records in the journal */
39051 u32 u; /* Unsigned loop counter */
39052 Pgno mxPg = 0; /* Size of the original file in pages */
39053 int rc; /* Result code of a subroutine */
39054 int res = 1; /* Value returned by sqlite3OsAccess() */
39055 char *zMaster = 0; /* Name of master journal file if any */
39056 int needPagerReset; /* True to reset page prior to first page rollback */
39058 /* Figure out how many records are in the journal. Abort early if
39059 ** the journal is empty.
39061 assert( isOpen(pPager->jfd) );
39062 rc = sqlite3OsFileSize(pPager->jfd, &szJ);
39063 if( rc!=SQLITE_OK ){
39064 goto end_playback;
39067 /* Read the master journal name from the journal, if it is present.
39068 ** If a master journal file name is specified, but the file is not
39069 ** present on disk, then the journal is not hot and does not need to be
39070 ** played back.
39072 ** TODO: Technically the following is an error because it assumes that
39073 ** buffer Pager.pTmpSpace is (mxPathname+1) bytes or larger. i.e. that
39074 ** (pPager->pageSize >= pPager->pVfs->mxPathname+1). Using os_unix.c,
39075 ** mxPathname is 512, which is the same as the minimum allowable value
39076 ** for pageSize.
39078 zMaster = pPager->pTmpSpace;
39079 rc = readMasterJournal(pPager->jfd, zMaster, pPager->pVfs->mxPathname+1);
39080 if( rc==SQLITE_OK && zMaster[0] ){
39081 rc = sqlite3OsAccess(pVfs, zMaster, SQLITE_ACCESS_EXISTS, &res);
39083 zMaster = 0;
39084 if( rc!=SQLITE_OK || !res ){
39085 goto end_playback;
39087 pPager->journalOff = 0;
39088 needPagerReset = isHot;
39090 /* This loop terminates either when a readJournalHdr() or
39091 ** pager_playback_one_page() call returns SQLITE_DONE or an IO error
39092 ** occurs.
39094 while( 1 ){
39095 /* Read the next journal header from the journal file. If there are
39096 ** not enough bytes left in the journal file for a complete header, or
39097 ** it is corrupted, then a process must have failed while writing it.
39098 ** This indicates nothing more needs to be rolled back.
39100 rc = readJournalHdr(pPager, isHot, szJ, &nRec, &mxPg);
39101 if( rc!=SQLITE_OK ){
39102 if( rc==SQLITE_DONE ){
39103 rc = SQLITE_OK;
39105 goto end_playback;
39108 /* If nRec is 0xffffffff, then this journal was created by a process
39109 ** working in no-sync mode. This means that the rest of the journal
39110 ** file consists of pages, there are no more journal headers. Compute
39111 ** the value of nRec based on this assumption.
39113 if( nRec==0xffffffff ){
39114 assert( pPager->journalOff==JOURNAL_HDR_SZ(pPager) );
39115 nRec = (int)((szJ - JOURNAL_HDR_SZ(pPager))/JOURNAL_PG_SZ(pPager));
39118 /* If nRec is 0 and this rollback is of a transaction created by this
39119 ** process and if this is the final header in the journal, then it means
39120 ** that this part of the journal was being filled but has not yet been
39121 ** synced to disk. Compute the number of pages based on the remaining
39122 ** size of the file.
39124 ** The third term of the test was added to fix ticket #2565.
39125 ** When rolling back a hot journal, nRec==0 always means that the next
39126 ** chunk of the journal contains zero pages to be rolled back. But
39127 ** when doing a ROLLBACK and the nRec==0 chunk is the last chunk in
39128 ** the journal, it means that the journal might contain additional
39129 ** pages that need to be rolled back and that the number of pages
39130 ** should be computed based on the journal file size.
39132 if( nRec==0 && !isHot &&
39133 pPager->journalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff ){
39134 nRec = (int)((szJ - pPager->journalOff) / JOURNAL_PG_SZ(pPager));
39137 /* If this is the first header read from the journal, truncate the
39138 ** database file back to its original size.
39140 if( pPager->journalOff==JOURNAL_HDR_SZ(pPager) ){
39141 rc = pager_truncate(pPager, mxPg);
39142 if( rc!=SQLITE_OK ){
39143 goto end_playback;
39145 pPager->dbSize = mxPg;
39148 /* Copy original pages out of the journal and back into the
39149 ** database file and/or page cache.
39151 for(u=0; u<nRec; u++){
39152 if( needPagerReset ){
39153 pager_reset(pPager);
39154 needPagerReset = 0;
39156 rc = pager_playback_one_page(pPager,&pPager->journalOff,0,1,0);
39157 if( rc!=SQLITE_OK ){
39158 if( rc==SQLITE_DONE ){
39159 rc = SQLITE_OK;
39160 pPager->journalOff = szJ;
39161 break;
39162 }else if( rc==SQLITE_IOERR_SHORT_READ ){
39163 /* If the journal has been truncated, simply stop reading and
39164 ** processing the journal. This might happen if the journal was
39165 ** not completely written and synced prior to a crash. In that
39166 ** case, the database should have never been written in the
39167 ** first place so it is OK to simply abandon the rollback. */
39168 rc = SQLITE_OK;
39169 goto end_playback;
39170 }else{
39171 /* If we are unable to rollback, quit and return the error
39172 ** code. This will cause the pager to enter the error state
39173 ** so that no further harm will be done. Perhaps the next
39174 ** process to come along will be able to rollback the database.
39176 goto end_playback;
39181 /*NOTREACHED*/
39182 assert( 0 );
39184 end_playback:
39185 /* Following a rollback, the database file should be back in its original
39186 ** state prior to the start of the transaction, so invoke the
39187 ** SQLITE_FCNTL_DB_UNCHANGED file-control method to disable the
39188 ** assertion that the transaction counter was modified.
39190 assert(
39191 pPager->fd->pMethods==0 ||
39192 sqlite3OsFileControl(pPager->fd,SQLITE_FCNTL_DB_UNCHANGED,0)>=SQLITE_OK
39195 /* If this playback is happening automatically as a result of an IO or
39196 ** malloc error that occurred after the change-counter was updated but
39197 ** before the transaction was committed, then the change-counter
39198 ** modification may just have been reverted. If this happens in exclusive
39199 ** mode, then subsequent transactions performed by the connection will not
39200 ** update the change-counter at all. This may lead to cache inconsistency
39201 ** problems for other processes at some point in the future. So, just
39202 ** in case this has happened, clear the changeCountDone flag now.
39204 pPager->changeCountDone = pPager->tempFile;
39206 if( rc==SQLITE_OK ){
39207 zMaster = pPager->pTmpSpace;
39208 rc = readMasterJournal(pPager->jfd, zMaster, pPager->pVfs->mxPathname+1);
39209 testcase( rc!=SQLITE_OK );
39211 if( rc==SQLITE_OK
39212 && (pPager->eState>=PAGER_WRITER_DBMOD || pPager->eState==PAGER_OPEN)
39214 rc = sqlite3PagerSync(pPager);
39216 if( rc==SQLITE_OK ){
39217 rc = pager_end_transaction(pPager, zMaster[0]!='\0');
39218 testcase( rc!=SQLITE_OK );
39220 if( rc==SQLITE_OK && zMaster[0] && res ){
39221 /* If there was a master journal and this routine will return success,
39222 ** see if it is possible to delete the master journal.
39224 rc = pager_delmaster(pPager, zMaster);
39225 testcase( rc!=SQLITE_OK );
39228 /* The Pager.sectorSize variable may have been updated while rolling
39229 ** back a journal created by a process with a different sector size
39230 ** value. Reset it to the correct value for this process.
39232 setSectorSize(pPager);
39233 return rc;
39238 ** Read the content for page pPg out of the database file and into
39239 ** pPg->pData. A shared lock or greater must be held on the database
39240 ** file before this function is called.
39242 ** If page 1 is read, then the value of Pager.dbFileVers[] is set to
39243 ** the value read from the database file.
39245 ** If an IO error occurs, then the IO error is returned to the caller.
39246 ** Otherwise, SQLITE_OK is returned.
39248 static int readDbPage(PgHdr *pPg){
39249 Pager *pPager = pPg->pPager; /* Pager object associated with page pPg */
39250 Pgno pgno = pPg->pgno; /* Page number to read */
39251 int rc = SQLITE_OK; /* Return code */
39252 int isInWal = 0; /* True if page is in log file */
39253 int pgsz = pPager->pageSize; /* Number of bytes to read */
39255 assert( pPager->eState>=PAGER_READER && !MEMDB );
39256 assert( isOpen(pPager->fd) );
39258 if( NEVER(!isOpen(pPager->fd)) ){
39259 assert( pPager->tempFile );
39260 memset(pPg->pData, 0, pPager->pageSize);
39261 return SQLITE_OK;
39264 if( pagerUseWal(pPager) ){
39265 /* Try to pull the page from the write-ahead log. */
39266 rc = sqlite3WalRead(pPager->pWal, pgno, &isInWal, pgsz, pPg->pData);
39268 if( rc==SQLITE_OK && !isInWal ){
39269 i64 iOffset = (pgno-1)*(i64)pPager->pageSize;
39270 rc = sqlite3OsRead(pPager->fd, pPg->pData, pgsz, iOffset);
39271 if( rc==SQLITE_IOERR_SHORT_READ ){
39272 rc = SQLITE_OK;
39276 if( pgno==1 ){
39277 if( rc ){
39278 /* If the read is unsuccessful, set the dbFileVers[] to something
39279 ** that will never be a valid file version. dbFileVers[] is a copy
39280 ** of bytes 24..39 of the database. Bytes 28..31 should always be
39281 ** zero or the size of the database in page. Bytes 32..35 and 35..39
39282 ** should be page numbers which are never 0xffffffff. So filling
39283 ** pPager->dbFileVers[] with all 0xff bytes should suffice.
39285 ** For an encrypted database, the situation is more complex: bytes
39286 ** 24..39 of the database are white noise. But the probability of
39287 ** white noising equaling 16 bytes of 0xff is vanishingly small so
39288 ** we should still be ok.
39290 memset(pPager->dbFileVers, 0xff, sizeof(pPager->dbFileVers));
39291 }else{
39292 u8 *dbFileVers = &((u8*)pPg->pData)[24];
39293 memcpy(&pPager->dbFileVers, dbFileVers, sizeof(pPager->dbFileVers));
39296 CODEC1(pPager, pPg->pData, pgno, 3, rc = SQLITE_NOMEM);
39298 PAGER_INCR(sqlite3_pager_readdb_count);
39299 PAGER_INCR(pPager->nRead);
39300 IOTRACE(("PGIN %p %d\n", pPager, pgno));
39301 PAGERTRACE(("FETCH %d page %d hash(%08x)\n",
39302 PAGERID(pPager), pgno, pager_pagehash(pPg)));
39304 return rc;
39308 ** Update the value of the change-counter at offsets 24 and 92 in
39309 ** the header and the sqlite version number at offset 96.
39311 ** This is an unconditional update. See also the pager_incr_changecounter()
39312 ** routine which only updates the change-counter if the update is actually
39313 ** needed, as determined by the pPager->changeCountDone state variable.
39315 static void pager_write_changecounter(PgHdr *pPg){
39316 u32 change_counter;
39318 /* Increment the value just read and write it back to byte 24. */
39319 change_counter = sqlite3Get4byte((u8*)pPg->pPager->dbFileVers)+1;
39320 put32bits(((char*)pPg->pData)+24, change_counter);
39322 /* Also store the SQLite version number in bytes 96..99 and in
39323 ** bytes 92..95 store the change counter for which the version number
39324 ** is valid. */
39325 put32bits(((char*)pPg->pData)+92, change_counter);
39326 put32bits(((char*)pPg->pData)+96, SQLITE_VERSION_NUMBER);
39329 #ifndef SQLITE_OMIT_WAL
39331 ** This function is invoked once for each page that has already been
39332 ** written into the log file when a WAL transaction is rolled back.
39333 ** Parameter iPg is the page number of said page. The pCtx argument
39334 ** is actually a pointer to the Pager structure.
39336 ** If page iPg is present in the cache, and has no outstanding references,
39337 ** it is discarded. Otherwise, if there are one or more outstanding
39338 ** references, the page content is reloaded from the database. If the
39339 ** attempt to reload content from the database is required and fails,
39340 ** return an SQLite error code. Otherwise, SQLITE_OK.
39342 static int pagerUndoCallback(void *pCtx, Pgno iPg){
39343 int rc = SQLITE_OK;
39344 Pager *pPager = (Pager *)pCtx;
39345 PgHdr *pPg;
39347 pPg = sqlite3PagerLookup(pPager, iPg);
39348 if( pPg ){
39349 if( sqlite3PcachePageRefcount(pPg)==1 ){
39350 sqlite3PcacheDrop(pPg);
39351 }else{
39352 rc = readDbPage(pPg);
39353 if( rc==SQLITE_OK ){
39354 pPager->xReiniter(pPg);
39356 sqlite3PagerUnref(pPg);
39360 /* Normally, if a transaction is rolled back, any backup processes are
39361 ** updated as data is copied out of the rollback journal and into the
39362 ** database. This is not generally possible with a WAL database, as
39363 ** rollback involves simply truncating the log file. Therefore, if one
39364 ** or more frames have already been written to the log (and therefore
39365 ** also copied into the backup databases) as part of this transaction,
39366 ** the backups must be restarted.
39368 sqlite3BackupRestart(pPager->pBackup);
39370 return rc;
39374 ** This function is called to rollback a transaction on a WAL database.
39376 static int pagerRollbackWal(Pager *pPager){
39377 int rc; /* Return Code */
39378 PgHdr *pList; /* List of dirty pages to revert */
39380 /* For all pages in the cache that are currently dirty or have already
39381 ** been written (but not committed) to the log file, do one of the
39382 ** following:
39384 ** + Discard the cached page (if refcount==0), or
39385 ** + Reload page content from the database (if refcount>0).
39387 pPager->dbSize = pPager->dbOrigSize;
39388 rc = sqlite3WalUndo(pPager->pWal, pagerUndoCallback, (void *)pPager);
39389 pList = sqlite3PcacheDirtyList(pPager->pPCache);
39390 while( pList && rc==SQLITE_OK ){
39391 PgHdr *pNext = pList->pDirty;
39392 rc = pagerUndoCallback((void *)pPager, pList->pgno);
39393 pList = pNext;
39396 return rc;
39400 ** This function is a wrapper around sqlite3WalFrames(). As well as logging
39401 ** the contents of the list of pages headed by pList (connected by pDirty),
39402 ** this function notifies any active backup processes that the pages have
39403 ** changed.
39405 ** The list of pages passed into this routine is always sorted by page number.
39406 ** Hence, if page 1 appears anywhere on the list, it will be the first page.
39408 static int pagerWalFrames(
39409 Pager *pPager, /* Pager object */
39410 PgHdr *pList, /* List of frames to log */
39411 Pgno nTruncate, /* Database size after this commit */
39412 int isCommit, /* True if this is a commit */
39413 int syncFlags /* Flags to pass to OsSync() (or 0) */
39415 int rc; /* Return code */
39416 #if defined(SQLITE_DEBUG) || defined(SQLITE_CHECK_PAGES)
39417 PgHdr *p; /* For looping over pages */
39418 #endif
39420 assert( pPager->pWal );
39421 #ifdef SQLITE_DEBUG
39422 /* Verify that the page list is in accending order */
39423 for(p=pList; p && p->pDirty; p=p->pDirty){
39424 assert( p->pgno < p->pDirty->pgno );
39426 #endif
39428 if( isCommit ){
39429 /* If a WAL transaction is being committed, there is no point in writing
39430 ** any pages with page numbers greater than nTruncate into the WAL file.
39431 ** They will never be read by any client. So remove them from the pDirty
39432 ** list here. */
39433 PgHdr *p;
39434 PgHdr **ppNext = &pList;
39435 for(p=pList; (*ppNext = p); p=p->pDirty){
39436 if( p->pgno<=nTruncate ) ppNext = &p->pDirty;
39438 assert( pList );
39441 if( pList->pgno==1 ) pager_write_changecounter(pList);
39442 rc = sqlite3WalFrames(pPager->pWal,
39443 pPager->pageSize, pList, nTruncate, isCommit, syncFlags
39445 if( rc==SQLITE_OK && pPager->pBackup ){
39446 PgHdr *p;
39447 for(p=pList; p; p=p->pDirty){
39448 sqlite3BackupUpdate(pPager->pBackup, p->pgno, (u8 *)p->pData);
39452 #ifdef SQLITE_CHECK_PAGES
39453 pList = sqlite3PcacheDirtyList(pPager->pPCache);
39454 for(p=pList; p; p=p->pDirty){
39455 pager_set_pagehash(p);
39457 #endif
39459 return rc;
39463 ** Begin a read transaction on the WAL.
39465 ** This routine used to be called "pagerOpenSnapshot()" because it essentially
39466 ** makes a snapshot of the database at the current point in time and preserves
39467 ** that snapshot for use by the reader in spite of concurrently changes by
39468 ** other writers or checkpointers.
39470 static int pagerBeginReadTransaction(Pager *pPager){
39471 int rc; /* Return code */
39472 int changed = 0; /* True if cache must be reset */
39474 assert( pagerUseWal(pPager) );
39475 assert( pPager->eState==PAGER_OPEN || pPager->eState==PAGER_READER );
39477 /* sqlite3WalEndReadTransaction() was not called for the previous
39478 ** transaction in locking_mode=EXCLUSIVE. So call it now. If we
39479 ** are in locking_mode=NORMAL and EndRead() was previously called,
39480 ** the duplicate call is harmless.
39482 sqlite3WalEndReadTransaction(pPager->pWal);
39484 rc = sqlite3WalBeginReadTransaction(pPager->pWal, &changed);
39485 if( rc!=SQLITE_OK || changed ){
39486 pager_reset(pPager);
39489 return rc;
39491 #endif
39494 ** This function is called as part of the transition from PAGER_OPEN
39495 ** to PAGER_READER state to determine the size of the database file
39496 ** in pages (assuming the page size currently stored in Pager.pageSize).
39498 ** If no error occurs, SQLITE_OK is returned and the size of the database
39499 ** in pages is stored in *pnPage. Otherwise, an error code (perhaps
39500 ** SQLITE_IOERR_FSTAT) is returned and *pnPage is left unmodified.
39502 static int pagerPagecount(Pager *pPager, Pgno *pnPage){
39503 Pgno nPage; /* Value to return via *pnPage */
39505 /* Query the WAL sub-system for the database size. The WalDbsize()
39506 ** function returns zero if the WAL is not open (i.e. Pager.pWal==0), or
39507 ** if the database size is not available. The database size is not
39508 ** available from the WAL sub-system if the log file is empty or
39509 ** contains no valid committed transactions.
39511 assert( pPager->eState==PAGER_OPEN );
39512 assert( pPager->eLock>=SHARED_LOCK || pPager->noReadlock );
39513 nPage = sqlite3WalDbsize(pPager->pWal);
39515 /* If the database size was not available from the WAL sub-system,
39516 ** determine it based on the size of the database file. If the size
39517 ** of the database file is not an integer multiple of the page-size,
39518 ** round down to the nearest page. Except, any file larger than 0
39519 ** bytes in size is considered to contain at least one page.
39521 if( nPage==0 ){
39522 i64 n = 0; /* Size of db file in bytes */
39523 assert( isOpen(pPager->fd) || pPager->tempFile );
39524 if( isOpen(pPager->fd) ){
39525 int rc = sqlite3OsFileSize(pPager->fd, &n);
39526 if( rc!=SQLITE_OK ){
39527 return rc;
39530 nPage = (Pgno)(n / pPager->pageSize);
39531 if( nPage==0 && n>0 ){
39532 nPage = 1;
39536 /* If the current number of pages in the file is greater than the
39537 ** configured maximum pager number, increase the allowed limit so
39538 ** that the file can be read.
39540 if( nPage>pPager->mxPgno ){
39541 pPager->mxPgno = (Pgno)nPage;
39544 *pnPage = nPage;
39545 return SQLITE_OK;
39548 #ifndef SQLITE_OMIT_WAL
39550 ** Check if the *-wal file that corresponds to the database opened by pPager
39551 ** exists if the database is not empy, or verify that the *-wal file does
39552 ** not exist (by deleting it) if the database file is empty.
39554 ** If the database is not empty and the *-wal file exists, open the pager
39555 ** in WAL mode. If the database is empty or if no *-wal file exists and
39556 ** if no error occurs, make sure Pager.journalMode is not set to
39557 ** PAGER_JOURNALMODE_WAL.
39559 ** Return SQLITE_OK or an error code.
39561 ** The caller must hold a SHARED lock on the database file to call this
39562 ** function. Because an EXCLUSIVE lock on the db file is required to delete
39563 ** a WAL on a none-empty database, this ensures there is no race condition
39564 ** between the xAccess() below and an xDelete() being executed by some
39565 ** other connection.
39567 static int pagerOpenWalIfPresent(Pager *pPager){
39568 int rc = SQLITE_OK;
39569 assert( pPager->eState==PAGER_OPEN );
39570 assert( pPager->eLock>=SHARED_LOCK || pPager->noReadlock );
39572 if( !pPager->tempFile ){
39573 int isWal; /* True if WAL file exists */
39574 Pgno nPage; /* Size of the database file */
39576 rc = pagerPagecount(pPager, &nPage);
39577 if( rc ) return rc;
39578 if( nPage==0 ){
39579 rc = sqlite3OsDelete(pPager->pVfs, pPager->zWal, 0);
39580 isWal = 0;
39581 }else{
39582 rc = sqlite3OsAccess(
39583 pPager->pVfs, pPager->zWal, SQLITE_ACCESS_EXISTS, &isWal
39586 if( rc==SQLITE_OK ){
39587 if( isWal ){
39588 testcase( sqlite3PcachePagecount(pPager->pPCache)==0 );
39589 rc = sqlite3PagerOpenWal(pPager, 0);
39590 }else if( pPager->journalMode==PAGER_JOURNALMODE_WAL ){
39591 pPager->journalMode = PAGER_JOURNALMODE_DELETE;
39595 return rc;
39597 #endif
39600 ** Playback savepoint pSavepoint. Or, if pSavepoint==NULL, then playback
39601 ** the entire master journal file. The case pSavepoint==NULL occurs when
39602 ** a ROLLBACK TO command is invoked on a SAVEPOINT that is a transaction
39603 ** savepoint.
39605 ** When pSavepoint is not NULL (meaning a non-transaction savepoint is
39606 ** being rolled back), then the rollback consists of up to three stages,
39607 ** performed in the order specified:
39609 ** * Pages are played back from the main journal starting at byte
39610 ** offset PagerSavepoint.iOffset and continuing to
39611 ** PagerSavepoint.iHdrOffset, or to the end of the main journal
39612 ** file if PagerSavepoint.iHdrOffset is zero.
39614 ** * If PagerSavepoint.iHdrOffset is not zero, then pages are played
39615 ** back starting from the journal header immediately following
39616 ** PagerSavepoint.iHdrOffset to the end of the main journal file.
39618 ** * Pages are then played back from the sub-journal file, starting
39619 ** with the PagerSavepoint.iSubRec and continuing to the end of
39620 ** the journal file.
39622 ** Throughout the rollback process, each time a page is rolled back, the
39623 ** corresponding bit is set in a bitvec structure (variable pDone in the
39624 ** implementation below). This is used to ensure that a page is only
39625 ** rolled back the first time it is encountered in either journal.
39627 ** If pSavepoint is NULL, then pages are only played back from the main
39628 ** journal file. There is no need for a bitvec in this case.
39630 ** In either case, before playback commences the Pager.dbSize variable
39631 ** is reset to the value that it held at the start of the savepoint
39632 ** (or transaction). No page with a page-number greater than this value
39633 ** is played back. If one is encountered it is simply skipped.
39635 static int pagerPlaybackSavepoint(Pager *pPager, PagerSavepoint *pSavepoint){
39636 i64 szJ; /* Effective size of the main journal */
39637 i64 iHdrOff; /* End of first segment of main-journal records */
39638 int rc = SQLITE_OK; /* Return code */
39639 Bitvec *pDone = 0; /* Bitvec to ensure pages played back only once */
39641 assert( pPager->eState!=PAGER_ERROR );
39642 assert( pPager->eState>=PAGER_WRITER_LOCKED );
39644 /* Allocate a bitvec to use to store the set of pages rolled back */
39645 if( pSavepoint ){
39646 pDone = sqlite3BitvecCreate(pSavepoint->nOrig);
39647 if( !pDone ){
39648 return SQLITE_NOMEM;
39652 /* Set the database size back to the value it was before the savepoint
39653 ** being reverted was opened.
39655 pPager->dbSize = pSavepoint ? pSavepoint->nOrig : pPager->dbOrigSize;
39656 pPager->changeCountDone = pPager->tempFile;
39658 if( !pSavepoint && pagerUseWal(pPager) ){
39659 return pagerRollbackWal(pPager);
39662 /* Use pPager->journalOff as the effective size of the main rollback
39663 ** journal. The actual file might be larger than this in
39664 ** PAGER_JOURNALMODE_TRUNCATE or PAGER_JOURNALMODE_PERSIST. But anything
39665 ** past pPager->journalOff is off-limits to us.
39667 szJ = pPager->journalOff;
39668 assert( pagerUseWal(pPager)==0 || szJ==0 );
39670 /* Begin by rolling back records from the main journal starting at
39671 ** PagerSavepoint.iOffset and continuing to the next journal header.
39672 ** There might be records in the main journal that have a page number
39673 ** greater than the current database size (pPager->dbSize) but those
39674 ** will be skipped automatically. Pages are added to pDone as they
39675 ** are played back.
39677 if( pSavepoint && !pagerUseWal(pPager) ){
39678 iHdrOff = pSavepoint->iHdrOffset ? pSavepoint->iHdrOffset : szJ;
39679 pPager->journalOff = pSavepoint->iOffset;
39680 while( rc==SQLITE_OK && pPager->journalOff<iHdrOff ){
39681 rc = pager_playback_one_page(pPager, &pPager->journalOff, pDone, 1, 1);
39683 assert( rc!=SQLITE_DONE );
39684 }else{
39685 pPager->journalOff = 0;
39688 /* Continue rolling back records out of the main journal starting at
39689 ** the first journal header seen and continuing until the effective end
39690 ** of the main journal file. Continue to skip out-of-range pages and
39691 ** continue adding pages rolled back to pDone.
39693 while( rc==SQLITE_OK && pPager->journalOff<szJ ){
39694 u32 ii; /* Loop counter */
39695 u32 nJRec = 0; /* Number of Journal Records */
39696 u32 dummy;
39697 rc = readJournalHdr(pPager, 0, szJ, &nJRec, &dummy);
39698 assert( rc!=SQLITE_DONE );
39701 ** The "pPager->journalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff"
39702 ** test is related to ticket #2565. See the discussion in the
39703 ** pager_playback() function for additional information.
39705 if( nJRec==0
39706 && pPager->journalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff
39708 nJRec = (u32)((szJ - pPager->journalOff)/JOURNAL_PG_SZ(pPager));
39710 for(ii=0; rc==SQLITE_OK && ii<nJRec && pPager->journalOff<szJ; ii++){
39711 rc = pager_playback_one_page(pPager, &pPager->journalOff, pDone, 1, 1);
39713 assert( rc!=SQLITE_DONE );
39715 assert( rc!=SQLITE_OK || pPager->journalOff>=szJ );
39717 /* Finally, rollback pages from the sub-journal. Page that were
39718 ** previously rolled back out of the main journal (and are hence in pDone)
39719 ** will be skipped. Out-of-range pages are also skipped.
39721 if( pSavepoint ){
39722 u32 ii; /* Loop counter */
39723 i64 offset = pSavepoint->iSubRec*(4+pPager->pageSize);
39725 if( pagerUseWal(pPager) ){
39726 rc = sqlite3WalSavepointUndo(pPager->pWal, pSavepoint->aWalData);
39728 for(ii=pSavepoint->iSubRec; rc==SQLITE_OK && ii<pPager->nSubRec; ii++){
39729 assert( offset==ii*(4+pPager->pageSize) );
39730 rc = pager_playback_one_page(pPager, &offset, pDone, 0, 1);
39732 assert( rc!=SQLITE_DONE );
39735 sqlite3BitvecDestroy(pDone);
39736 if( rc==SQLITE_OK ){
39737 pPager->journalOff = szJ;
39740 return rc;
39744 ** Change the maximum number of in-memory pages that are allowed.
39746 SQLITE_PRIVATE void sqlite3PagerSetCachesize(Pager *pPager, int mxPage){
39747 sqlite3PcacheSetCachesize(pPager->pPCache, mxPage);
39751 ** Adjust the robustness of the database to damage due to OS crashes
39752 ** or power failures by changing the number of syncs()s when writing
39753 ** the rollback journal. There are three levels:
39755 ** OFF sqlite3OsSync() is never called. This is the default
39756 ** for temporary and transient files.
39758 ** NORMAL The journal is synced once before writes begin on the
39759 ** database. This is normally adequate protection, but
39760 ** it is theoretically possible, though very unlikely,
39761 ** that an inopertune power failure could leave the journal
39762 ** in a state which would cause damage to the database
39763 ** when it is rolled back.
39765 ** FULL The journal is synced twice before writes begin on the
39766 ** database (with some additional information - the nRec field
39767 ** of the journal header - being written in between the two
39768 ** syncs). If we assume that writing a
39769 ** single disk sector is atomic, then this mode provides
39770 ** assurance that the journal will not be corrupted to the
39771 ** point of causing damage to the database during rollback.
39773 ** The above is for a rollback-journal mode. For WAL mode, OFF continues
39774 ** to mean that no syncs ever occur. NORMAL means that the WAL is synced
39775 ** prior to the start of checkpoint and that the database file is synced
39776 ** at the conclusion of the checkpoint if the entire content of the WAL
39777 ** was written back into the database. But no sync operations occur for
39778 ** an ordinary commit in NORMAL mode with WAL. FULL means that the WAL
39779 ** file is synced following each commit operation, in addition to the
39780 ** syncs associated with NORMAL.
39782 ** Do not confuse synchronous=FULL with SQLITE_SYNC_FULL. The
39783 ** SQLITE_SYNC_FULL macro means to use the MacOSX-style full-fsync
39784 ** using fcntl(F_FULLFSYNC). SQLITE_SYNC_NORMAL means to do an
39785 ** ordinary fsync() call. There is no difference between SQLITE_SYNC_FULL
39786 ** and SQLITE_SYNC_NORMAL on platforms other than MacOSX. But the
39787 ** synchronous=FULL versus synchronous=NORMAL setting determines when
39788 ** the xSync primitive is called and is relevant to all platforms.
39790 ** Numeric values associated with these states are OFF==1, NORMAL=2,
39791 ** and FULL=3.
39793 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
39794 SQLITE_PRIVATE void sqlite3PagerSetSafetyLevel(
39795 Pager *pPager, /* The pager to set safety level for */
39796 int level, /* PRAGMA synchronous. 1=OFF, 2=NORMAL, 3=FULL */
39797 int bFullFsync, /* PRAGMA fullfsync */
39798 int bCkptFullFsync /* PRAGMA checkpoint_fullfsync */
39800 assert( level>=1 && level<=3 );
39801 pPager->noSync = (level==1 || pPager->tempFile) ?1:0;
39802 pPager->fullSync = (level==3 && !pPager->tempFile) ?1:0;
39803 if( pPager->noSync ){
39804 pPager->syncFlags = 0;
39805 pPager->ckptSyncFlags = 0;
39806 }else if( bFullFsync ){
39807 pPager->syncFlags = SQLITE_SYNC_FULL;
39808 pPager->ckptSyncFlags = SQLITE_SYNC_FULL;
39809 }else if( bCkptFullFsync ){
39810 pPager->syncFlags = SQLITE_SYNC_NORMAL;
39811 pPager->ckptSyncFlags = SQLITE_SYNC_FULL;
39812 }else{
39813 pPager->syncFlags = SQLITE_SYNC_NORMAL;
39814 pPager->ckptSyncFlags = SQLITE_SYNC_NORMAL;
39817 #endif
39820 ** The following global variable is incremented whenever the library
39821 ** attempts to open a temporary file. This information is used for
39822 ** testing and analysis only.
39824 #ifdef SQLITE_TEST
39825 SQLITE_API int sqlite3_opentemp_count = 0;
39826 #endif
39829 ** Open a temporary file.
39831 ** Write the file descriptor into *pFile. Return SQLITE_OK on success
39832 ** or some other error code if we fail. The OS will automatically
39833 ** delete the temporary file when it is closed.
39835 ** The flags passed to the VFS layer xOpen() call are those specified
39836 ** by parameter vfsFlags ORed with the following:
39838 ** SQLITE_OPEN_READWRITE
39839 ** SQLITE_OPEN_CREATE
39840 ** SQLITE_OPEN_EXCLUSIVE
39841 ** SQLITE_OPEN_DELETEONCLOSE
39843 static int pagerOpentemp(
39844 Pager *pPager, /* The pager object */
39845 sqlite3_file *pFile, /* Write the file descriptor here */
39846 int vfsFlags /* Flags passed through to the VFS */
39848 int rc; /* Return code */
39850 #ifdef SQLITE_TEST
39851 sqlite3_opentemp_count++; /* Used for testing and analysis only */
39852 #endif
39854 vfsFlags |= SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE |
39855 SQLITE_OPEN_EXCLUSIVE | SQLITE_OPEN_DELETEONCLOSE;
39856 rc = sqlite3OsOpen(pPager->pVfs, 0, pFile, vfsFlags, 0);
39857 assert( rc!=SQLITE_OK || isOpen(pFile) );
39858 return rc;
39862 ** Set the busy handler function.
39864 ** The pager invokes the busy-handler if sqlite3OsLock() returns
39865 ** SQLITE_BUSY when trying to upgrade from no-lock to a SHARED lock,
39866 ** or when trying to upgrade from a RESERVED lock to an EXCLUSIVE
39867 ** lock. It does *not* invoke the busy handler when upgrading from
39868 ** SHARED to RESERVED, or when upgrading from SHARED to EXCLUSIVE
39869 ** (which occurs during hot-journal rollback). Summary:
39871 ** Transition | Invokes xBusyHandler
39872 ** --------------------------------------------------------
39873 ** NO_LOCK -> SHARED_LOCK | Yes
39874 ** SHARED_LOCK -> RESERVED_LOCK | No
39875 ** SHARED_LOCK -> EXCLUSIVE_LOCK | No
39876 ** RESERVED_LOCK -> EXCLUSIVE_LOCK | Yes
39878 ** If the busy-handler callback returns non-zero, the lock is
39879 ** retried. If it returns zero, then the SQLITE_BUSY error is
39880 ** returned to the caller of the pager API function.
39882 SQLITE_PRIVATE void sqlite3PagerSetBusyhandler(
39883 Pager *pPager, /* Pager object */
39884 int (*xBusyHandler)(void *), /* Pointer to busy-handler function */
39885 void *pBusyHandlerArg /* Argument to pass to xBusyHandler */
39887 pPager->xBusyHandler = xBusyHandler;
39888 pPager->pBusyHandlerArg = pBusyHandlerArg;
39892 ** Change the page size used by the Pager object. The new page size
39893 ** is passed in *pPageSize.
39895 ** If the pager is in the error state when this function is called, it
39896 ** is a no-op. The value returned is the error state error code (i.e.
39897 ** one of SQLITE_IOERR, an SQLITE_IOERR_xxx sub-code or SQLITE_FULL).
39899 ** Otherwise, if all of the following are true:
39901 ** * the new page size (value of *pPageSize) is valid (a power
39902 ** of two between 512 and SQLITE_MAX_PAGE_SIZE, inclusive), and
39904 ** * there are no outstanding page references, and
39906 ** * the database is either not an in-memory database or it is
39907 ** an in-memory database that currently consists of zero pages.
39909 ** then the pager object page size is set to *pPageSize.
39911 ** If the page size is changed, then this function uses sqlite3PagerMalloc()
39912 ** to obtain a new Pager.pTmpSpace buffer. If this allocation attempt
39913 ** fails, SQLITE_NOMEM is returned and the page size remains unchanged.
39914 ** In all other cases, SQLITE_OK is returned.
39916 ** If the page size is not changed, either because one of the enumerated
39917 ** conditions above is not true, the pager was in error state when this
39918 ** function was called, or because the memory allocation attempt failed,
39919 ** then *pPageSize is set to the old, retained page size before returning.
39921 SQLITE_PRIVATE int sqlite3PagerSetPagesize(Pager *pPager, u32 *pPageSize, int nReserve){
39922 int rc = SQLITE_OK;
39924 /* It is not possible to do a full assert_pager_state() here, as this
39925 ** function may be called from within PagerOpen(), before the state
39926 ** of the Pager object is internally consistent.
39928 ** At one point this function returned an error if the pager was in
39929 ** PAGER_ERROR state. But since PAGER_ERROR state guarantees that
39930 ** there is at least one outstanding page reference, this function
39931 ** is a no-op for that case anyhow.
39934 u32 pageSize = *pPageSize;
39935 assert( pageSize==0 || (pageSize>=512 && pageSize<=SQLITE_MAX_PAGE_SIZE) );
39936 if( (pPager->memDb==0 || pPager->dbSize==0)
39937 && sqlite3PcacheRefCount(pPager->pPCache)==0
39938 && pageSize && pageSize!=(u32)pPager->pageSize
39940 char *pNew = NULL; /* New temp space */
39941 i64 nByte = 0;
39943 if( pPager->eState>PAGER_OPEN && isOpen(pPager->fd) ){
39944 rc = sqlite3OsFileSize(pPager->fd, &nByte);
39946 if( rc==SQLITE_OK ){
39947 pNew = (char *)sqlite3PageMalloc(pageSize);
39948 if( !pNew ) rc = SQLITE_NOMEM;
39951 if( rc==SQLITE_OK ){
39952 pager_reset(pPager);
39953 pPager->dbSize = (Pgno)(nByte/pageSize);
39954 pPager->pageSize = pageSize;
39955 sqlite3PageFree(pPager->pTmpSpace);
39956 pPager->pTmpSpace = pNew;
39957 sqlite3PcacheSetPageSize(pPager->pPCache, pageSize);
39961 *pPageSize = pPager->pageSize;
39962 if( rc==SQLITE_OK ){
39963 if( nReserve<0 ) nReserve = pPager->nReserve;
39964 assert( nReserve>=0 && nReserve<1000 );
39965 pPager->nReserve = (i16)nReserve;
39966 pagerReportSize(pPager);
39968 return rc;
39972 ** Return a pointer to the "temporary page" buffer held internally
39973 ** by the pager. This is a buffer that is big enough to hold the
39974 ** entire content of a database page. This buffer is used internally
39975 ** during rollback and will be overwritten whenever a rollback
39976 ** occurs. But other modules are free to use it too, as long as
39977 ** no rollbacks are happening.
39979 SQLITE_PRIVATE void *sqlite3PagerTempSpace(Pager *pPager){
39980 return pPager->pTmpSpace;
39984 ** Attempt to set the maximum database page count if mxPage is positive.
39985 ** Make no changes if mxPage is zero or negative. And never reduce the
39986 ** maximum page count below the current size of the database.
39988 ** Regardless of mxPage, return the current maximum page count.
39990 SQLITE_PRIVATE int sqlite3PagerMaxPageCount(Pager *pPager, int mxPage){
39991 if( mxPage>0 ){
39992 pPager->mxPgno = mxPage;
39994 assert( pPager->eState!=PAGER_OPEN ); /* Called only by OP_MaxPgcnt */
39995 assert( pPager->mxPgno>=pPager->dbSize ); /* OP_MaxPgcnt enforces this */
39996 return pPager->mxPgno;
40000 ** The following set of routines are used to disable the simulated
40001 ** I/O error mechanism. These routines are used to avoid simulated
40002 ** errors in places where we do not care about errors.
40004 ** Unless -DSQLITE_TEST=1 is used, these routines are all no-ops
40005 ** and generate no code.
40007 #ifdef SQLITE_TEST
40008 SQLITE_API extern int sqlite3_io_error_pending;
40009 SQLITE_API extern int sqlite3_io_error_hit;
40010 static int saved_cnt;
40011 void disable_simulated_io_errors(void){
40012 saved_cnt = sqlite3_io_error_pending;
40013 sqlite3_io_error_pending = -1;
40015 void enable_simulated_io_errors(void){
40016 sqlite3_io_error_pending = saved_cnt;
40018 #else
40019 # define disable_simulated_io_errors()
40020 # define enable_simulated_io_errors()
40021 #endif
40024 ** Read the first N bytes from the beginning of the file into memory
40025 ** that pDest points to.
40027 ** If the pager was opened on a transient file (zFilename==""), or
40028 ** opened on a file less than N bytes in size, the output buffer is
40029 ** zeroed and SQLITE_OK returned. The rationale for this is that this
40030 ** function is used to read database headers, and a new transient or
40031 ** zero sized database has a header than consists entirely of zeroes.
40033 ** If any IO error apart from SQLITE_IOERR_SHORT_READ is encountered,
40034 ** the error code is returned to the caller and the contents of the
40035 ** output buffer undefined.
40037 SQLITE_PRIVATE int sqlite3PagerReadFileheader(Pager *pPager, int N, unsigned char *pDest){
40038 int rc = SQLITE_OK;
40039 memset(pDest, 0, N);
40040 assert( isOpen(pPager->fd) || pPager->tempFile );
40042 /* This routine is only called by btree immediately after creating
40043 ** the Pager object. There has not been an opportunity to transition
40044 ** to WAL mode yet.
40046 assert( !pagerUseWal(pPager) );
40048 if( isOpen(pPager->fd) ){
40049 IOTRACE(("DBHDR %p 0 %d\n", pPager, N))
40050 rc = sqlite3OsRead(pPager->fd, pDest, N, 0);
40051 if( rc==SQLITE_IOERR_SHORT_READ ){
40052 rc = SQLITE_OK;
40055 return rc;
40059 ** This function may only be called when a read-transaction is open on
40060 ** the pager. It returns the total number of pages in the database.
40062 ** However, if the file is between 1 and <page-size> bytes in size, then
40063 ** this is considered a 1 page file.
40065 SQLITE_PRIVATE void sqlite3PagerPagecount(Pager *pPager, int *pnPage){
40066 assert( pPager->eState>=PAGER_READER );
40067 assert( pPager->eState!=PAGER_WRITER_FINISHED );
40068 *pnPage = (int)pPager->dbSize;
40073 ** Try to obtain a lock of type locktype on the database file. If
40074 ** a similar or greater lock is already held, this function is a no-op
40075 ** (returning SQLITE_OK immediately).
40077 ** Otherwise, attempt to obtain the lock using sqlite3OsLock(). Invoke
40078 ** the busy callback if the lock is currently not available. Repeat
40079 ** until the busy callback returns false or until the attempt to
40080 ** obtain the lock succeeds.
40082 ** Return SQLITE_OK on success and an error code if we cannot obtain
40083 ** the lock. If the lock is obtained successfully, set the Pager.state
40084 ** variable to locktype before returning.
40086 static int pager_wait_on_lock(Pager *pPager, int locktype){
40087 int rc; /* Return code */
40089 /* Check that this is either a no-op (because the requested lock is
40090 ** already held, or one of the transistions that the busy-handler
40091 ** may be invoked during, according to the comment above
40092 ** sqlite3PagerSetBusyhandler().
40094 assert( (pPager->eLock>=locktype)
40095 || (pPager->eLock==NO_LOCK && locktype==SHARED_LOCK)
40096 || (pPager->eLock==RESERVED_LOCK && locktype==EXCLUSIVE_LOCK)
40099 do {
40100 rc = pagerLockDb(pPager, locktype);
40101 }while( rc==SQLITE_BUSY && pPager->xBusyHandler(pPager->pBusyHandlerArg) );
40102 return rc;
40106 ** Function assertTruncateConstraint(pPager) checks that one of the
40107 ** following is true for all dirty pages currently in the page-cache:
40109 ** a) The page number is less than or equal to the size of the
40110 ** current database image, in pages, OR
40112 ** b) if the page content were written at this time, it would not
40113 ** be necessary to write the current content out to the sub-journal
40114 ** (as determined by function subjRequiresPage()).
40116 ** If the condition asserted by this function were not true, and the
40117 ** dirty page were to be discarded from the cache via the pagerStress()
40118 ** routine, pagerStress() would not write the current page content to
40119 ** the database file. If a savepoint transaction were rolled back after
40120 ** this happened, the correct behaviour would be to restore the current
40121 ** content of the page. However, since this content is not present in either
40122 ** the database file or the portion of the rollback journal and
40123 ** sub-journal rolled back the content could not be restored and the
40124 ** database image would become corrupt. It is therefore fortunate that
40125 ** this circumstance cannot arise.
40127 #if defined(SQLITE_DEBUG)
40128 static void assertTruncateConstraintCb(PgHdr *pPg){
40129 assert( pPg->flags&PGHDR_DIRTY );
40130 assert( !subjRequiresPage(pPg) || pPg->pgno<=pPg->pPager->dbSize );
40132 static void assertTruncateConstraint(Pager *pPager){
40133 sqlite3PcacheIterateDirty(pPager->pPCache, assertTruncateConstraintCb);
40135 #else
40136 # define assertTruncateConstraint(pPager)
40137 #endif
40140 ** Truncate the in-memory database file image to nPage pages. This
40141 ** function does not actually modify the database file on disk. It
40142 ** just sets the internal state of the pager object so that the
40143 ** truncation will be done when the current transaction is committed.
40145 SQLITE_PRIVATE void sqlite3PagerTruncateImage(Pager *pPager, Pgno nPage){
40146 assert( pPager->dbSize>=nPage );
40147 assert( pPager->eState>=PAGER_WRITER_CACHEMOD );
40148 pPager->dbSize = nPage;
40149 assertTruncateConstraint(pPager);
40154 ** This function is called before attempting a hot-journal rollback. It
40155 ** syncs the journal file to disk, then sets pPager->journalHdr to the
40156 ** size of the journal file so that the pager_playback() routine knows
40157 ** that the entire journal file has been synced.
40159 ** Syncing a hot-journal to disk before attempting to roll it back ensures
40160 ** that if a power-failure occurs during the rollback, the process that
40161 ** attempts rollback following system recovery sees the same journal
40162 ** content as this process.
40164 ** If everything goes as planned, SQLITE_OK is returned. Otherwise,
40165 ** an SQLite error code.
40167 static int pagerSyncHotJournal(Pager *pPager){
40168 int rc = SQLITE_OK;
40169 if( !pPager->noSync ){
40170 rc = sqlite3OsSync(pPager->jfd, SQLITE_SYNC_NORMAL);
40172 if( rc==SQLITE_OK ){
40173 rc = sqlite3OsFileSize(pPager->jfd, &pPager->journalHdr);
40175 return rc;
40179 ** Shutdown the page cache. Free all memory and close all files.
40181 ** If a transaction was in progress when this routine is called, that
40182 ** transaction is rolled back. All outstanding pages are invalidated
40183 ** and their memory is freed. Any attempt to use a page associated
40184 ** with this page cache after this function returns will likely
40185 ** result in a coredump.
40187 ** This function always succeeds. If a transaction is active an attempt
40188 ** is made to roll it back. If an error occurs during the rollback
40189 ** a hot journal may be left in the filesystem but no error is returned
40190 ** to the caller.
40192 SQLITE_PRIVATE int sqlite3PagerClose(Pager *pPager){
40193 u8 *pTmp = (u8 *)pPager->pTmpSpace;
40195 disable_simulated_io_errors();
40196 sqlite3BeginBenignMalloc();
40197 /* pPager->errCode = 0; */
40198 pPager->exclusiveMode = 0;
40199 #ifndef SQLITE_OMIT_WAL
40200 sqlite3WalClose(pPager->pWal, pPager->ckptSyncFlags, pPager->pageSize, pTmp);
40201 pPager->pWal = 0;
40202 #endif
40203 pager_reset(pPager);
40204 if( MEMDB ){
40205 pager_unlock(pPager);
40206 }else{
40207 /* If it is open, sync the journal file before calling UnlockAndRollback.
40208 ** If this is not done, then an unsynced portion of the open journal
40209 ** file may be played back into the database. If a power failure occurs
40210 ** while this is happening, the database could become corrupt.
40212 ** If an error occurs while trying to sync the journal, shift the pager
40213 ** into the ERROR state. This causes UnlockAndRollback to unlock the
40214 ** database and close the journal file without attempting to roll it
40215 ** back or finalize it. The next database user will have to do hot-journal
40216 ** rollback before accessing the database file.
40218 if( isOpen(pPager->jfd) ){
40219 pager_error(pPager, pagerSyncHotJournal(pPager));
40221 pagerUnlockAndRollback(pPager);
40223 sqlite3EndBenignMalloc();
40224 enable_simulated_io_errors();
40225 PAGERTRACE(("CLOSE %d\n", PAGERID(pPager)));
40226 IOTRACE(("CLOSE %p\n", pPager))
40227 sqlite3OsClose(pPager->jfd);
40228 sqlite3OsClose(pPager->fd);
40229 sqlite3PageFree(pTmp);
40230 sqlite3PcacheClose(pPager->pPCache);
40232 #ifdef SQLITE_HAS_CODEC
40233 if( pPager->xCodecFree ) pPager->xCodecFree(pPager->pCodec);
40234 #endif
40236 assert( !pPager->aSavepoint && !pPager->pInJournal );
40237 assert( !isOpen(pPager->jfd) && !isOpen(pPager->sjfd) );
40239 sqlite3_free(pPager);
40240 return SQLITE_OK;
40243 #if !defined(NDEBUG) || defined(SQLITE_TEST)
40245 ** Return the page number for page pPg.
40247 SQLITE_PRIVATE Pgno sqlite3PagerPagenumber(DbPage *pPg){
40248 return pPg->pgno;
40250 #endif
40253 ** Increment the reference count for page pPg.
40255 SQLITE_PRIVATE void sqlite3PagerRef(DbPage *pPg){
40256 sqlite3PcacheRef(pPg);
40260 ** Sync the journal. In other words, make sure all the pages that have
40261 ** been written to the journal have actually reached the surface of the
40262 ** disk and can be restored in the event of a hot-journal rollback.
40264 ** If the Pager.noSync flag is set, then this function is a no-op.
40265 ** Otherwise, the actions required depend on the journal-mode and the
40266 ** device characteristics of the the file-system, as follows:
40268 ** * If the journal file is an in-memory journal file, no action need
40269 ** be taken.
40271 ** * Otherwise, if the device does not support the SAFE_APPEND property,
40272 ** then the nRec field of the most recently written journal header
40273 ** is updated to contain the number of journal records that have
40274 ** been written following it. If the pager is operating in full-sync
40275 ** mode, then the journal file is synced before this field is updated.
40277 ** * If the device does not support the SEQUENTIAL property, then
40278 ** journal file is synced.
40280 ** Or, in pseudo-code:
40282 ** if( NOT <in-memory journal> ){
40283 ** if( NOT SAFE_APPEND ){
40284 ** if( <full-sync mode> ) xSync(<journal file>);
40285 ** <update nRec field>
40286 ** }
40287 ** if( NOT SEQUENTIAL ) xSync(<journal file>);
40288 ** }
40290 ** If successful, this routine clears the PGHDR_NEED_SYNC flag of every
40291 ** page currently held in memory before returning SQLITE_OK. If an IO
40292 ** error is encountered, then the IO error code is returned to the caller.
40294 static int syncJournal(Pager *pPager, int newHdr){
40295 int rc; /* Return code */
40297 assert( pPager->eState==PAGER_WRITER_CACHEMOD
40298 || pPager->eState==PAGER_WRITER_DBMOD
40300 assert( assert_pager_state(pPager) );
40301 assert( !pagerUseWal(pPager) );
40303 rc = sqlite3PagerExclusiveLock(pPager);
40304 if( rc!=SQLITE_OK ) return rc;
40306 if( !pPager->noSync ){
40307 assert( !pPager->tempFile );
40308 if( isOpen(pPager->jfd) && pPager->journalMode!=PAGER_JOURNALMODE_MEMORY ){
40309 const int iDc = sqlite3OsDeviceCharacteristics(pPager->fd);
40310 assert( isOpen(pPager->jfd) );
40312 if( 0==(iDc&SQLITE_IOCAP_SAFE_APPEND) ){
40313 /* This block deals with an obscure problem. If the last connection
40314 ** that wrote to this database was operating in persistent-journal
40315 ** mode, then the journal file may at this point actually be larger
40316 ** than Pager.journalOff bytes. If the next thing in the journal
40317 ** file happens to be a journal-header (written as part of the
40318 ** previous connection's transaction), and a crash or power-failure
40319 ** occurs after nRec is updated but before this connection writes
40320 ** anything else to the journal file (or commits/rolls back its
40321 ** transaction), then SQLite may become confused when doing the
40322 ** hot-journal rollback following recovery. It may roll back all
40323 ** of this connections data, then proceed to rolling back the old,
40324 ** out-of-date data that follows it. Database corruption.
40326 ** To work around this, if the journal file does appear to contain
40327 ** a valid header following Pager.journalOff, then write a 0x00
40328 ** byte to the start of it to prevent it from being recognized.
40330 ** Variable iNextHdrOffset is set to the offset at which this
40331 ** problematic header will occur, if it exists. aMagic is used
40332 ** as a temporary buffer to inspect the first couple of bytes of
40333 ** the potential journal header.
40335 i64 iNextHdrOffset;
40336 u8 aMagic[8];
40337 u8 zHeader[sizeof(aJournalMagic)+4];
40339 memcpy(zHeader, aJournalMagic, sizeof(aJournalMagic));
40340 put32bits(&zHeader[sizeof(aJournalMagic)], pPager->nRec);
40342 iNextHdrOffset = journalHdrOffset(pPager);
40343 rc = sqlite3OsRead(pPager->jfd, aMagic, 8, iNextHdrOffset);
40344 if( rc==SQLITE_OK && 0==memcmp(aMagic, aJournalMagic, 8) ){
40345 static const u8 zerobyte = 0;
40346 rc = sqlite3OsWrite(pPager->jfd, &zerobyte, 1, iNextHdrOffset);
40348 if( rc!=SQLITE_OK && rc!=SQLITE_IOERR_SHORT_READ ){
40349 return rc;
40352 /* Write the nRec value into the journal file header. If in
40353 ** full-synchronous mode, sync the journal first. This ensures that
40354 ** all data has really hit the disk before nRec is updated to mark
40355 ** it as a candidate for rollback.
40357 ** This is not required if the persistent media supports the
40358 ** SAFE_APPEND property. Because in this case it is not possible
40359 ** for garbage data to be appended to the file, the nRec field
40360 ** is populated with 0xFFFFFFFF when the journal header is written
40361 ** and never needs to be updated.
40363 if( pPager->fullSync && 0==(iDc&SQLITE_IOCAP_SEQUENTIAL) ){
40364 PAGERTRACE(("SYNC journal of %d\n", PAGERID(pPager)));
40365 IOTRACE(("JSYNC %p\n", pPager))
40366 rc = sqlite3OsSync(pPager->jfd, pPager->syncFlags);
40367 if( rc!=SQLITE_OK ) return rc;
40369 IOTRACE(("JHDR %p %lld\n", pPager, pPager->journalHdr));
40370 rc = sqlite3OsWrite(
40371 pPager->jfd, zHeader, sizeof(zHeader), pPager->journalHdr
40373 if( rc!=SQLITE_OK ) return rc;
40375 if( 0==(iDc&SQLITE_IOCAP_SEQUENTIAL) ){
40376 PAGERTRACE(("SYNC journal of %d\n", PAGERID(pPager)));
40377 IOTRACE(("JSYNC %p\n", pPager))
40378 rc = sqlite3OsSync(pPager->jfd, pPager->syncFlags|
40379 (pPager->syncFlags==SQLITE_SYNC_FULL?SQLITE_SYNC_DATAONLY:0)
40381 if( rc!=SQLITE_OK ) return rc;
40384 pPager->journalHdr = pPager->journalOff;
40385 if( newHdr && 0==(iDc&SQLITE_IOCAP_SAFE_APPEND) ){
40386 pPager->nRec = 0;
40387 rc = writeJournalHdr(pPager);
40388 if( rc!=SQLITE_OK ) return rc;
40390 }else{
40391 pPager->journalHdr = pPager->journalOff;
40395 /* Unless the pager is in noSync mode, the journal file was just
40396 ** successfully synced. Either way, clear the PGHDR_NEED_SYNC flag on
40397 ** all pages.
40399 sqlite3PcacheClearSyncFlags(pPager->pPCache);
40400 pPager->eState = PAGER_WRITER_DBMOD;
40401 assert( assert_pager_state(pPager) );
40402 return SQLITE_OK;
40406 ** The argument is the first in a linked list of dirty pages connected
40407 ** by the PgHdr.pDirty pointer. This function writes each one of the
40408 ** in-memory pages in the list to the database file. The argument may
40409 ** be NULL, representing an empty list. In this case this function is
40410 ** a no-op.
40412 ** The pager must hold at least a RESERVED lock when this function
40413 ** is called. Before writing anything to the database file, this lock
40414 ** is upgraded to an EXCLUSIVE lock. If the lock cannot be obtained,
40415 ** SQLITE_BUSY is returned and no data is written to the database file.
40417 ** If the pager is a temp-file pager and the actual file-system file
40418 ** is not yet open, it is created and opened before any data is
40419 ** written out.
40421 ** Once the lock has been upgraded and, if necessary, the file opened,
40422 ** the pages are written out to the database file in list order. Writing
40423 ** a page is skipped if it meets either of the following criteria:
40425 ** * The page number is greater than Pager.dbSize, or
40426 ** * The PGHDR_DONT_WRITE flag is set on the page.
40428 ** If writing out a page causes the database file to grow, Pager.dbFileSize
40429 ** is updated accordingly. If page 1 is written out, then the value cached
40430 ** in Pager.dbFileVers[] is updated to match the new value stored in
40431 ** the database file.
40433 ** If everything is successful, SQLITE_OK is returned. If an IO error
40434 ** occurs, an IO error code is returned. Or, if the EXCLUSIVE lock cannot
40435 ** be obtained, SQLITE_BUSY is returned.
40437 static int pager_write_pagelist(Pager *pPager, PgHdr *pList){
40438 int rc = SQLITE_OK; /* Return code */
40440 /* This function is only called for rollback pagers in WRITER_DBMOD state. */
40441 assert( !pagerUseWal(pPager) );
40442 assert( pPager->eState==PAGER_WRITER_DBMOD );
40443 assert( pPager->eLock==EXCLUSIVE_LOCK );
40445 /* If the file is a temp-file has not yet been opened, open it now. It
40446 ** is not possible for rc to be other than SQLITE_OK if this branch
40447 ** is taken, as pager_wait_on_lock() is a no-op for temp-files.
40449 if( !isOpen(pPager->fd) ){
40450 assert( pPager->tempFile && rc==SQLITE_OK );
40451 rc = pagerOpentemp(pPager, pPager->fd, pPager->vfsFlags);
40454 /* Before the first write, give the VFS a hint of what the final
40455 ** file size will be.
40457 assert( rc!=SQLITE_OK || isOpen(pPager->fd) );
40458 if( rc==SQLITE_OK && pPager->dbSize>pPager->dbHintSize ){
40459 sqlite3_int64 szFile = pPager->pageSize * (sqlite3_int64)pPager->dbSize;
40460 sqlite3OsFileControl(pPager->fd, SQLITE_FCNTL_SIZE_HINT, &szFile);
40461 pPager->dbHintSize = pPager->dbSize;
40464 while( rc==SQLITE_OK && pList ){
40465 Pgno pgno = pList->pgno;
40467 /* If there are dirty pages in the page cache with page numbers greater
40468 ** than Pager.dbSize, this means sqlite3PagerTruncateImage() was called to
40469 ** make the file smaller (presumably by auto-vacuum code). Do not write
40470 ** any such pages to the file.
40472 ** Also, do not write out any page that has the PGHDR_DONT_WRITE flag
40473 ** set (set by sqlite3PagerDontWrite()).
40475 if( pgno<=pPager->dbSize && 0==(pList->flags&PGHDR_DONT_WRITE) ){
40476 i64 offset = (pgno-1)*(i64)pPager->pageSize; /* Offset to write */
40477 char *pData; /* Data to write */
40479 assert( (pList->flags&PGHDR_NEED_SYNC)==0 );
40480 if( pList->pgno==1 ) pager_write_changecounter(pList);
40482 /* Encode the database */
40483 CODEC2(pPager, pList->pData, pgno, 6, return SQLITE_NOMEM, pData);
40485 /* Write out the page data. */
40486 rc = sqlite3OsWrite(pPager->fd, pData, pPager->pageSize, offset);
40488 /* If page 1 was just written, update Pager.dbFileVers to match
40489 ** the value now stored in the database file. If writing this
40490 ** page caused the database file to grow, update dbFileSize.
40492 if( pgno==1 ){
40493 memcpy(&pPager->dbFileVers, &pData[24], sizeof(pPager->dbFileVers));
40495 if( pgno>pPager->dbFileSize ){
40496 pPager->dbFileSize = pgno;
40499 /* Update any backup objects copying the contents of this pager. */
40500 sqlite3BackupUpdate(pPager->pBackup, pgno, (u8*)pList->pData);
40502 PAGERTRACE(("STORE %d page %d hash(%08x)\n",
40503 PAGERID(pPager), pgno, pager_pagehash(pList)));
40504 IOTRACE(("PGOUT %p %d\n", pPager, pgno));
40505 PAGER_INCR(sqlite3_pager_writedb_count);
40506 PAGER_INCR(pPager->nWrite);
40507 }else{
40508 PAGERTRACE(("NOSTORE %d page %d\n", PAGERID(pPager), pgno));
40510 pager_set_pagehash(pList);
40511 pList = pList->pDirty;
40514 return rc;
40518 ** Ensure that the sub-journal file is open. If it is already open, this
40519 ** function is a no-op.
40521 ** SQLITE_OK is returned if everything goes according to plan. An
40522 ** SQLITE_IOERR_XXX error code is returned if a call to sqlite3OsOpen()
40523 ** fails.
40525 static int openSubJournal(Pager *pPager){
40526 int rc = SQLITE_OK;
40527 if( !isOpen(pPager->sjfd) ){
40528 if( pPager->journalMode==PAGER_JOURNALMODE_MEMORY || pPager->subjInMemory ){
40529 sqlite3MemJournalOpen(pPager->sjfd);
40530 }else{
40531 rc = pagerOpentemp(pPager, pPager->sjfd, SQLITE_OPEN_SUBJOURNAL);
40534 return rc;
40538 ** Append a record of the current state of page pPg to the sub-journal.
40539 ** It is the callers responsibility to use subjRequiresPage() to check
40540 ** that it is really required before calling this function.
40542 ** If successful, set the bit corresponding to pPg->pgno in the bitvecs
40543 ** for all open savepoints before returning.
40545 ** This function returns SQLITE_OK if everything is successful, an IO
40546 ** error code if the attempt to write to the sub-journal fails, or
40547 ** SQLITE_NOMEM if a malloc fails while setting a bit in a savepoint
40548 ** bitvec.
40550 static int subjournalPage(PgHdr *pPg){
40551 int rc = SQLITE_OK;
40552 Pager *pPager = pPg->pPager;
40553 if( pPager->journalMode!=PAGER_JOURNALMODE_OFF ){
40555 /* Open the sub-journal, if it has not already been opened */
40556 assert( pPager->useJournal );
40557 assert( isOpen(pPager->jfd) || pagerUseWal(pPager) );
40558 assert( isOpen(pPager->sjfd) || pPager->nSubRec==0 );
40559 assert( pagerUseWal(pPager)
40560 || pageInJournal(pPg)
40561 || pPg->pgno>pPager->dbOrigSize
40563 rc = openSubJournal(pPager);
40565 /* If the sub-journal was opened successfully (or was already open),
40566 ** write the journal record into the file. */
40567 if( rc==SQLITE_OK ){
40568 void *pData = pPg->pData;
40569 i64 offset = pPager->nSubRec*(4+pPager->pageSize);
40570 char *pData2;
40572 CODEC2(pPager, pData, pPg->pgno, 7, return SQLITE_NOMEM, pData2);
40573 PAGERTRACE(("STMT-JOURNAL %d page %d\n", PAGERID(pPager), pPg->pgno));
40574 rc = write32bits(pPager->sjfd, offset, pPg->pgno);
40575 if( rc==SQLITE_OK ){
40576 rc = sqlite3OsWrite(pPager->sjfd, pData2, pPager->pageSize, offset+4);
40580 if( rc==SQLITE_OK ){
40581 pPager->nSubRec++;
40582 assert( pPager->nSavepoint>0 );
40583 rc = addToSavepointBitvecs(pPager, pPg->pgno);
40585 return rc;
40589 ** This function is called by the pcache layer when it has reached some
40590 ** soft memory limit. The first argument is a pointer to a Pager object
40591 ** (cast as a void*). The pager is always 'purgeable' (not an in-memory
40592 ** database). The second argument is a reference to a page that is
40593 ** currently dirty but has no outstanding references. The page
40594 ** is always associated with the Pager object passed as the first
40595 ** argument.
40597 ** The job of this function is to make pPg clean by writing its contents
40598 ** out to the database file, if possible. This may involve syncing the
40599 ** journal file.
40601 ** If successful, sqlite3PcacheMakeClean() is called on the page and
40602 ** SQLITE_OK returned. If an IO error occurs while trying to make the
40603 ** page clean, the IO error code is returned. If the page cannot be
40604 ** made clean for some other reason, but no error occurs, then SQLITE_OK
40605 ** is returned by sqlite3PcacheMakeClean() is not called.
40607 static int pagerStress(void *p, PgHdr *pPg){
40608 Pager *pPager = (Pager *)p;
40609 int rc = SQLITE_OK;
40611 assert( pPg->pPager==pPager );
40612 assert( pPg->flags&PGHDR_DIRTY );
40614 /* The doNotSyncSpill flag is set during times when doing a sync of
40615 ** journal (and adding a new header) is not allowed. This occurs
40616 ** during calls to sqlite3PagerWrite() while trying to journal multiple
40617 ** pages belonging to the same sector.
40619 ** The doNotSpill flag inhibits all cache spilling regardless of whether
40620 ** or not a sync is required. This is set during a rollback.
40622 ** Spilling is also prohibited when in an error state since that could
40623 ** lead to database corruption. In the current implementaton it
40624 ** is impossible for sqlite3PCacheFetch() to be called with createFlag==1
40625 ** while in the error state, hence it is impossible for this routine to
40626 ** be called in the error state. Nevertheless, we include a NEVER()
40627 ** test for the error state as a safeguard against future changes.
40629 if( NEVER(pPager->errCode) ) return SQLITE_OK;
40630 if( pPager->doNotSpill ) return SQLITE_OK;
40631 if( pPager->doNotSyncSpill && (pPg->flags & PGHDR_NEED_SYNC)!=0 ){
40632 return SQLITE_OK;
40635 pPg->pDirty = 0;
40636 if( pagerUseWal(pPager) ){
40637 /* Write a single frame for this page to the log. */
40638 if( subjRequiresPage(pPg) ){
40639 rc = subjournalPage(pPg);
40641 if( rc==SQLITE_OK ){
40642 rc = pagerWalFrames(pPager, pPg, 0, 0, 0);
40644 }else{
40646 /* Sync the journal file if required. */
40647 if( pPg->flags&PGHDR_NEED_SYNC
40648 || pPager->eState==PAGER_WRITER_CACHEMOD
40650 rc = syncJournal(pPager, 1);
40653 /* If the page number of this page is larger than the current size of
40654 ** the database image, it may need to be written to the sub-journal.
40655 ** This is because the call to pager_write_pagelist() below will not
40656 ** actually write data to the file in this case.
40658 ** Consider the following sequence of events:
40660 ** BEGIN;
40661 ** <journal page X>
40662 ** <modify page X>
40663 ** SAVEPOINT sp;
40664 ** <shrink database file to Y pages>
40665 ** pagerStress(page X)
40666 ** ROLLBACK TO sp;
40668 ** If (X>Y), then when pagerStress is called page X will not be written
40669 ** out to the database file, but will be dropped from the cache. Then,
40670 ** following the "ROLLBACK TO sp" statement, reading page X will read
40671 ** data from the database file. This will be the copy of page X as it
40672 ** was when the transaction started, not as it was when "SAVEPOINT sp"
40673 ** was executed.
40675 ** The solution is to write the current data for page X into the
40676 ** sub-journal file now (if it is not already there), so that it will
40677 ** be restored to its current value when the "ROLLBACK TO sp" is
40678 ** executed.
40680 if( NEVER(
40681 rc==SQLITE_OK && pPg->pgno>pPager->dbSize && subjRequiresPage(pPg)
40682 ) ){
40683 rc = subjournalPage(pPg);
40686 /* Write the contents of the page out to the database file. */
40687 if( rc==SQLITE_OK ){
40688 assert( (pPg->flags&PGHDR_NEED_SYNC)==0 );
40689 rc = pager_write_pagelist(pPager, pPg);
40693 /* Mark the page as clean. */
40694 if( rc==SQLITE_OK ){
40695 PAGERTRACE(("STRESS %d page %d\n", PAGERID(pPager), pPg->pgno));
40696 sqlite3PcacheMakeClean(pPg);
40699 return pager_error(pPager, rc);
40704 ** Allocate and initialize a new Pager object and put a pointer to it
40705 ** in *ppPager. The pager should eventually be freed by passing it
40706 ** to sqlite3PagerClose().
40708 ** The zFilename argument is the path to the database file to open.
40709 ** If zFilename is NULL then a randomly-named temporary file is created
40710 ** and used as the file to be cached. Temporary files are be deleted
40711 ** automatically when they are closed. If zFilename is ":memory:" then
40712 ** all information is held in cache. It is never written to disk.
40713 ** This can be used to implement an in-memory database.
40715 ** The nExtra parameter specifies the number of bytes of space allocated
40716 ** along with each page reference. This space is available to the user
40717 ** via the sqlite3PagerGetExtra() API.
40719 ** The flags argument is used to specify properties that affect the
40720 ** operation of the pager. It should be passed some bitwise combination
40721 ** of the PAGER_OMIT_JOURNAL and PAGER_NO_READLOCK flags.
40723 ** The vfsFlags parameter is a bitmask to pass to the flags parameter
40724 ** of the xOpen() method of the supplied VFS when opening files.
40726 ** If the pager object is allocated and the specified file opened
40727 ** successfully, SQLITE_OK is returned and *ppPager set to point to
40728 ** the new pager object. If an error occurs, *ppPager is set to NULL
40729 ** and error code returned. This function may return SQLITE_NOMEM
40730 ** (sqlite3Malloc() is used to allocate memory), SQLITE_CANTOPEN or
40731 ** various SQLITE_IO_XXX errors.
40733 SQLITE_PRIVATE int sqlite3PagerOpen(
40734 sqlite3_vfs *pVfs, /* The virtual file system to use */
40735 Pager **ppPager, /* OUT: Return the Pager structure here */
40736 const char *zFilename, /* Name of the database file to open */
40737 int nExtra, /* Extra bytes append to each in-memory page */
40738 int flags, /* flags controlling this file */
40739 int vfsFlags, /* flags passed through to sqlite3_vfs.xOpen() */
40740 void (*xReinit)(DbPage*) /* Function to reinitialize pages */
40742 u8 *pPtr;
40743 Pager *pPager = 0; /* Pager object to allocate and return */
40744 int rc = SQLITE_OK; /* Return code */
40745 int tempFile = 0; /* True for temp files (incl. in-memory files) */
40746 int memDb = 0; /* True if this is an in-memory file */
40747 int readOnly = 0; /* True if this is a read-only file */
40748 int journalFileSize; /* Bytes to allocate for each journal fd */
40749 char *zPathname = 0; /* Full path to database file */
40750 int nPathname = 0; /* Number of bytes in zPathname */
40751 int useJournal = (flags & PAGER_OMIT_JOURNAL)==0; /* False to omit journal */
40752 int noReadlock = (flags & PAGER_NO_READLOCK)!=0; /* True to omit read-lock */
40753 int pcacheSize = sqlite3PcacheSize(); /* Bytes to allocate for PCache */
40754 u32 szPageDflt = SQLITE_DEFAULT_PAGE_SIZE; /* Default page size */
40756 /* Figure out how much space is required for each journal file-handle
40757 ** (there are two of them, the main journal and the sub-journal). This
40758 ** is the maximum space required for an in-memory journal file handle
40759 ** and a regular journal file-handle. Note that a "regular journal-handle"
40760 ** may be a wrapper capable of caching the first portion of the journal
40761 ** file in memory to implement the atomic-write optimization (see
40762 ** source file journal.c).
40764 if( sqlite3JournalSize(pVfs)>sqlite3MemJournalSize() ){
40765 journalFileSize = ROUND8(sqlite3JournalSize(pVfs));
40766 }else{
40767 journalFileSize = ROUND8(sqlite3MemJournalSize());
40770 /* Set the output variable to NULL in case an error occurs. */
40771 *ppPager = 0;
40773 #ifndef SQLITE_OMIT_MEMORYDB
40774 if( flags & PAGER_MEMORY ){
40775 memDb = 1;
40776 zFilename = 0;
40778 #endif
40780 /* Compute and store the full pathname in an allocated buffer pointed
40781 ** to by zPathname, length nPathname. Or, if this is a temporary file,
40782 ** leave both nPathname and zPathname set to 0.
40784 if( zFilename && zFilename[0] ){
40785 nPathname = pVfs->mxPathname+1;
40786 zPathname = sqlite3Malloc(nPathname*2);
40787 if( zPathname==0 ){
40788 return SQLITE_NOMEM;
40790 zPathname[0] = 0; /* Make sure initialized even if FullPathname() fails */
40791 rc = sqlite3OsFullPathname(pVfs, zFilename, nPathname, zPathname);
40792 nPathname = sqlite3Strlen30(zPathname);
40793 if( rc==SQLITE_OK && nPathname+8>pVfs->mxPathname ){
40794 /* This branch is taken when the journal path required by
40795 ** the database being opened will be more than pVfs->mxPathname
40796 ** bytes in length. This means the database cannot be opened,
40797 ** as it will not be possible to open the journal file or even
40798 ** check for a hot-journal before reading.
40800 rc = SQLITE_CANTOPEN_BKPT;
40802 if( rc!=SQLITE_OK ){
40803 sqlite3_free(zPathname);
40804 return rc;
40808 /* Allocate memory for the Pager structure, PCache object, the
40809 ** three file descriptors, the database file name and the journal
40810 ** file name. The layout in memory is as follows:
40812 ** Pager object (sizeof(Pager) bytes)
40813 ** PCache object (sqlite3PcacheSize() bytes)
40814 ** Database file handle (pVfs->szOsFile bytes)
40815 ** Sub-journal file handle (journalFileSize bytes)
40816 ** Main journal file handle (journalFileSize bytes)
40817 ** Database file name (nPathname+1 bytes)
40818 ** Journal file name (nPathname+8+1 bytes)
40820 pPtr = (u8 *)sqlite3MallocZero(
40821 ROUND8(sizeof(*pPager)) + /* Pager structure */
40822 ROUND8(pcacheSize) + /* PCache object */
40823 ROUND8(pVfs->szOsFile) + /* The main db file */
40824 journalFileSize * 2 + /* The two journal files */
40825 nPathname + 1 + /* zFilename */
40826 nPathname + 8 + 1 /* zJournal */
40827 #ifndef SQLITE_OMIT_WAL
40828 + nPathname + 4 + 1 /* zWal */
40829 #endif
40831 assert( EIGHT_BYTE_ALIGNMENT(SQLITE_INT_TO_PTR(journalFileSize)) );
40832 if( !pPtr ){
40833 sqlite3_free(zPathname);
40834 return SQLITE_NOMEM;
40836 pPager = (Pager*)(pPtr);
40837 pPager->pPCache = (PCache*)(pPtr += ROUND8(sizeof(*pPager)));
40838 pPager->fd = (sqlite3_file*)(pPtr += ROUND8(pcacheSize));
40839 pPager->sjfd = (sqlite3_file*)(pPtr += ROUND8(pVfs->szOsFile));
40840 pPager->jfd = (sqlite3_file*)(pPtr += journalFileSize);
40841 pPager->zFilename = (char*)(pPtr += journalFileSize);
40842 assert( EIGHT_BYTE_ALIGNMENT(pPager->jfd) );
40844 /* Fill in the Pager.zFilename and Pager.zJournal buffers, if required. */
40845 if( zPathname ){
40846 assert( nPathname>0 );
40847 pPager->zJournal = (char*)(pPtr += nPathname + 1);
40848 memcpy(pPager->zFilename, zPathname, nPathname);
40849 memcpy(pPager->zJournal, zPathname, nPathname);
40850 memcpy(&pPager->zJournal[nPathname], "-journal", 8);
40851 #ifndef SQLITE_OMIT_WAL
40852 pPager->zWal = &pPager->zJournal[nPathname+8+1];
40853 memcpy(pPager->zWal, zPathname, nPathname);
40854 memcpy(&pPager->zWal[nPathname], "-wal", 4);
40855 #endif
40856 sqlite3_free(zPathname);
40858 pPager->pVfs = pVfs;
40859 pPager->vfsFlags = vfsFlags;
40861 /* Open the pager file.
40863 if( zFilename && zFilename[0] ){
40864 int fout = 0; /* VFS flags returned by xOpen() */
40865 rc = sqlite3OsOpen(pVfs, pPager->zFilename, pPager->fd, vfsFlags, &fout);
40866 assert( !memDb );
40867 readOnly = (fout&SQLITE_OPEN_READONLY);
40869 /* If the file was successfully opened for read/write access,
40870 ** choose a default page size in case we have to create the
40871 ** database file. The default page size is the maximum of:
40873 ** + SQLITE_DEFAULT_PAGE_SIZE,
40874 ** + The value returned by sqlite3OsSectorSize()
40875 ** + The largest page size that can be written atomically.
40877 if( rc==SQLITE_OK && !readOnly ){
40878 setSectorSize(pPager);
40879 assert(SQLITE_DEFAULT_PAGE_SIZE<=SQLITE_MAX_DEFAULT_PAGE_SIZE);
40880 if( szPageDflt<pPager->sectorSize ){
40881 if( pPager->sectorSize>SQLITE_MAX_DEFAULT_PAGE_SIZE ){
40882 szPageDflt = SQLITE_MAX_DEFAULT_PAGE_SIZE;
40883 }else{
40884 szPageDflt = (u32)pPager->sectorSize;
40887 #ifdef SQLITE_ENABLE_ATOMIC_WRITE
40889 int iDc = sqlite3OsDeviceCharacteristics(pPager->fd);
40890 int ii;
40891 assert(SQLITE_IOCAP_ATOMIC512==(512>>8));
40892 assert(SQLITE_IOCAP_ATOMIC64K==(65536>>8));
40893 assert(SQLITE_MAX_DEFAULT_PAGE_SIZE<=65536);
40894 for(ii=szPageDflt; ii<=SQLITE_MAX_DEFAULT_PAGE_SIZE; ii=ii*2){
40895 if( iDc&(SQLITE_IOCAP_ATOMIC|(ii>>8)) ){
40896 szPageDflt = ii;
40900 #endif
40902 }else{
40903 /* If a temporary file is requested, it is not opened immediately.
40904 ** In this case we accept the default page size and delay actually
40905 ** opening the file until the first call to OsWrite().
40907 ** This branch is also run for an in-memory database. An in-memory
40908 ** database is the same as a temp-file that is never written out to
40909 ** disk and uses an in-memory rollback journal.
40911 tempFile = 1;
40912 pPager->eState = PAGER_READER;
40913 pPager->eLock = EXCLUSIVE_LOCK;
40914 readOnly = (vfsFlags&SQLITE_OPEN_READONLY);
40917 /* The following call to PagerSetPagesize() serves to set the value of
40918 ** Pager.pageSize and to allocate the Pager.pTmpSpace buffer.
40920 if( rc==SQLITE_OK ){
40921 assert( pPager->memDb==0 );
40922 rc = sqlite3PagerSetPagesize(pPager, &szPageDflt, -1);
40923 testcase( rc!=SQLITE_OK );
40926 /* If an error occurred in either of the blocks above, free the
40927 ** Pager structure and close the file.
40929 if( rc!=SQLITE_OK ){
40930 assert( !pPager->pTmpSpace );
40931 sqlite3OsClose(pPager->fd);
40932 sqlite3_free(pPager);
40933 return rc;
40936 /* Initialize the PCache object. */
40937 assert( nExtra<1000 );
40938 nExtra = ROUND8(nExtra);
40939 sqlite3PcacheOpen(szPageDflt, nExtra, !memDb,
40940 !memDb?pagerStress:0, (void *)pPager, pPager->pPCache);
40942 PAGERTRACE(("OPEN %d %s\n", FILEHANDLEID(pPager->fd), pPager->zFilename));
40943 IOTRACE(("OPEN %p %s\n", pPager, pPager->zFilename))
40945 pPager->useJournal = (u8)useJournal;
40946 pPager->noReadlock = (noReadlock && readOnly) ?1:0;
40947 /* pPager->stmtOpen = 0; */
40948 /* pPager->stmtInUse = 0; */
40949 /* pPager->nRef = 0; */
40950 /* pPager->stmtSize = 0; */
40951 /* pPager->stmtJSize = 0; */
40952 /* pPager->nPage = 0; */
40953 pPager->mxPgno = SQLITE_MAX_PAGE_COUNT;
40954 /* pPager->state = PAGER_UNLOCK; */
40955 #if 0
40956 assert( pPager->state == (tempFile ? PAGER_EXCLUSIVE : PAGER_UNLOCK) );
40957 #endif
40958 /* pPager->errMask = 0; */
40959 pPager->tempFile = (u8)tempFile;
40960 assert( tempFile==PAGER_LOCKINGMODE_NORMAL
40961 || tempFile==PAGER_LOCKINGMODE_EXCLUSIVE );
40962 assert( PAGER_LOCKINGMODE_EXCLUSIVE==1 );
40963 pPager->exclusiveMode = (u8)tempFile;
40964 pPager->changeCountDone = pPager->tempFile;
40965 pPager->memDb = (u8)memDb;
40966 pPager->readOnly = (u8)readOnly;
40967 assert( useJournal || pPager->tempFile );
40968 pPager->noSync = pPager->tempFile;
40969 pPager->fullSync = pPager->noSync ?0:1;
40970 pPager->syncFlags = pPager->noSync ? 0 : SQLITE_SYNC_NORMAL;
40971 pPager->ckptSyncFlags = pPager->syncFlags;
40972 /* pPager->pFirst = 0; */
40973 /* pPager->pFirstSynced = 0; */
40974 /* pPager->pLast = 0; */
40975 pPager->nExtra = (u16)nExtra;
40976 pPager->journalSizeLimit = SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT;
40977 assert( isOpen(pPager->fd) || tempFile );
40978 setSectorSize(pPager);
40979 if( !useJournal ){
40980 pPager->journalMode = PAGER_JOURNALMODE_OFF;
40981 }else if( memDb ){
40982 pPager->journalMode = PAGER_JOURNALMODE_MEMORY;
40984 /* pPager->xBusyHandler = 0; */
40985 /* pPager->pBusyHandlerArg = 0; */
40986 pPager->xReiniter = xReinit;
40987 /* memset(pPager->aHash, 0, sizeof(pPager->aHash)); */
40989 *ppPager = pPager;
40990 return SQLITE_OK;
40996 ** This function is called after transitioning from PAGER_UNLOCK to
40997 ** PAGER_SHARED state. It tests if there is a hot journal present in
40998 ** the file-system for the given pager. A hot journal is one that
40999 ** needs to be played back. According to this function, a hot-journal
41000 ** file exists if the following criteria are met:
41002 ** * The journal file exists in the file system, and
41003 ** * No process holds a RESERVED or greater lock on the database file, and
41004 ** * The database file itself is greater than 0 bytes in size, and
41005 ** * The first byte of the journal file exists and is not 0x00.
41007 ** If the current size of the database file is 0 but a journal file
41008 ** exists, that is probably an old journal left over from a prior
41009 ** database with the same name. In this case the journal file is
41010 ** just deleted using OsDelete, *pExists is set to 0 and SQLITE_OK
41011 ** is returned.
41013 ** This routine does not check if there is a master journal filename
41014 ** at the end of the file. If there is, and that master journal file
41015 ** does not exist, then the journal file is not really hot. In this
41016 ** case this routine will return a false-positive. The pager_playback()
41017 ** routine will discover that the journal file is not really hot and
41018 ** will not roll it back.
41020 ** If a hot-journal file is found to exist, *pExists is set to 1 and
41021 ** SQLITE_OK returned. If no hot-journal file is present, *pExists is
41022 ** set to 0 and SQLITE_OK returned. If an IO error occurs while trying
41023 ** to determine whether or not a hot-journal file exists, the IO error
41024 ** code is returned and the value of *pExists is undefined.
41026 static int hasHotJournal(Pager *pPager, int *pExists){
41027 sqlite3_vfs * const pVfs = pPager->pVfs;
41028 int rc = SQLITE_OK; /* Return code */
41029 int exists = 1; /* True if a journal file is present */
41030 int jrnlOpen = !!isOpen(pPager->jfd);
41032 assert( pPager->useJournal );
41033 assert( isOpen(pPager->fd) );
41034 assert( pPager->eState==PAGER_OPEN );
41036 assert( jrnlOpen==0 || ( sqlite3OsDeviceCharacteristics(pPager->jfd) &
41037 SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN
41040 *pExists = 0;
41041 if( !jrnlOpen ){
41042 rc = sqlite3OsAccess(pVfs, pPager->zJournal, SQLITE_ACCESS_EXISTS, &exists);
41044 if( rc==SQLITE_OK && exists ){
41045 int locked = 0; /* True if some process holds a RESERVED lock */
41047 /* Race condition here: Another process might have been holding the
41048 ** the RESERVED lock and have a journal open at the sqlite3OsAccess()
41049 ** call above, but then delete the journal and drop the lock before
41050 ** we get to the following sqlite3OsCheckReservedLock() call. If that
41051 ** is the case, this routine might think there is a hot journal when
41052 ** in fact there is none. This results in a false-positive which will
41053 ** be dealt with by the playback routine. Ticket #3883.
41055 rc = sqlite3OsCheckReservedLock(pPager->fd, &locked);
41056 if( rc==SQLITE_OK && !locked ){
41057 Pgno nPage; /* Number of pages in database file */
41059 /* Check the size of the database file. If it consists of 0 pages,
41060 ** then delete the journal file. See the header comment above for
41061 ** the reasoning here. Delete the obsolete journal file under
41062 ** a RESERVED lock to avoid race conditions and to avoid violating
41063 ** [H33020].
41065 rc = pagerPagecount(pPager, &nPage);
41066 if( rc==SQLITE_OK ){
41067 if( nPage==0 ){
41068 sqlite3BeginBenignMalloc();
41069 if( pagerLockDb(pPager, RESERVED_LOCK)==SQLITE_OK ){
41070 sqlite3OsDelete(pVfs, pPager->zJournal, 0);
41071 if( !pPager->exclusiveMode ) pagerUnlockDb(pPager, SHARED_LOCK);
41073 sqlite3EndBenignMalloc();
41074 }else{
41075 /* The journal file exists and no other connection has a reserved
41076 ** or greater lock on the database file. Now check that there is
41077 ** at least one non-zero bytes at the start of the journal file.
41078 ** If there is, then we consider this journal to be hot. If not,
41079 ** it can be ignored.
41081 if( !jrnlOpen ){
41082 int f = SQLITE_OPEN_READONLY|SQLITE_OPEN_MAIN_JOURNAL;
41083 rc = sqlite3OsOpen(pVfs, pPager->zJournal, pPager->jfd, f, &f);
41085 if( rc==SQLITE_OK ){
41086 u8 first = 0;
41087 rc = sqlite3OsRead(pPager->jfd, (void *)&first, 1, 0);
41088 if( rc==SQLITE_IOERR_SHORT_READ ){
41089 rc = SQLITE_OK;
41091 if( !jrnlOpen ){
41092 sqlite3OsClose(pPager->jfd);
41094 *pExists = (first!=0);
41095 }else if( rc==SQLITE_CANTOPEN ){
41096 /* If we cannot open the rollback journal file in order to see if
41097 ** its has a zero header, that might be due to an I/O error, or
41098 ** it might be due to the race condition described above and in
41099 ** ticket #3883. Either way, assume that the journal is hot.
41100 ** This might be a false positive. But if it is, then the
41101 ** automatic journal playback and recovery mechanism will deal
41102 ** with it under an EXCLUSIVE lock where we do not need to
41103 ** worry so much with race conditions.
41105 *pExists = 1;
41106 rc = SQLITE_OK;
41113 return rc;
41117 ** This function is called to obtain a shared lock on the database file.
41118 ** It is illegal to call sqlite3PagerAcquire() until after this function
41119 ** has been successfully called. If a shared-lock is already held when
41120 ** this function is called, it is a no-op.
41122 ** The following operations are also performed by this function.
41124 ** 1) If the pager is currently in PAGER_OPEN state (no lock held
41125 ** on the database file), then an attempt is made to obtain a
41126 ** SHARED lock on the database file. Immediately after obtaining
41127 ** the SHARED lock, the file-system is checked for a hot-journal,
41128 ** which is played back if present. Following any hot-journal
41129 ** rollback, the contents of the cache are validated by checking
41130 ** the 'change-counter' field of the database file header and
41131 ** discarded if they are found to be invalid.
41133 ** 2) If the pager is running in exclusive-mode, and there are currently
41134 ** no outstanding references to any pages, and is in the error state,
41135 ** then an attempt is made to clear the error state by discarding
41136 ** the contents of the page cache and rolling back any open journal
41137 ** file.
41139 ** If everything is successful, SQLITE_OK is returned. If an IO error
41140 ** occurs while locking the database, checking for a hot-journal file or
41141 ** rolling back a journal file, the IO error code is returned.
41143 SQLITE_PRIVATE int sqlite3PagerSharedLock(Pager *pPager){
41144 int rc = SQLITE_OK; /* Return code */
41146 /* This routine is only called from b-tree and only when there are no
41147 ** outstanding pages. This implies that the pager state should either
41148 ** be OPEN or READER. READER is only possible if the pager is or was in
41149 ** exclusive access mode.
41151 assert( sqlite3PcacheRefCount(pPager->pPCache)==0 );
41152 assert( assert_pager_state(pPager) );
41153 assert( pPager->eState==PAGER_OPEN || pPager->eState==PAGER_READER );
41154 if( NEVER(MEMDB && pPager->errCode) ){ return pPager->errCode; }
41156 if( !pagerUseWal(pPager) && pPager->eState==PAGER_OPEN ){
41157 int bHotJournal = 1; /* True if there exists a hot journal-file */
41159 assert( !MEMDB );
41160 assert( pPager->noReadlock==0 || pPager->readOnly );
41162 if( pPager->noReadlock==0 ){
41163 rc = pager_wait_on_lock(pPager, SHARED_LOCK);
41164 if( rc!=SQLITE_OK ){
41165 assert( pPager->eLock==NO_LOCK || pPager->eLock==UNKNOWN_LOCK );
41166 goto failed;
41170 /* If a journal file exists, and there is no RESERVED lock on the
41171 ** database file, then it either needs to be played back or deleted.
41173 if( pPager->eLock<=SHARED_LOCK ){
41174 rc = hasHotJournal(pPager, &bHotJournal);
41176 if( rc!=SQLITE_OK ){
41177 goto failed;
41179 if( bHotJournal ){
41180 /* Get an EXCLUSIVE lock on the database file. At this point it is
41181 ** important that a RESERVED lock is not obtained on the way to the
41182 ** EXCLUSIVE lock. If it were, another process might open the
41183 ** database file, detect the RESERVED lock, and conclude that the
41184 ** database is safe to read while this process is still rolling the
41185 ** hot-journal back.
41187 ** Because the intermediate RESERVED lock is not requested, any
41188 ** other process attempting to access the database file will get to
41189 ** this point in the code and fail to obtain its own EXCLUSIVE lock
41190 ** on the database file.
41192 ** Unless the pager is in locking_mode=exclusive mode, the lock is
41193 ** downgraded to SHARED_LOCK before this function returns.
41195 rc = pagerLockDb(pPager, EXCLUSIVE_LOCK);
41196 if( rc!=SQLITE_OK ){
41197 goto failed;
41200 /* If it is not already open and the file exists on disk, open the
41201 ** journal for read/write access. Write access is required because
41202 ** in exclusive-access mode the file descriptor will be kept open
41203 ** and possibly used for a transaction later on. Also, write-access
41204 ** is usually required to finalize the journal in journal_mode=persist
41205 ** mode (and also for journal_mode=truncate on some systems).
41207 ** If the journal does not exist, it usually means that some
41208 ** other connection managed to get in and roll it back before
41209 ** this connection obtained the exclusive lock above. Or, it
41210 ** may mean that the pager was in the error-state when this
41211 ** function was called and the journal file does not exist.
41213 if( !isOpen(pPager->jfd) ){
41214 sqlite3_vfs * const pVfs = pPager->pVfs;
41215 int bExists; /* True if journal file exists */
41216 rc = sqlite3OsAccess(
41217 pVfs, pPager->zJournal, SQLITE_ACCESS_EXISTS, &bExists);
41218 if( rc==SQLITE_OK && bExists ){
41219 int fout = 0;
41220 int f = SQLITE_OPEN_READWRITE|SQLITE_OPEN_MAIN_JOURNAL;
41221 assert( !pPager->tempFile );
41222 rc = sqlite3OsOpen(pVfs, pPager->zJournal, pPager->jfd, f, &fout);
41223 assert( rc!=SQLITE_OK || isOpen(pPager->jfd) );
41224 if( rc==SQLITE_OK && fout&SQLITE_OPEN_READONLY ){
41225 rc = SQLITE_CANTOPEN_BKPT;
41226 sqlite3OsClose(pPager->jfd);
41231 /* Playback and delete the journal. Drop the database write
41232 ** lock and reacquire the read lock. Purge the cache before
41233 ** playing back the hot-journal so that we don't end up with
41234 ** an inconsistent cache. Sync the hot journal before playing
41235 ** it back since the process that crashed and left the hot journal
41236 ** probably did not sync it and we are required to always sync
41237 ** the journal before playing it back.
41239 if( isOpen(pPager->jfd) ){
41240 assert( rc==SQLITE_OK );
41241 rc = pagerSyncHotJournal(pPager);
41242 if( rc==SQLITE_OK ){
41243 rc = pager_playback(pPager, 1);
41244 pPager->eState = PAGER_OPEN;
41246 }else if( !pPager->exclusiveMode ){
41247 pagerUnlockDb(pPager, SHARED_LOCK);
41250 if( rc!=SQLITE_OK ){
41251 /* This branch is taken if an error occurs while trying to open
41252 ** or roll back a hot-journal while holding an EXCLUSIVE lock. The
41253 ** pager_unlock() routine will be called before returning to unlock
41254 ** the file. If the unlock attempt fails, then Pager.eLock must be
41255 ** set to UNKNOWN_LOCK (see the comment above the #define for
41256 ** UNKNOWN_LOCK above for an explanation).
41258 ** In order to get pager_unlock() to do this, set Pager.eState to
41259 ** PAGER_ERROR now. This is not actually counted as a transition
41260 ** to ERROR state in the state diagram at the top of this file,
41261 ** since we know that the same call to pager_unlock() will very
41262 ** shortly transition the pager object to the OPEN state. Calling
41263 ** assert_pager_state() would fail now, as it should not be possible
41264 ** to be in ERROR state when there are zero outstanding page
41265 ** references.
41267 pager_error(pPager, rc);
41268 goto failed;
41271 assert( pPager->eState==PAGER_OPEN );
41272 assert( (pPager->eLock==SHARED_LOCK)
41273 || (pPager->exclusiveMode && pPager->eLock>SHARED_LOCK)
41277 if( !pPager->tempFile
41278 && (pPager->pBackup || sqlite3PcachePagecount(pPager->pPCache)>0)
41280 /* The shared-lock has just been acquired on the database file
41281 ** and there are already pages in the cache (from a previous
41282 ** read or write transaction). Check to see if the database
41283 ** has been modified. If the database has changed, flush the
41284 ** cache.
41286 ** Database changes is detected by looking at 15 bytes beginning
41287 ** at offset 24 into the file. The first 4 of these 16 bytes are
41288 ** a 32-bit counter that is incremented with each change. The
41289 ** other bytes change randomly with each file change when
41290 ** a codec is in use.
41292 ** There is a vanishingly small chance that a change will not be
41293 ** detected. The chance of an undetected change is so small that
41294 ** it can be neglected.
41296 Pgno nPage = 0;
41297 char dbFileVers[sizeof(pPager->dbFileVers)];
41299 rc = pagerPagecount(pPager, &nPage);
41300 if( rc ) goto failed;
41302 if( nPage>0 ){
41303 IOTRACE(("CKVERS %p %d\n", pPager, sizeof(dbFileVers)));
41304 rc = sqlite3OsRead(pPager->fd, &dbFileVers, sizeof(dbFileVers), 24);
41305 if( rc!=SQLITE_OK ){
41306 goto failed;
41308 }else{
41309 memset(dbFileVers, 0, sizeof(dbFileVers));
41312 if( memcmp(pPager->dbFileVers, dbFileVers, sizeof(dbFileVers))!=0 ){
41313 pager_reset(pPager);
41317 /* If there is a WAL file in the file-system, open this database in WAL
41318 ** mode. Otherwise, the following function call is a no-op.
41320 rc = pagerOpenWalIfPresent(pPager);
41321 #ifndef SQLITE_OMIT_WAL
41322 assert( pPager->pWal==0 || rc==SQLITE_OK );
41323 #endif
41326 if( pagerUseWal(pPager) ){
41327 assert( rc==SQLITE_OK );
41328 rc = pagerBeginReadTransaction(pPager);
41331 if( pPager->eState==PAGER_OPEN && rc==SQLITE_OK ){
41332 rc = pagerPagecount(pPager, &pPager->dbSize);
41335 failed:
41336 if( rc!=SQLITE_OK ){
41337 assert( !MEMDB );
41338 pager_unlock(pPager);
41339 assert( pPager->eState==PAGER_OPEN );
41340 }else{
41341 pPager->eState = PAGER_READER;
41343 return rc;
41347 ** If the reference count has reached zero, rollback any active
41348 ** transaction and unlock the pager.
41350 ** Except, in locking_mode=EXCLUSIVE when there is nothing to in
41351 ** the rollback journal, the unlock is not performed and there is
41352 ** nothing to rollback, so this routine is a no-op.
41354 static void pagerUnlockIfUnused(Pager *pPager){
41355 if( (sqlite3PcacheRefCount(pPager->pPCache)==0) ){
41356 pagerUnlockAndRollback(pPager);
41361 ** Acquire a reference to page number pgno in pager pPager (a page
41362 ** reference has type DbPage*). If the requested reference is
41363 ** successfully obtained, it is copied to *ppPage and SQLITE_OK returned.
41365 ** If the requested page is already in the cache, it is returned.
41366 ** Otherwise, a new page object is allocated and populated with data
41367 ** read from the database file. In some cases, the pcache module may
41368 ** choose not to allocate a new page object and may reuse an existing
41369 ** object with no outstanding references.
41371 ** The extra data appended to a page is always initialized to zeros the
41372 ** first time a page is loaded into memory. If the page requested is
41373 ** already in the cache when this function is called, then the extra
41374 ** data is left as it was when the page object was last used.
41376 ** If the database image is smaller than the requested page or if a
41377 ** non-zero value is passed as the noContent parameter and the
41378 ** requested page is not already stored in the cache, then no
41379 ** actual disk read occurs. In this case the memory image of the
41380 ** page is initialized to all zeros.
41382 ** If noContent is true, it means that we do not care about the contents
41383 ** of the page. This occurs in two seperate scenarios:
41385 ** a) When reading a free-list leaf page from the database, and
41387 ** b) When a savepoint is being rolled back and we need to load
41388 ** a new page into the cache to be filled with the data read
41389 ** from the savepoint journal.
41391 ** If noContent is true, then the data returned is zeroed instead of
41392 ** being read from the database. Additionally, the bits corresponding
41393 ** to pgno in Pager.pInJournal (bitvec of pages already written to the
41394 ** journal file) and the PagerSavepoint.pInSavepoint bitvecs of any open
41395 ** savepoints are set. This means if the page is made writable at any
41396 ** point in the future, using a call to sqlite3PagerWrite(), its contents
41397 ** will not be journaled. This saves IO.
41399 ** The acquisition might fail for several reasons. In all cases,
41400 ** an appropriate error code is returned and *ppPage is set to NULL.
41402 ** See also sqlite3PagerLookup(). Both this routine and Lookup() attempt
41403 ** to find a page in the in-memory cache first. If the page is not already
41404 ** in memory, this routine goes to disk to read it in whereas Lookup()
41405 ** just returns 0. This routine acquires a read-lock the first time it
41406 ** has to go to disk, and could also playback an old journal if necessary.
41407 ** Since Lookup() never goes to disk, it never has to deal with locks
41408 ** or journal files.
41410 SQLITE_PRIVATE int sqlite3PagerAcquire(
41411 Pager *pPager, /* The pager open on the database file */
41412 Pgno pgno, /* Page number to fetch */
41413 DbPage **ppPage, /* Write a pointer to the page here */
41414 int noContent /* Do not bother reading content from disk if true */
41416 /* This just passes through to our modified version with NULL data. */
41417 return sqlite3PagerAcquire2(pPager, pgno, ppPage, noContent, 0);
41421 ** This is an internal version of sqlite3PagerAcquire that takes an extra
41422 ** parameter of data to use to fill the page with. This allows more efficient
41423 ** filling for preloaded data. If this extra parameter is NULL, we'll go to
41424 ** the file.
41426 ** See sqlite3PagerLoadall which uses this function.
41428 SQLITE_PRIVATE int sqlite3PagerAcquire2(
41429 Pager *pPager, /* The pager open on the database file */
41430 Pgno pgno, /* Page number to fetch */
41431 DbPage **ppPage, /* Write a pointer to the page here */
41432 int noContent, /* Do not bother reading content from disk if true */
41433 unsigned char* pDataToFill
41435 int rc;
41436 PgHdr *pPg;
41438 assert( pPager->eState>=PAGER_READER );
41439 assert( assert_pager_state(pPager) );
41441 if( pgno==0 ){
41442 return SQLITE_CORRUPT_BKPT;
41445 /* If the pager is in the error state, return an error immediately.
41446 ** Otherwise, request the page from the PCache layer. */
41447 if( pPager->errCode!=SQLITE_OK ){
41448 rc = pPager->errCode;
41449 }else{
41450 rc = sqlite3PcacheFetch(pPager->pPCache, pgno, 1, ppPage);
41453 if( rc!=SQLITE_OK ){
41454 /* Either the call to sqlite3PcacheFetch() returned an error or the
41455 ** pager was already in the error-state when this function was called.
41456 ** Set pPg to 0 and jump to the exception handler. */
41457 pPg = 0;
41458 goto pager_acquire_err;
41460 assert( (*ppPage)->pgno==pgno );
41461 assert( (*ppPage)->pPager==pPager || (*ppPage)->pPager==0 );
41463 if( (*ppPage)->pPager && !noContent ){
41464 /* In this case the pcache already contains an initialized copy of
41465 ** the page. Return without further ado. */
41466 assert( pgno<=PAGER_MAX_PGNO && pgno!=PAGER_MJ_PGNO(pPager) );
41467 PAGER_INCR(pPager->nHit);
41468 return SQLITE_OK;
41470 }else{
41471 /* The pager cache has created a new page. Its content needs to
41472 ** be initialized. */
41474 PAGER_INCR(pPager->nMiss);
41475 pPg = *ppPage;
41476 pPg->pPager = pPager;
41478 /* The maximum page number is 2^31. Return SQLITE_CORRUPT if a page
41479 ** number greater than this, or the unused locking-page, is requested. */
41480 if( pgno>PAGER_MAX_PGNO || pgno==PAGER_MJ_PGNO(pPager) ){
41481 rc = SQLITE_CORRUPT_BKPT;
41482 goto pager_acquire_err;
41485 if( MEMDB || pPager->dbSize<pgno || noContent || !isOpen(pPager->fd) ){
41486 if( pgno>pPager->mxPgno ){
41487 rc = SQLITE_FULL;
41488 goto pager_acquire_err;
41490 if( noContent ){
41491 /* Failure to set the bits in the InJournal bit-vectors is benign.
41492 ** It merely means that we might do some extra work to journal a
41493 ** page that does not need to be journaled. Nevertheless, be sure
41494 ** to test the case where a malloc error occurs while trying to set
41495 ** a bit in a bit vector.
41497 sqlite3BeginBenignMalloc();
41498 if( pgno<=pPager->dbOrigSize ){
41499 TESTONLY( rc = ) sqlite3BitvecSet(pPager->pInJournal, pgno);
41500 testcase( rc==SQLITE_NOMEM );
41502 TESTONLY( rc = ) addToSavepointBitvecs(pPager, pgno);
41503 testcase( rc==SQLITE_NOMEM );
41504 sqlite3EndBenignMalloc();
41506 memset(pPg->pData, 0, pPager->pageSize);
41507 IOTRACE(("ZERO %p %d\n", pPager, pgno));
41508 }else{
41509 assert( pPg->pPager==pPager );
41510 if( pDataToFill ){
41511 /* Just copy from the given memory */
41512 memcpy(pPg->pData, pDataToFill, pPager->pageSize);
41513 CODEC1(pPager, pPg->pData, pPg->pgno, 3, rc = SQLITE_NOMEM;
41514 goto pager_acquire_err);
41515 }else{
41516 /* Load from disk (old regular sqlite code path) */
41517 rc = readDbPage(pPg);
41518 if( rc!=SQLITE_OK ){
41519 goto pager_acquire_err;
41523 pager_set_pagehash(pPg);
41526 return SQLITE_OK;
41528 pager_acquire_err:
41529 assert( rc!=SQLITE_OK );
41530 if( pPg ){
41531 sqlite3PcacheDrop(pPg);
41533 pagerUnlockIfUnused(pPager);
41535 *ppPage = 0;
41536 return rc;
41540 ** Acquire a page if it is already in the in-memory cache. Do
41541 ** not read the page from disk. Return a pointer to the page,
41542 ** or 0 if the page is not in cache.
41544 ** See also sqlite3PagerGet(). The difference between this routine
41545 ** and sqlite3PagerGet() is that _get() will go to the disk and read
41546 ** in the page if the page is not already in cache. This routine
41547 ** returns NULL if the page is not in cache or if a disk I/O error
41548 ** has ever happened.
41550 SQLITE_PRIVATE DbPage *sqlite3PagerLookup(Pager *pPager, Pgno pgno){
41551 PgHdr *pPg = 0;
41552 assert( pPager!=0 );
41553 assert( pgno!=0 );
41554 assert( pPager->pPCache!=0 );
41555 assert( pPager->eState>=PAGER_READER && pPager->eState!=PAGER_ERROR );
41556 sqlite3PcacheFetch(pPager->pPCache, pgno, 0, &pPg);
41557 return pPg;
41561 ** Release a page reference.
41563 ** If the number of references to the page drop to zero, then the
41564 ** page is added to the LRU list. When all references to all pages
41565 ** are released, a rollback occurs and the lock on the database is
41566 ** removed.
41568 SQLITE_PRIVATE void sqlite3PagerUnref(DbPage *pPg){
41569 if( pPg ){
41570 Pager *pPager = pPg->pPager;
41571 sqlite3PcacheRelease(pPg);
41572 pagerUnlockIfUnused(pPager);
41576 #if defined(__APPLE__)
41578 ** Create and return a CFURLRef given a cstring containing the path to a file.
41580 static CFURLRef create_cfurl_from_cstring(const char* filePath){
41581 CFStringRef urlString = CFStringCreateWithFileSystemRepresentation(
41582 kCFAllocatorDefault, filePath);
41583 CFURLRef urlRef = CFURLCreateWithFileSystemPath(kCFAllocatorDefault,
41584 urlString, kCFURLPOSIXPathStyle, FALSE);
41585 CFRelease(urlString);
41586 return urlRef;
41588 #endif
41591 ** This function is called at the start of every write transaction.
41592 ** There must already be a RESERVED or EXCLUSIVE lock on the database
41593 ** file when this routine is called.
41595 ** Open the journal file for pager pPager and write a journal header
41596 ** to the start of it. If there are active savepoints, open the sub-journal
41597 ** as well. This function is only used when the journal file is being
41598 ** opened to write a rollback log for a transaction. It is not used
41599 ** when opening a hot journal file to roll it back.
41601 ** If the journal file is already open (as it may be in exclusive mode),
41602 ** then this function just writes a journal header to the start of the
41603 ** already open file.
41605 ** Whether or not the journal file is opened by this function, the
41606 ** Pager.pInJournal bitvec structure is allocated.
41608 ** Return SQLITE_OK if everything is successful. Otherwise, return
41609 ** SQLITE_NOMEM if the attempt to allocate Pager.pInJournal fails, or
41610 ** an IO error code if opening or writing the journal file fails.
41612 static int pager_open_journal(Pager *pPager){
41613 int rc = SQLITE_OK; /* Return code */
41614 sqlite3_vfs * const pVfs = pPager->pVfs; /* Local cache of vfs pointer */
41616 assert( pPager->eState==PAGER_WRITER_LOCKED );
41617 assert( assert_pager_state(pPager) );
41618 assert( pPager->pInJournal==0 );
41620 /* If already in the error state, this function is a no-op. But on
41621 ** the other hand, this routine is never called if we are already in
41622 ** an error state. */
41623 if( NEVER(pPager->errCode) ) return pPager->errCode;
41625 if( !pagerUseWal(pPager) && pPager->journalMode!=PAGER_JOURNALMODE_OFF ){
41626 pPager->pInJournal = sqlite3BitvecCreate(pPager->dbSize);
41627 if( pPager->pInJournal==0 ){
41628 return SQLITE_NOMEM;
41631 /* Open the journal file if it is not already open. */
41632 if( !isOpen(pPager->jfd) ){
41633 if( pPager->journalMode==PAGER_JOURNALMODE_MEMORY ){
41634 sqlite3MemJournalOpen(pPager->jfd);
41635 }else{
41636 const int flags = /* VFS flags to open journal file */
41637 SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|
41638 (pPager->tempFile ?
41639 (SQLITE_OPEN_DELETEONCLOSE|SQLITE_OPEN_TEMP_JOURNAL):
41640 (SQLITE_OPEN_MAIN_JOURNAL)
41642 #ifdef SQLITE_ENABLE_ATOMIC_WRITE
41643 rc = sqlite3JournalOpen(
41644 pVfs, pPager->zJournal, pPager->jfd, flags, jrnlBufferSize(pPager)
41646 #else
41647 rc = sqlite3OsOpen(pVfs, pPager->zJournal, pPager->jfd, flags, 0);
41648 #endif
41649 #if defined(__APPLE__)
41650 /* Set the TimeMachine exclusion metadata for the journal if it has
41651 ** been set for the database. Only do this for unix-type vfs
41652 ** implementations. */
41653 if( rc==SQLITE_OK && pPager->zFilename!=NULL
41654 && strlen(pPager->zFilename)>0
41655 && strncmp(pVfs->zName, "unix", 4)==0
41656 && ( pVfs->zName[4]=='-' || pVfs->zName[4]=='\0' ) ){
41657 CFURLRef database = create_cfurl_from_cstring(pPager->zFilename);
41658 if( CSBackupIsItemExcluded(database, NULL) ){
41659 CFURLRef journal = create_cfurl_from_cstring(pPager->zJournal);
41660 /* Ignore errors from the following exclusion call. */
41661 CSBackupSetItemExcluded(journal, TRUE, FALSE);
41662 CFRelease(journal);
41664 CFRelease(database);
41666 #endif
41668 assert( rc!=SQLITE_OK || isOpen(pPager->jfd) );
41672 /* Write the first journal header to the journal file and open
41673 ** the sub-journal if necessary.
41675 if( rc==SQLITE_OK ){
41676 /* TODO: Check if all of these are really required. */
41677 pPager->nRec = 0;
41678 pPager->journalOff = 0;
41679 pPager->setMaster = 0;
41680 pPager->journalHdr = 0;
41681 rc = writeJournalHdr(pPager);
41685 if( rc!=SQLITE_OK ){
41686 sqlite3BitvecDestroy(pPager->pInJournal);
41687 pPager->pInJournal = 0;
41688 }else{
41689 assert( pPager->eState==PAGER_WRITER_LOCKED );
41690 pPager->eState = PAGER_WRITER_CACHEMOD;
41693 return rc;
41697 ** Begin a write-transaction on the specified pager object. If a
41698 ** write-transaction has already been opened, this function is a no-op.
41700 ** If the exFlag argument is false, then acquire at least a RESERVED
41701 ** lock on the database file. If exFlag is true, then acquire at least
41702 ** an EXCLUSIVE lock. If such a lock is already held, no locking
41703 ** functions need be called.
41705 ** If the subjInMemory argument is non-zero, then any sub-journal opened
41706 ** within this transaction will be opened as an in-memory file. This
41707 ** has no effect if the sub-journal is already opened (as it may be when
41708 ** running in exclusive mode) or if the transaction does not require a
41709 ** sub-journal. If the subjInMemory argument is zero, then any required
41710 ** sub-journal is implemented in-memory if pPager is an in-memory database,
41711 ** or using a temporary file otherwise.
41713 SQLITE_PRIVATE int sqlite3PagerBegin(Pager *pPager, int exFlag, int subjInMemory){
41714 int rc = SQLITE_OK;
41716 if( pPager->errCode ) return pPager->errCode;
41717 assert( pPager->eState>=PAGER_READER && pPager->eState<PAGER_ERROR );
41718 pPager->subjInMemory = (u8)subjInMemory;
41720 if( ALWAYS(pPager->eState==PAGER_READER) ){
41721 assert( pPager->pInJournal==0 );
41723 if( pagerUseWal(pPager) ){
41724 /* If the pager is configured to use locking_mode=exclusive, and an
41725 ** exclusive lock on the database is not already held, obtain it now.
41727 if( pPager->exclusiveMode && sqlite3WalExclusiveMode(pPager->pWal, -1) ){
41728 rc = pagerLockDb(pPager, EXCLUSIVE_LOCK);
41729 if( rc!=SQLITE_OK ){
41730 return rc;
41732 sqlite3WalExclusiveMode(pPager->pWal, 1);
41735 /* Grab the write lock on the log file. If successful, upgrade to
41736 ** PAGER_RESERVED state. Otherwise, return an error code to the caller.
41737 ** The busy-handler is not invoked if another connection already
41738 ** holds the write-lock. If possible, the upper layer will call it.
41740 rc = sqlite3WalBeginWriteTransaction(pPager->pWal);
41741 }else{
41742 /* Obtain a RESERVED lock on the database file. If the exFlag parameter
41743 ** is true, then immediately upgrade this to an EXCLUSIVE lock. The
41744 ** busy-handler callback can be used when upgrading to the EXCLUSIVE
41745 ** lock, but not when obtaining the RESERVED lock.
41747 rc = pagerLockDb(pPager, RESERVED_LOCK);
41748 if( rc==SQLITE_OK && exFlag ){
41749 rc = pager_wait_on_lock(pPager, EXCLUSIVE_LOCK);
41753 if( rc==SQLITE_OK ){
41754 /* Change to WRITER_LOCKED state.
41756 ** WAL mode sets Pager.eState to PAGER_WRITER_LOCKED or CACHEMOD
41757 ** when it has an open transaction, but never to DBMOD or FINISHED.
41758 ** This is because in those states the code to roll back savepoint
41759 ** transactions may copy data from the sub-journal into the database
41760 ** file as well as into the page cache. Which would be incorrect in
41761 ** WAL mode.
41763 pPager->eState = PAGER_WRITER_LOCKED;
41764 pPager->dbHintSize = pPager->dbSize;
41765 pPager->dbFileSize = pPager->dbSize;
41766 pPager->dbOrigSize = pPager->dbSize;
41767 pPager->journalOff = 0;
41770 assert( rc==SQLITE_OK || pPager->eState==PAGER_READER );
41771 assert( rc!=SQLITE_OK || pPager->eState==PAGER_WRITER_LOCKED );
41772 assert( assert_pager_state(pPager) );
41775 PAGERTRACE(("TRANSACTION %d\n", PAGERID(pPager)));
41776 return rc;
41780 ** Mark a single data page as writeable. The page is written into the
41781 ** main journal or sub-journal as required. If the page is written into
41782 ** one of the journals, the corresponding bit is set in the
41783 ** Pager.pInJournal bitvec and the PagerSavepoint.pInSavepoint bitvecs
41784 ** of any open savepoints as appropriate.
41786 static int pager_write(PgHdr *pPg){
41787 void *pData = pPg->pData;
41788 Pager *pPager = pPg->pPager;
41789 int rc = SQLITE_OK;
41791 /* This routine is not called unless a write-transaction has already
41792 ** been started. The journal file may or may not be open at this point.
41793 ** It is never called in the ERROR state.
41795 assert( pPager->eState==PAGER_WRITER_LOCKED
41796 || pPager->eState==PAGER_WRITER_CACHEMOD
41797 || pPager->eState==PAGER_WRITER_DBMOD
41799 assert( assert_pager_state(pPager) );
41801 /* If an error has been previously detected, report the same error
41802 ** again. This should not happen, but the check provides robustness. */
41803 if( NEVER(pPager->errCode) ) return pPager->errCode;
41805 /* Higher-level routines never call this function if database is not
41806 ** writable. But check anyway, just for robustness. */
41807 if( NEVER(pPager->readOnly) ) return SQLITE_PERM;
41809 CHECK_PAGE(pPg);
41811 /* The journal file needs to be opened. Higher level routines have already
41812 ** obtained the necessary locks to begin the write-transaction, but the
41813 ** rollback journal might not yet be open. Open it now if this is the case.
41815 ** This is done before calling sqlite3PcacheMakeDirty() on the page.
41816 ** Otherwise, if it were done after calling sqlite3PcacheMakeDirty(), then
41817 ** an error might occur and the pager would end up in WRITER_LOCKED state
41818 ** with pages marked as dirty in the cache.
41820 if( pPager->eState==PAGER_WRITER_LOCKED ){
41821 rc = pager_open_journal(pPager);
41822 if( rc!=SQLITE_OK ) return rc;
41824 assert( pPager->eState>=PAGER_WRITER_CACHEMOD );
41825 assert( assert_pager_state(pPager) );
41827 /* Mark the page as dirty. If the page has already been written
41828 ** to the journal then we can return right away.
41830 sqlite3PcacheMakeDirty(pPg);
41831 if( pageInJournal(pPg) && !subjRequiresPage(pPg) ){
41832 assert( !pagerUseWal(pPager) );
41833 }else{
41835 /* The transaction journal now exists and we have a RESERVED or an
41836 ** EXCLUSIVE lock on the main database file. Write the current page to
41837 ** the transaction journal if it is not there already.
41839 if( !pageInJournal(pPg) && !pagerUseWal(pPager) ){
41840 assert( pagerUseWal(pPager)==0 );
41841 if( pPg->pgno<=pPager->dbOrigSize && isOpen(pPager->jfd) ){
41842 u32 cksum;
41843 char *pData2;
41844 i64 iOff = pPager->journalOff;
41846 /* We should never write to the journal file the page that
41847 ** contains the database locks. The following assert verifies
41848 ** that we do not. */
41849 assert( pPg->pgno!=PAGER_MJ_PGNO(pPager) );
41851 assert( pPager->journalHdr<=pPager->journalOff );
41852 CODEC2(pPager, pData, pPg->pgno, 7, return SQLITE_NOMEM, pData2);
41853 cksum = pager_cksum(pPager, (u8*)pData2);
41855 /* Even if an IO or diskfull error occurs while journalling the
41856 ** page in the block above, set the need-sync flag for the page.
41857 ** Otherwise, when the transaction is rolled back, the logic in
41858 ** playback_one_page() will think that the page needs to be restored
41859 ** in the database file. And if an IO error occurs while doing so,
41860 ** then corruption may follow.
41862 pPg->flags |= PGHDR_NEED_SYNC;
41864 rc = write32bits(pPager->jfd, iOff, pPg->pgno);
41865 if( rc!=SQLITE_OK ) return rc;
41866 rc = sqlite3OsWrite(pPager->jfd, pData2, pPager->pageSize, iOff+4);
41867 if( rc!=SQLITE_OK ) return rc;
41868 rc = write32bits(pPager->jfd, iOff+pPager->pageSize+4, cksum);
41869 if( rc!=SQLITE_OK ) return rc;
41871 IOTRACE(("JOUT %p %d %lld %d\n", pPager, pPg->pgno,
41872 pPager->journalOff, pPager->pageSize));
41873 PAGER_INCR(sqlite3_pager_writej_count);
41874 PAGERTRACE(("JOURNAL %d page %d needSync=%d hash(%08x)\n",
41875 PAGERID(pPager), pPg->pgno,
41876 ((pPg->flags&PGHDR_NEED_SYNC)?1:0), pager_pagehash(pPg)));
41878 pPager->journalOff += 8 + pPager->pageSize;
41879 pPager->nRec++;
41880 assert( pPager->pInJournal!=0 );
41881 rc = sqlite3BitvecSet(pPager->pInJournal, pPg->pgno);
41882 testcase( rc==SQLITE_NOMEM );
41883 assert( rc==SQLITE_OK || rc==SQLITE_NOMEM );
41884 rc |= addToSavepointBitvecs(pPager, pPg->pgno);
41885 if( rc!=SQLITE_OK ){
41886 assert( rc==SQLITE_NOMEM );
41887 return rc;
41889 }else{
41890 if( pPager->eState!=PAGER_WRITER_DBMOD ){
41891 pPg->flags |= PGHDR_NEED_SYNC;
41893 PAGERTRACE(("APPEND %d page %d needSync=%d\n",
41894 PAGERID(pPager), pPg->pgno,
41895 ((pPg->flags&PGHDR_NEED_SYNC)?1:0)));
41899 /* If the statement journal is open and the page is not in it,
41900 ** then write the current page to the statement journal. Note that
41901 ** the statement journal format differs from the standard journal format
41902 ** in that it omits the checksums and the header.
41904 if( subjRequiresPage(pPg) ){
41905 rc = subjournalPage(pPg);
41909 /* Update the database size and return.
41911 if( pPager->dbSize<pPg->pgno ){
41912 pPager->dbSize = pPg->pgno;
41914 return rc;
41918 ** Mark a data page as writeable. This routine must be called before
41919 ** making changes to a page. The caller must check the return value
41920 ** of this function and be careful not to change any page data unless
41921 ** this routine returns SQLITE_OK.
41923 ** The difference between this function and pager_write() is that this
41924 ** function also deals with the special case where 2 or more pages
41925 ** fit on a single disk sector. In this case all co-resident pages
41926 ** must have been written to the journal file before returning.
41928 ** If an error occurs, SQLITE_NOMEM or an IO error code is returned
41929 ** as appropriate. Otherwise, SQLITE_OK.
41931 SQLITE_PRIVATE int sqlite3PagerWrite(DbPage *pDbPage){
41932 int rc = SQLITE_OK;
41934 PgHdr *pPg = pDbPage;
41935 Pager *pPager = pPg->pPager;
41936 Pgno nPagePerSector = (pPager->sectorSize/pPager->pageSize);
41938 assert( pPager->eState>=PAGER_WRITER_LOCKED );
41939 assert( pPager->eState!=PAGER_ERROR );
41940 assert( assert_pager_state(pPager) );
41942 if( nPagePerSector>1 ){
41943 Pgno nPageCount; /* Total number of pages in database file */
41944 Pgno pg1; /* First page of the sector pPg is located on. */
41945 int nPage = 0; /* Number of pages starting at pg1 to journal */
41946 int ii; /* Loop counter */
41947 int needSync = 0; /* True if any page has PGHDR_NEED_SYNC */
41949 /* Set the doNotSyncSpill flag to 1. This is because we cannot allow
41950 ** a journal header to be written between the pages journaled by
41951 ** this function.
41953 assert( !MEMDB );
41954 assert( pPager->doNotSyncSpill==0 );
41955 pPager->doNotSyncSpill++;
41957 /* This trick assumes that both the page-size and sector-size are
41958 ** an integer power of 2. It sets variable pg1 to the identifier
41959 ** of the first page of the sector pPg is located on.
41961 pg1 = ((pPg->pgno-1) & ~(nPagePerSector-1)) + 1;
41963 nPageCount = pPager->dbSize;
41964 if( pPg->pgno>nPageCount ){
41965 nPage = (pPg->pgno - pg1)+1;
41966 }else if( (pg1+nPagePerSector-1)>nPageCount ){
41967 nPage = nPageCount+1-pg1;
41968 }else{
41969 nPage = nPagePerSector;
41971 assert(nPage>0);
41972 assert(pg1<=pPg->pgno);
41973 assert((pg1+nPage)>pPg->pgno);
41975 for(ii=0; ii<nPage && rc==SQLITE_OK; ii++){
41976 Pgno pg = pg1+ii;
41977 PgHdr *pPage;
41978 if( pg==pPg->pgno || !sqlite3BitvecTest(pPager->pInJournal, pg) ){
41979 if( pg!=PAGER_MJ_PGNO(pPager) ){
41980 rc = sqlite3PagerGet(pPager, pg, &pPage);
41981 if( rc==SQLITE_OK ){
41982 rc = pager_write(pPage);
41983 if( pPage->flags&PGHDR_NEED_SYNC ){
41984 needSync = 1;
41986 sqlite3PagerUnref(pPage);
41989 }else if( (pPage = pager_lookup(pPager, pg))!=0 ){
41990 if( pPage->flags&PGHDR_NEED_SYNC ){
41991 needSync = 1;
41993 sqlite3PagerUnref(pPage);
41997 /* If the PGHDR_NEED_SYNC flag is set for any of the nPage pages
41998 ** starting at pg1, then it needs to be set for all of them. Because
41999 ** writing to any of these nPage pages may damage the others, the
42000 ** journal file must contain sync()ed copies of all of them
42001 ** before any of them can be written out to the database file.
42003 if( rc==SQLITE_OK && needSync ){
42004 assert( !MEMDB );
42005 for(ii=0; ii<nPage; ii++){
42006 PgHdr *pPage = pager_lookup(pPager, pg1+ii);
42007 if( pPage ){
42008 pPage->flags |= PGHDR_NEED_SYNC;
42009 sqlite3PagerUnref(pPage);
42014 assert( pPager->doNotSyncSpill==1 );
42015 pPager->doNotSyncSpill--;
42016 }else{
42017 rc = pager_write(pDbPage);
42019 return rc;
42023 ** Return TRUE if the page given in the argument was previously passed
42024 ** to sqlite3PagerWrite(). In other words, return TRUE if it is ok
42025 ** to change the content of the page.
42027 #ifndef NDEBUG
42028 SQLITE_PRIVATE int sqlite3PagerIswriteable(DbPage *pPg){
42029 return pPg->flags&PGHDR_DIRTY;
42031 #endif
42034 ** A call to this routine tells the pager that it is not necessary to
42035 ** write the information on page pPg back to the disk, even though
42036 ** that page might be marked as dirty. This happens, for example, when
42037 ** the page has been added as a leaf of the freelist and so its
42038 ** content no longer matters.
42040 ** The overlying software layer calls this routine when all of the data
42041 ** on the given page is unused. The pager marks the page as clean so
42042 ** that it does not get written to disk.
42044 ** Tests show that this optimization can quadruple the speed of large
42045 ** DELETE operations.
42047 SQLITE_PRIVATE void sqlite3PagerDontWrite(PgHdr *pPg){
42048 Pager *pPager = pPg->pPager;
42049 if( (pPg->flags&PGHDR_DIRTY) && pPager->nSavepoint==0 ){
42050 PAGERTRACE(("DONT_WRITE page %d of %d\n", pPg->pgno, PAGERID(pPager)));
42051 IOTRACE(("CLEAN %p %d\n", pPager, pPg->pgno))
42052 pPg->flags |= PGHDR_DONT_WRITE;
42053 pager_set_pagehash(pPg);
42058 ** This routine is called to increment the value of the database file
42059 ** change-counter, stored as a 4-byte big-endian integer starting at
42060 ** byte offset 24 of the pager file. The secondary change counter at
42061 ** 92 is also updated, as is the SQLite version number at offset 96.
42063 ** But this only happens if the pPager->changeCountDone flag is false.
42064 ** To avoid excess churning of page 1, the update only happens once.
42065 ** See also the pager_write_changecounter() routine that does an
42066 ** unconditional update of the change counters.
42068 ** If the isDirectMode flag is zero, then this is done by calling
42069 ** sqlite3PagerWrite() on page 1, then modifying the contents of the
42070 ** page data. In this case the file will be updated when the current
42071 ** transaction is committed.
42073 ** The isDirectMode flag may only be non-zero if the library was compiled
42074 ** with the SQLITE_ENABLE_ATOMIC_WRITE macro defined. In this case,
42075 ** if isDirect is non-zero, then the database file is updated directly
42076 ** by writing an updated version of page 1 using a call to the
42077 ** sqlite3OsWrite() function.
42079 static int pager_incr_changecounter(Pager *pPager, int isDirectMode){
42080 int rc = SQLITE_OK;
42082 assert( pPager->eState==PAGER_WRITER_CACHEMOD
42083 || pPager->eState==PAGER_WRITER_DBMOD
42085 assert( assert_pager_state(pPager) );
42087 /* Declare and initialize constant integer 'isDirect'. If the
42088 ** atomic-write optimization is enabled in this build, then isDirect
42089 ** is initialized to the value passed as the isDirectMode parameter
42090 ** to this function. Otherwise, it is always set to zero.
42092 ** The idea is that if the atomic-write optimization is not
42093 ** enabled at compile time, the compiler can omit the tests of
42094 ** 'isDirect' below, as well as the block enclosed in the
42095 ** "if( isDirect )" condition.
42097 #ifndef SQLITE_ENABLE_ATOMIC_WRITE
42098 # define DIRECT_MODE 0
42099 assert( isDirectMode==0 );
42100 UNUSED_PARAMETER(isDirectMode);
42101 #else
42102 # define DIRECT_MODE isDirectMode
42103 #endif
42105 if( !pPager->changeCountDone && pPager->dbSize>0 ){
42106 PgHdr *pPgHdr; /* Reference to page 1 */
42108 assert( !pPager->tempFile && isOpen(pPager->fd) );
42110 /* Open page 1 of the file for writing. */
42111 rc = sqlite3PagerGet(pPager, 1, &pPgHdr);
42112 assert( pPgHdr==0 || rc==SQLITE_OK );
42114 /* If page one was fetched successfully, and this function is not
42115 ** operating in direct-mode, make page 1 writable. When not in
42116 ** direct mode, page 1 is always held in cache and hence the PagerGet()
42117 ** above is always successful - hence the ALWAYS on rc==SQLITE_OK.
42119 if( !DIRECT_MODE && ALWAYS(rc==SQLITE_OK) ){
42120 rc = sqlite3PagerWrite(pPgHdr);
42123 if( rc==SQLITE_OK ){
42124 /* Actually do the update of the change counter */
42125 pager_write_changecounter(pPgHdr);
42127 /* If running in direct mode, write the contents of page 1 to the file. */
42128 if( DIRECT_MODE ){
42129 const void *zBuf;
42130 assert( pPager->dbFileSize>0 );
42131 CODEC2(pPager, pPgHdr->pData, 1, 6, rc=SQLITE_NOMEM, zBuf);
42132 if( rc==SQLITE_OK ){
42133 rc = sqlite3OsWrite(pPager->fd, zBuf, pPager->pageSize, 0);
42135 if( rc==SQLITE_OK ){
42136 pPager->changeCountDone = 1;
42138 }else{
42139 pPager->changeCountDone = 1;
42143 /* Release the page reference. */
42144 sqlite3PagerUnref(pPgHdr);
42146 return rc;
42150 ** Sync the database file to disk. This is a no-op for in-memory databases
42151 ** or pages with the Pager.noSync flag set.
42153 ** If successful, or if called on a pager for which it is a no-op, this
42154 ** function returns SQLITE_OK. Otherwise, an IO error code is returned.
42156 SQLITE_PRIVATE int sqlite3PagerSync(Pager *pPager){
42157 int rc = SQLITE_OK;
42158 if( !pPager->noSync ){
42159 assert( !MEMDB );
42160 rc = sqlite3OsSync(pPager->fd, pPager->syncFlags);
42161 }else if( isOpen(pPager->fd) ){
42162 assert( !MEMDB );
42163 sqlite3OsFileControl(pPager->fd, SQLITE_FCNTL_SYNC_OMITTED, (void *)&rc);
42165 return rc;
42169 ** This function may only be called while a write-transaction is active in
42170 ** rollback. If the connection is in WAL mode, this call is a no-op.
42171 ** Otherwise, if the connection does not already have an EXCLUSIVE lock on
42172 ** the database file, an attempt is made to obtain one.
42174 ** If the EXCLUSIVE lock is already held or the attempt to obtain it is
42175 ** successful, or the connection is in WAL mode, SQLITE_OK is returned.
42176 ** Otherwise, either SQLITE_BUSY or an SQLITE_IOERR_XXX error code is
42177 ** returned.
42179 SQLITE_PRIVATE int sqlite3PagerExclusiveLock(Pager *pPager){
42180 int rc = SQLITE_OK;
42181 assert( pPager->eState==PAGER_WRITER_CACHEMOD
42182 || pPager->eState==PAGER_WRITER_DBMOD
42183 || pPager->eState==PAGER_WRITER_LOCKED
42185 assert( assert_pager_state(pPager) );
42186 if( 0==pagerUseWal(pPager) ){
42187 rc = pager_wait_on_lock(pPager, EXCLUSIVE_LOCK);
42189 return rc;
42193 ** Sync the database file for the pager pPager. zMaster points to the name
42194 ** of a master journal file that should be written into the individual
42195 ** journal file. zMaster may be NULL, which is interpreted as no master
42196 ** journal (a single database transaction).
42198 ** This routine ensures that:
42200 ** * The database file change-counter is updated,
42201 ** * the journal is synced (unless the atomic-write optimization is used),
42202 ** * all dirty pages are written to the database file,
42203 ** * the database file is truncated (if required), and
42204 ** * the database file synced.
42206 ** The only thing that remains to commit the transaction is to finalize
42207 ** (delete, truncate or zero the first part of) the journal file (or
42208 ** delete the master journal file if specified).
42210 ** Note that if zMaster==NULL, this does not overwrite a previous value
42211 ** passed to an sqlite3PagerCommitPhaseOne() call.
42213 ** If the final parameter - noSync - is true, then the database file itself
42214 ** is not synced. The caller must call sqlite3PagerSync() directly to
42215 ** sync the database file before calling CommitPhaseTwo() to delete the
42216 ** journal file in this case.
42218 SQLITE_PRIVATE int sqlite3PagerCommitPhaseOne(
42219 Pager *pPager, /* Pager object */
42220 const char *zMaster, /* If not NULL, the master journal name */
42221 int noSync /* True to omit the xSync on the db file */
42223 int rc = SQLITE_OK; /* Return code */
42225 assert( pPager->eState==PAGER_WRITER_LOCKED
42226 || pPager->eState==PAGER_WRITER_CACHEMOD
42227 || pPager->eState==PAGER_WRITER_DBMOD
42228 || pPager->eState==PAGER_ERROR
42230 assert( assert_pager_state(pPager) );
42232 /* If a prior error occurred, report that error again. */
42233 if( NEVER(pPager->errCode) ) return pPager->errCode;
42235 PAGERTRACE(("DATABASE SYNC: File=%s zMaster=%s nSize=%d\n",
42236 pPager->zFilename, zMaster, pPager->dbSize));
42238 /* If no database changes have been made, return early. */
42239 if( pPager->eState<PAGER_WRITER_CACHEMOD ) return SQLITE_OK;
42241 if( MEMDB ){
42242 /* If this is an in-memory db, or no pages have been written to, or this
42243 ** function has already been called, it is mostly a no-op. However, any
42244 ** backup in progress needs to be restarted.
42246 sqlite3BackupRestart(pPager->pBackup);
42247 }else{
42248 if( pagerUseWal(pPager) ){
42249 PgHdr *pList = sqlite3PcacheDirtyList(pPager->pPCache);
42250 PgHdr *pPageOne = 0;
42251 if( pList==0 ){
42252 /* Must have at least one page for the WAL commit flag.
42253 ** Ticket [2d1a5c67dfc2363e44f29d9bbd57f] 2011-05-18 */
42254 rc = sqlite3PagerGet(pPager, 1, &pPageOne);
42255 pList = pPageOne;
42256 pList->pDirty = 0;
42258 assert( pList!=0 || rc!=SQLITE_OK );
42259 if( pList ){
42260 rc = pagerWalFrames(pPager, pList, pPager->dbSize, 1,
42261 (pPager->fullSync ? pPager->syncFlags : 0)
42264 sqlite3PagerUnref(pPageOne);
42265 if( rc==SQLITE_OK ){
42266 sqlite3PcacheCleanAll(pPager->pPCache);
42268 }else{
42269 /* The following block updates the change-counter. Exactly how it
42270 ** does this depends on whether or not the atomic-update optimization
42271 ** was enabled at compile time, and if this transaction meets the
42272 ** runtime criteria to use the operation:
42274 ** * The file-system supports the atomic-write property for
42275 ** blocks of size page-size, and
42276 ** * This commit is not part of a multi-file transaction, and
42277 ** * Exactly one page has been modified and store in the journal file.
42279 ** If the optimization was not enabled at compile time, then the
42280 ** pager_incr_changecounter() function is called to update the change
42281 ** counter in 'indirect-mode'. If the optimization is compiled in but
42282 ** is not applicable to this transaction, call sqlite3JournalCreate()
42283 ** to make sure the journal file has actually been created, then call
42284 ** pager_incr_changecounter() to update the change-counter in indirect
42285 ** mode.
42287 ** Otherwise, if the optimization is both enabled and applicable,
42288 ** then call pager_incr_changecounter() to update the change-counter
42289 ** in 'direct' mode. In this case the journal file will never be
42290 ** created for this transaction.
42292 #ifdef SQLITE_ENABLE_ATOMIC_WRITE
42293 PgHdr *pPg;
42294 assert( isOpen(pPager->jfd)
42295 || pPager->journalMode==PAGER_JOURNALMODE_OFF
42296 || pPager->journalMode==PAGER_JOURNALMODE_WAL
42298 if( !zMaster && isOpen(pPager->jfd)
42299 && pPager->journalOff==jrnlBufferSize(pPager)
42300 && pPager->dbSize>=pPager->dbOrigSize
42301 && (0==(pPg = sqlite3PcacheDirtyList(pPager->pPCache)) || 0==pPg->pDirty)
42303 /* Update the db file change counter via the direct-write method. The
42304 ** following call will modify the in-memory representation of page 1
42305 ** to include the updated change counter and then write page 1
42306 ** directly to the database file. Because of the atomic-write
42307 ** property of the host file-system, this is safe.
42309 rc = pager_incr_changecounter(pPager, 1);
42310 }else{
42311 rc = sqlite3JournalCreate(pPager->jfd);
42312 if( rc==SQLITE_OK ){
42313 rc = pager_incr_changecounter(pPager, 0);
42316 #else
42317 rc = pager_incr_changecounter(pPager, 0);
42318 #endif
42319 if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
42321 /* If this transaction has made the database smaller, then all pages
42322 ** being discarded by the truncation must be written to the journal
42323 ** file. This can only happen in auto-vacuum mode.
42325 ** Before reading the pages with page numbers larger than the
42326 ** current value of Pager.dbSize, set dbSize back to the value
42327 ** that it took at the start of the transaction. Otherwise, the
42328 ** calls to sqlite3PagerGet() return zeroed pages instead of
42329 ** reading data from the database file.
42331 #ifndef SQLITE_OMIT_AUTOVACUUM
42332 if( pPager->dbSize<pPager->dbOrigSize
42333 && pPager->journalMode!=PAGER_JOURNALMODE_OFF
42335 Pgno i; /* Iterator variable */
42336 const Pgno iSkip = PAGER_MJ_PGNO(pPager); /* Pending lock page */
42337 const Pgno dbSize = pPager->dbSize; /* Database image size */
42338 pPager->dbSize = pPager->dbOrigSize;
42339 for( i=dbSize+1; i<=pPager->dbOrigSize; i++ ){
42340 if( !sqlite3BitvecTest(pPager->pInJournal, i) && i!=iSkip ){
42341 PgHdr *pPage; /* Page to journal */
42342 rc = sqlite3PagerGet(pPager, i, &pPage);
42343 if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
42344 rc = sqlite3PagerWrite(pPage);
42345 sqlite3PagerUnref(pPage);
42346 if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
42349 pPager->dbSize = dbSize;
42351 #endif
42353 /* Write the master journal name into the journal file. If a master
42354 ** journal file name has already been written to the journal file,
42355 ** or if zMaster is NULL (no master journal), then this call is a no-op.
42357 rc = writeMasterJournal(pPager, zMaster);
42358 if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
42360 /* Sync the journal file and write all dirty pages to the database.
42361 ** If the atomic-update optimization is being used, this sync will not
42362 ** create the journal file or perform any real IO.
42364 ** Because the change-counter page was just modified, unless the
42365 ** atomic-update optimization is used it is almost certain that the
42366 ** journal requires a sync here. However, in locking_mode=exclusive
42367 ** on a system under memory pressure it is just possible that this is
42368 ** not the case. In this case it is likely enough that the redundant
42369 ** xSync() call will be changed to a no-op by the OS anyhow.
42371 rc = syncJournal(pPager, 0);
42372 if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
42374 rc = pager_write_pagelist(pPager,sqlite3PcacheDirtyList(pPager->pPCache));
42375 if( rc!=SQLITE_OK ){
42376 assert( rc!=SQLITE_IOERR_BLOCKED );
42377 goto commit_phase_one_exit;
42379 sqlite3PcacheCleanAll(pPager->pPCache);
42381 /* If the file on disk is not the same size as the database image,
42382 ** then use pager_truncate to grow or shrink the file here.
42384 if( pPager->dbSize!=pPager->dbFileSize ){
42385 Pgno nNew = pPager->dbSize - (pPager->dbSize==PAGER_MJ_PGNO(pPager));
42386 assert( pPager->eState==PAGER_WRITER_DBMOD );
42387 rc = pager_truncate(pPager, nNew);
42388 if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
42391 /* Finally, sync the database file. */
42392 if( !noSync ){
42393 rc = sqlite3PagerSync(pPager);
42395 IOTRACE(("DBSYNC %p\n", pPager))
42399 commit_phase_one_exit:
42400 if( rc==SQLITE_OK && !pagerUseWal(pPager) ){
42401 pPager->eState = PAGER_WRITER_FINISHED;
42403 return rc;
42408 ** When this function is called, the database file has been completely
42409 ** updated to reflect the changes made by the current transaction and
42410 ** synced to disk. The journal file still exists in the file-system
42411 ** though, and if a failure occurs at this point it will eventually
42412 ** be used as a hot-journal and the current transaction rolled back.
42414 ** This function finalizes the journal file, either by deleting,
42415 ** truncating or partially zeroing it, so that it cannot be used
42416 ** for hot-journal rollback. Once this is done the transaction is
42417 ** irrevocably committed.
42419 ** If an error occurs, an IO error code is returned and the pager
42420 ** moves into the error state. Otherwise, SQLITE_OK is returned.
42422 SQLITE_PRIVATE int sqlite3PagerCommitPhaseTwo(Pager *pPager){
42423 int rc = SQLITE_OK; /* Return code */
42425 /* This routine should not be called if a prior error has occurred.
42426 ** But if (due to a coding error elsewhere in the system) it does get
42427 ** called, just return the same error code without doing anything. */
42428 if( NEVER(pPager->errCode) ) return pPager->errCode;
42430 assert( pPager->eState==PAGER_WRITER_LOCKED
42431 || pPager->eState==PAGER_WRITER_FINISHED
42432 || (pagerUseWal(pPager) && pPager->eState==PAGER_WRITER_CACHEMOD)
42434 assert( assert_pager_state(pPager) );
42436 /* An optimization. If the database was not actually modified during
42437 ** this transaction, the pager is running in exclusive-mode and is
42438 ** using persistent journals, then this function is a no-op.
42440 ** The start of the journal file currently contains a single journal
42441 ** header with the nRec field set to 0. If such a journal is used as
42442 ** a hot-journal during hot-journal rollback, 0 changes will be made
42443 ** to the database file. So there is no need to zero the journal
42444 ** header. Since the pager is in exclusive mode, there is no need
42445 ** to drop any locks either.
42447 if( pPager->eState==PAGER_WRITER_LOCKED
42448 && pPager->exclusiveMode
42449 && pPager->journalMode==PAGER_JOURNALMODE_PERSIST
42451 assert( pPager->journalOff==JOURNAL_HDR_SZ(pPager) || !pPager->journalOff );
42452 pPager->eState = PAGER_READER;
42453 return SQLITE_OK;
42456 PAGERTRACE(("COMMIT %d\n", PAGERID(pPager)));
42457 rc = pager_end_transaction(pPager, pPager->setMaster);
42458 return pager_error(pPager, rc);
42462 ** If a write transaction is open, then all changes made within the
42463 ** transaction are reverted and the current write-transaction is closed.
42464 ** The pager falls back to PAGER_READER state if successful, or PAGER_ERROR
42465 ** state if an error occurs.
42467 ** If the pager is already in PAGER_ERROR state when this function is called,
42468 ** it returns Pager.errCode immediately. No work is performed in this case.
42470 ** Otherwise, in rollback mode, this function performs two functions:
42472 ** 1) It rolls back the journal file, restoring all database file and
42473 ** in-memory cache pages to the state they were in when the transaction
42474 ** was opened, and
42476 ** 2) It finalizes the journal file, so that it is not used for hot
42477 ** rollback at any point in the future.
42479 ** Finalization of the journal file (task 2) is only performed if the
42480 ** rollback is successful.
42482 ** In WAL mode, all cache-entries containing data modified within the
42483 ** current transaction are either expelled from the cache or reverted to
42484 ** their pre-transaction state by re-reading data from the database or
42485 ** WAL files. The WAL transaction is then closed.
42487 SQLITE_PRIVATE int sqlite3PagerRollback(Pager *pPager){
42488 int rc = SQLITE_OK; /* Return code */
42489 PAGERTRACE(("ROLLBACK %d\n", PAGERID(pPager)));
42491 /* PagerRollback() is a no-op if called in READER or OPEN state. If
42492 ** the pager is already in the ERROR state, the rollback is not
42493 ** attempted here. Instead, the error code is returned to the caller.
42495 assert( assert_pager_state(pPager) );
42496 if( pPager->eState==PAGER_ERROR ) return pPager->errCode;
42497 if( pPager->eState<=PAGER_READER ) return SQLITE_OK;
42499 if( pagerUseWal(pPager) ){
42500 int rc2;
42501 rc = sqlite3PagerSavepoint(pPager, SAVEPOINT_ROLLBACK, -1);
42502 rc2 = pager_end_transaction(pPager, pPager->setMaster);
42503 if( rc==SQLITE_OK ) rc = rc2;
42504 }else if( !isOpen(pPager->jfd) || pPager->eState==PAGER_WRITER_LOCKED ){
42505 int eState = pPager->eState;
42506 rc = pager_end_transaction(pPager, 0);
42507 if( !MEMDB && eState>PAGER_WRITER_LOCKED ){
42508 /* This can happen using journal_mode=off. Move the pager to the error
42509 ** state to indicate that the contents of the cache may not be trusted.
42510 ** Any active readers will get SQLITE_ABORT.
42512 pPager->errCode = SQLITE_ABORT;
42513 pPager->eState = PAGER_ERROR;
42514 return rc;
42516 }else{
42517 rc = pager_playback(pPager, 0);
42520 assert( pPager->eState==PAGER_READER || rc!=SQLITE_OK );
42521 assert( rc==SQLITE_OK || rc==SQLITE_FULL || (rc&0xFF)==SQLITE_IOERR );
42523 /* If an error occurs during a ROLLBACK, we can no longer trust the pager
42524 ** cache. So call pager_error() on the way out to make any error persistent.
42526 return pager_error(pPager, rc);
42530 ** Return TRUE if the database file is opened read-only. Return FALSE
42531 ** if the database is (in theory) writable.
42533 SQLITE_PRIVATE u8 sqlite3PagerIsreadonly(Pager *pPager){
42534 return pPager->readOnly;
42538 ** Return the number of references to the pager.
42540 SQLITE_PRIVATE int sqlite3PagerRefcount(Pager *pPager){
42541 return sqlite3PcacheRefCount(pPager->pPCache);
42545 ** Return the approximate number of bytes of memory currently
42546 ** used by the pager and its associated cache.
42548 SQLITE_PRIVATE int sqlite3PagerMemUsed(Pager *pPager){
42549 int perPageSize = pPager->pageSize + pPager->nExtra + sizeof(PgHdr)
42550 + 5*sizeof(void*);
42551 return perPageSize*sqlite3PcachePagecount(pPager->pPCache)
42552 + sqlite3MallocSize(pPager)
42553 + pPager->pageSize;
42557 ** Return the number of references to the specified page.
42559 SQLITE_PRIVATE int sqlite3PagerPageRefcount(DbPage *pPage){
42560 return sqlite3PcachePageRefcount(pPage);
42563 #ifdef SQLITE_TEST
42565 ** This routine is used for testing and analysis only.
42567 SQLITE_PRIVATE int *sqlite3PagerStats(Pager *pPager){
42568 static int a[11];
42569 a[0] = sqlite3PcacheRefCount(pPager->pPCache);
42570 a[1] = sqlite3PcachePagecount(pPager->pPCache);
42571 a[2] = sqlite3PcacheGetCachesize(pPager->pPCache);
42572 a[3] = pPager->eState==PAGER_OPEN ? -1 : (int) pPager->dbSize;
42573 a[4] = pPager->eState;
42574 a[5] = pPager->errCode;
42575 a[6] = pPager->nHit;
42576 a[7] = pPager->nMiss;
42577 a[8] = 0; /* Used to be pPager->nOvfl */
42578 a[9] = pPager->nRead;
42579 a[10] = pPager->nWrite;
42580 return a;
42582 #endif
42585 ** Return true if this is an in-memory pager.
42587 SQLITE_PRIVATE int sqlite3PagerIsMemdb(Pager *pPager){
42588 return MEMDB;
42592 ** Check that there are at least nSavepoint savepoints open. If there are
42593 ** currently less than nSavepoints open, then open one or more savepoints
42594 ** to make up the difference. If the number of savepoints is already
42595 ** equal to nSavepoint, then this function is a no-op.
42597 ** If a memory allocation fails, SQLITE_NOMEM is returned. If an error
42598 ** occurs while opening the sub-journal file, then an IO error code is
42599 ** returned. Otherwise, SQLITE_OK.
42601 SQLITE_PRIVATE int sqlite3PagerOpenSavepoint(Pager *pPager, int nSavepoint){
42602 int rc = SQLITE_OK; /* Return code */
42603 int nCurrent = pPager->nSavepoint; /* Current number of savepoints */
42605 assert( pPager->eState>=PAGER_WRITER_LOCKED );
42606 assert( assert_pager_state(pPager) );
42608 if( nSavepoint>nCurrent && pPager->useJournal ){
42609 int ii; /* Iterator variable */
42610 PagerSavepoint *aNew; /* New Pager.aSavepoint array */
42612 /* Grow the Pager.aSavepoint array using realloc(). Return SQLITE_NOMEM
42613 ** if the allocation fails. Otherwise, zero the new portion in case a
42614 ** malloc failure occurs while populating it in the for(...) loop below.
42616 aNew = (PagerSavepoint *)sqlite3Realloc(
42617 pPager->aSavepoint, sizeof(PagerSavepoint)*nSavepoint
42619 if( !aNew ){
42620 return SQLITE_NOMEM;
42622 memset(&aNew[nCurrent], 0, (nSavepoint-nCurrent) * sizeof(PagerSavepoint));
42623 pPager->aSavepoint = aNew;
42625 /* Populate the PagerSavepoint structures just allocated. */
42626 for(ii=nCurrent; ii<nSavepoint; ii++){
42627 aNew[ii].nOrig = pPager->dbSize;
42628 if( isOpen(pPager->jfd) && pPager->journalOff>0 ){
42629 aNew[ii].iOffset = pPager->journalOff;
42630 }else{
42631 aNew[ii].iOffset = JOURNAL_HDR_SZ(pPager);
42633 aNew[ii].iSubRec = pPager->nSubRec;
42634 aNew[ii].pInSavepoint = sqlite3BitvecCreate(pPager->dbSize);
42635 if( !aNew[ii].pInSavepoint ){
42636 return SQLITE_NOMEM;
42638 if( pagerUseWal(pPager) ){
42639 sqlite3WalSavepoint(pPager->pWal, aNew[ii].aWalData);
42641 pPager->nSavepoint = ii+1;
42643 assert( pPager->nSavepoint==nSavepoint );
42644 assertTruncateConstraint(pPager);
42647 return rc;
42651 ** This function is called to rollback or release (commit) a savepoint.
42652 ** The savepoint to release or rollback need not be the most recently
42653 ** created savepoint.
42655 ** Parameter op is always either SAVEPOINT_ROLLBACK or SAVEPOINT_RELEASE.
42656 ** If it is SAVEPOINT_RELEASE, then release and destroy the savepoint with
42657 ** index iSavepoint. If it is SAVEPOINT_ROLLBACK, then rollback all changes
42658 ** that have occurred since the specified savepoint was created.
42660 ** The savepoint to rollback or release is identified by parameter
42661 ** iSavepoint. A value of 0 means to operate on the outermost savepoint
42662 ** (the first created). A value of (Pager.nSavepoint-1) means operate
42663 ** on the most recently created savepoint. If iSavepoint is greater than
42664 ** (Pager.nSavepoint-1), then this function is a no-op.
42666 ** If a negative value is passed to this function, then the current
42667 ** transaction is rolled back. This is different to calling
42668 ** sqlite3PagerRollback() because this function does not terminate
42669 ** the transaction or unlock the database, it just restores the
42670 ** contents of the database to its original state.
42672 ** In any case, all savepoints with an index greater than iSavepoint
42673 ** are destroyed. If this is a release operation (op==SAVEPOINT_RELEASE),
42674 ** then savepoint iSavepoint is also destroyed.
42676 ** This function may return SQLITE_NOMEM if a memory allocation fails,
42677 ** or an IO error code if an IO error occurs while rolling back a
42678 ** savepoint. If no errors occur, SQLITE_OK is returned.
42680 SQLITE_PRIVATE int sqlite3PagerSavepoint(Pager *pPager, int op, int iSavepoint){
42681 int rc = pPager->errCode; /* Return code */
42683 assert( op==SAVEPOINT_RELEASE || op==SAVEPOINT_ROLLBACK );
42684 assert( iSavepoint>=0 || op==SAVEPOINT_ROLLBACK );
42686 if( rc==SQLITE_OK && iSavepoint<pPager->nSavepoint ){
42687 int ii; /* Iterator variable */
42688 int nNew; /* Number of remaining savepoints after this op. */
42690 /* Figure out how many savepoints will still be active after this
42691 ** operation. Store this value in nNew. Then free resources associated
42692 ** with any savepoints that are destroyed by this operation.
42694 nNew = iSavepoint + (( op==SAVEPOINT_RELEASE ) ? 0 : 1);
42695 for(ii=nNew; ii<pPager->nSavepoint; ii++){
42696 sqlite3BitvecDestroy(pPager->aSavepoint[ii].pInSavepoint);
42698 pPager->nSavepoint = nNew;
42700 /* If this is a release of the outermost savepoint, truncate
42701 ** the sub-journal to zero bytes in size. */
42702 if( op==SAVEPOINT_RELEASE ){
42703 if( nNew==0 && isOpen(pPager->sjfd) ){
42704 /* Only truncate if it is an in-memory sub-journal. */
42705 if( sqlite3IsMemJournal(pPager->sjfd) ){
42706 rc = sqlite3OsTruncate(pPager->sjfd, 0);
42707 assert( rc==SQLITE_OK );
42709 pPager->nSubRec = 0;
42712 /* Else this is a rollback operation, playback the specified savepoint.
42713 ** If this is a temp-file, it is possible that the journal file has
42714 ** not yet been opened. In this case there have been no changes to
42715 ** the database file, so the playback operation can be skipped.
42717 else if( pagerUseWal(pPager) || isOpen(pPager->jfd) ){
42718 PagerSavepoint *pSavepoint = (nNew==0)?0:&pPager->aSavepoint[nNew-1];
42719 rc = pagerPlaybackSavepoint(pPager, pSavepoint);
42720 assert(rc!=SQLITE_DONE);
42724 return rc;
42728 ** Return the full pathname of the database file.
42730 SQLITE_PRIVATE const char *sqlite3PagerFilename(Pager *pPager){
42731 return pPager->zFilename;
42735 ** Return the VFS structure for the pager.
42737 SQLITE_PRIVATE const sqlite3_vfs *sqlite3PagerVfs(Pager *pPager){
42738 return pPager->pVfs;
42742 ** Return the file handle for the database file associated
42743 ** with the pager. This might return NULL if the file has
42744 ** not yet been opened.
42746 SQLITE_PRIVATE sqlite3_file *sqlite3PagerFile(Pager *pPager){
42747 return pPager->fd;
42751 ** Return the full pathname of the journal file.
42753 SQLITE_PRIVATE const char *sqlite3PagerJournalname(Pager *pPager){
42754 return pPager->zJournal;
42758 ** Return true if fsync() calls are disabled for this pager. Return FALSE
42759 ** if fsync()s are executed normally.
42761 SQLITE_PRIVATE int sqlite3PagerNosync(Pager *pPager){
42762 return pPager->noSync;
42765 #ifdef SQLITE_HAS_CODEC
42767 ** Set or retrieve the codec for this pager
42769 SQLITE_PRIVATE void sqlite3PagerSetCodec(
42770 Pager *pPager,
42771 void *(*xCodec)(void*,void*,Pgno,int),
42772 void (*xCodecSizeChng)(void*,int,int),
42773 void (*xCodecFree)(void*),
42774 void *pCodec
42776 if( pPager->xCodecFree ) pPager->xCodecFree(pPager->pCodec);
42777 pPager->xCodec = pPager->memDb ? 0 : xCodec;
42778 pPager->xCodecSizeChng = xCodecSizeChng;
42779 pPager->xCodecFree = xCodecFree;
42780 pPager->pCodec = pCodec;
42781 pagerReportSize(pPager);
42783 SQLITE_PRIVATE void *sqlite3PagerGetCodec(Pager *pPager){
42784 return pPager->pCodec;
42786 #endif
42788 #ifndef SQLITE_OMIT_AUTOVACUUM
42790 ** Move the page pPg to location pgno in the file.
42792 ** There must be no references to the page previously located at
42793 ** pgno (which we call pPgOld) though that page is allowed to be
42794 ** in cache. If the page previously located at pgno is not already
42795 ** in the rollback journal, it is not put there by by this routine.
42797 ** References to the page pPg remain valid. Updating any
42798 ** meta-data associated with pPg (i.e. data stored in the nExtra bytes
42799 ** allocated along with the page) is the responsibility of the caller.
42801 ** A transaction must be active when this routine is called. It used to be
42802 ** required that a statement transaction was not active, but this restriction
42803 ** has been removed (CREATE INDEX needs to move a page when a statement
42804 ** transaction is active).
42806 ** If the fourth argument, isCommit, is non-zero, then this page is being
42807 ** moved as part of a database reorganization just before the transaction
42808 ** is being committed. In this case, it is guaranteed that the database page
42809 ** pPg refers to will not be written to again within this transaction.
42811 ** This function may return SQLITE_NOMEM or an IO error code if an error
42812 ** occurs. Otherwise, it returns SQLITE_OK.
42814 SQLITE_PRIVATE int sqlite3PagerMovepage(Pager *pPager, DbPage *pPg, Pgno pgno, int isCommit){
42815 PgHdr *pPgOld; /* The page being overwritten. */
42816 Pgno needSyncPgno = 0; /* Old value of pPg->pgno, if sync is required */
42817 int rc; /* Return code */
42818 Pgno origPgno; /* The original page number */
42820 assert( pPg->nRef>0 );
42821 assert( pPager->eState==PAGER_WRITER_CACHEMOD
42822 || pPager->eState==PAGER_WRITER_DBMOD
42824 assert( assert_pager_state(pPager) );
42826 /* In order to be able to rollback, an in-memory database must journal
42827 ** the page we are moving from.
42829 if( MEMDB ){
42830 rc = sqlite3PagerWrite(pPg);
42831 if( rc ) return rc;
42834 /* If the page being moved is dirty and has not been saved by the latest
42835 ** savepoint, then save the current contents of the page into the
42836 ** sub-journal now. This is required to handle the following scenario:
42838 ** BEGIN;
42839 ** <journal page X, then modify it in memory>
42840 ** SAVEPOINT one;
42841 ** <Move page X to location Y>
42842 ** ROLLBACK TO one;
42844 ** If page X were not written to the sub-journal here, it would not
42845 ** be possible to restore its contents when the "ROLLBACK TO one"
42846 ** statement were is processed.
42848 ** subjournalPage() may need to allocate space to store pPg->pgno into
42849 ** one or more savepoint bitvecs. This is the reason this function
42850 ** may return SQLITE_NOMEM.
42852 if( pPg->flags&PGHDR_DIRTY
42853 && subjRequiresPage(pPg)
42854 && SQLITE_OK!=(rc = subjournalPage(pPg))
42856 return rc;
42859 PAGERTRACE(("MOVE %d page %d (needSync=%d) moves to %d\n",
42860 PAGERID(pPager), pPg->pgno, (pPg->flags&PGHDR_NEED_SYNC)?1:0, pgno));
42861 IOTRACE(("MOVE %p %d %d\n", pPager, pPg->pgno, pgno))
42863 /* If the journal needs to be sync()ed before page pPg->pgno can
42864 ** be written to, store pPg->pgno in local variable needSyncPgno.
42866 ** If the isCommit flag is set, there is no need to remember that
42867 ** the journal needs to be sync()ed before database page pPg->pgno
42868 ** can be written to. The caller has already promised not to write to it.
42870 if( (pPg->flags&PGHDR_NEED_SYNC) && !isCommit ){
42871 needSyncPgno = pPg->pgno;
42872 assert( pageInJournal(pPg) || pPg->pgno>pPager->dbOrigSize );
42873 assert( pPg->flags&PGHDR_DIRTY );
42876 /* If the cache contains a page with page-number pgno, remove it
42877 ** from its hash chain. Also, if the PGHDR_NEED_SYNC flag was set for
42878 ** page pgno before the 'move' operation, it needs to be retained
42879 ** for the page moved there.
42881 pPg->flags &= ~PGHDR_NEED_SYNC;
42882 pPgOld = pager_lookup(pPager, pgno);
42883 assert( !pPgOld || pPgOld->nRef==1 );
42884 if( pPgOld ){
42885 pPg->flags |= (pPgOld->flags&PGHDR_NEED_SYNC);
42886 if( MEMDB ){
42887 /* Do not discard pages from an in-memory database since we might
42888 ** need to rollback later. Just move the page out of the way. */
42889 sqlite3PcacheMove(pPgOld, pPager->dbSize+1);
42890 }else{
42891 sqlite3PcacheDrop(pPgOld);
42895 origPgno = pPg->pgno;
42896 sqlite3PcacheMove(pPg, pgno);
42897 sqlite3PcacheMakeDirty(pPg);
42899 /* For an in-memory database, make sure the original page continues
42900 ** to exist, in case the transaction needs to roll back. Use pPgOld
42901 ** as the original page since it has already been allocated.
42903 if( MEMDB ){
42904 assert( pPgOld );
42905 sqlite3PcacheMove(pPgOld, origPgno);
42906 sqlite3PagerUnref(pPgOld);
42909 if( needSyncPgno ){
42910 /* If needSyncPgno is non-zero, then the journal file needs to be
42911 ** sync()ed before any data is written to database file page needSyncPgno.
42912 ** Currently, no such page exists in the page-cache and the
42913 ** "is journaled" bitvec flag has been set. This needs to be remedied by
42914 ** loading the page into the pager-cache and setting the PGHDR_NEED_SYNC
42915 ** flag.
42917 ** If the attempt to load the page into the page-cache fails, (due
42918 ** to a malloc() or IO failure), clear the bit in the pInJournal[]
42919 ** array. Otherwise, if the page is loaded and written again in
42920 ** this transaction, it may be written to the database file before
42921 ** it is synced into the journal file. This way, it may end up in
42922 ** the journal file twice, but that is not a problem.
42924 PgHdr *pPgHdr;
42925 rc = sqlite3PagerGet(pPager, needSyncPgno, &pPgHdr);
42926 if( rc!=SQLITE_OK ){
42927 if( needSyncPgno<=pPager->dbOrigSize ){
42928 assert( pPager->pTmpSpace!=0 );
42929 sqlite3BitvecClear(pPager->pInJournal, needSyncPgno, pPager->pTmpSpace);
42931 return rc;
42933 pPgHdr->flags |= PGHDR_NEED_SYNC;
42934 sqlite3PcacheMakeDirty(pPgHdr);
42935 sqlite3PagerUnref(pPgHdr);
42938 return SQLITE_OK;
42940 #endif
42942 /* Begin preload-cache.patch for Chromium */
42943 #if 1
42944 /* NOTE(shess): Testing to see if simply reading the data into the
42945 * filesystem buffers will have the positive speed impact without the
42946 * negative memory impact.
42948 SQLITE_PRIVATE int sqlite3PagerLoadall(Pager* pPager)
42950 int i, pageSize, loadPages, rc;
42951 unsigned char *fileData;
42953 /* TODO(shess): This test may not be relevant for this
42954 * implementation, but keep the invariant consistent.
42956 pageSize = pPager->pageSize;
42957 if (pPager->dbSize < 0 || pageSize < 0) {
42958 /* pager not initialized, this means a statement is not open */
42959 return SQLITE_MISUSE;
42962 /* Allocate a buffer to read pages into. */
42963 /* TODO(shess): No need to read by page, this could be a fixed-size
42964 * buffer on stack.
42966 fileData = sqlite3Malloc(pageSize);
42967 if (!fileData)
42968 return SQLITE_NOMEM;
42970 /* Load the smaller of the entire cache or the entire database. */
42971 loadPages = sqlite3PcacheGetCachesize(pPager->pPCache);
42972 if (loadPages > pPager->dbSize)
42973 loadPages = pPager->dbSize;
42975 /* Read database page by page. */
42976 rc = SQLITE_OK;
42977 for(i=0; i < loadPages; i++) {
42978 rc = sqlite3OsRead(pPager->fd, fileData, pageSize, i*pageSize);
42979 if (rc != SQLITE_OK)
42980 break;
42982 sqlite3_free(fileData);
42983 return rc;
42985 #else
42987 ** When making large allocations, there is no need to stress the heap and
42988 ** potentially hold its lock while we allocate a bunch of memory. If we know
42989 ** the allocation will be large, go directly to the OS instead of the heap.
42991 static void* allocLarge(size_t size) {
42992 #if SQLITE_OS_WIN
42993 return VirtualAlloc(NULL, size, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE);
42994 #else
42995 return sqlite3Malloc(size);
42996 #endif
42999 static void freeLarge(void* ptr) {
43000 #if SQLITE_OS_WIN
43001 VirtualFree(ptr, 0, MEM_RELEASE);
43002 #else
43003 sqlite3_free(ptr);
43004 #endif
43008 ** Addition: This will attempt to populate the database cache with
43009 ** the first N bytes of the file, where N is the total size of the cache.
43010 ** Because we can load this as one chunk from the disk, this is much faster
43011 ** than loading a subset of the pages one at a time in random order.
43013 ** The pager must be initialized before this function is called. This means a
43014 * statement must be open that has initialized the pager and is keeping the
43015 ** cache in memory.
43017 SQLITE_PRIVATE int sqlite3PagerLoadall(Pager* pPager)
43019 int i;
43020 int rc;
43021 int nMax;
43022 int loadSize;
43023 int loadPages;
43024 unsigned char *fileData;
43026 if (pPager->dbSize < 0 || pPager->pageSize < 0) {
43027 /* pager not initialized, this means a statement is not open */
43028 return SQLITE_MISUSE;
43031 /* compute sizes */
43032 nMax = sqlite3PcacheGetCachesize(pPager->pPCache);
43033 if (nMax < pPager->dbSize)
43034 loadPages = nMax;
43035 else
43036 loadPages = pPager->dbSize;
43037 loadSize = loadPages * pPager->pageSize;
43039 /* load the file as one chunk */
43040 fileData = allocLarge(loadSize);
43041 if (! fileData)
43042 return SQLITE_NOMEM;
43043 rc = sqlite3OsRead(pPager->fd, fileData, loadSize, 0);
43044 if (rc != SQLITE_OK) {
43045 freeLarge(fileData);
43046 return rc;
43049 /* Copy the data to each page. Note that the page numbers we pass to _get
43050 * are one-based, 0 is a marker for no page. We also need to check that we
43051 * haven't loaded more pages than the cache can hold total. There may have
43052 * already been a few pages loaded before, so we may fill the cache before
43053 * loading all of the pages we want to.
43055 for(i=1;
43056 i <= loadPages && sqlite3PcachePagecount(pPager->pPCache) < nMax;
43057 i++) {
43058 DbPage *pPage = 0;
43059 rc = sqlite3PagerAcquire2(pPager, i, &pPage, 0,
43060 &fileData[(i-1)*(i64)pPager->pageSize]);
43061 if (rc != SQLITE_OK)
43062 break;
43063 sqlite3PagerUnref(pPage);
43065 freeLarge(fileData);
43066 return SQLITE_OK;
43068 #endif
43069 /* End preload-cache.patch for Chromium */
43072 ** Return a pointer to the data for the specified page.
43074 SQLITE_PRIVATE void *sqlite3PagerGetData(DbPage *pPg){
43075 assert( pPg->nRef>0 || pPg->pPager->memDb );
43076 return pPg->pData;
43080 ** Return a pointer to the Pager.nExtra bytes of "extra" space
43081 ** allocated along with the specified page.
43083 SQLITE_PRIVATE void *sqlite3PagerGetExtra(DbPage *pPg){
43084 return pPg->pExtra;
43088 ** Get/set the locking-mode for this pager. Parameter eMode must be one
43089 ** of PAGER_LOCKINGMODE_QUERY, PAGER_LOCKINGMODE_NORMAL or
43090 ** PAGER_LOCKINGMODE_EXCLUSIVE. If the parameter is not _QUERY, then
43091 ** the locking-mode is set to the value specified.
43093 ** The returned value is either PAGER_LOCKINGMODE_NORMAL or
43094 ** PAGER_LOCKINGMODE_EXCLUSIVE, indicating the current (possibly updated)
43095 ** locking-mode.
43097 SQLITE_PRIVATE int sqlite3PagerLockingMode(Pager *pPager, int eMode){
43098 assert( eMode==PAGER_LOCKINGMODE_QUERY
43099 || eMode==PAGER_LOCKINGMODE_NORMAL
43100 || eMode==PAGER_LOCKINGMODE_EXCLUSIVE );
43101 assert( PAGER_LOCKINGMODE_QUERY<0 );
43102 assert( PAGER_LOCKINGMODE_NORMAL>=0 && PAGER_LOCKINGMODE_EXCLUSIVE>=0 );
43103 assert( pPager->exclusiveMode || 0==sqlite3WalHeapMemory(pPager->pWal) );
43104 if( eMode>=0 && !pPager->tempFile && !sqlite3WalHeapMemory(pPager->pWal) ){
43105 pPager->exclusiveMode = (u8)eMode;
43107 return (int)pPager->exclusiveMode;
43111 ** Set the journal-mode for this pager. Parameter eMode must be one of:
43113 ** PAGER_JOURNALMODE_DELETE
43114 ** PAGER_JOURNALMODE_TRUNCATE
43115 ** PAGER_JOURNALMODE_PERSIST
43116 ** PAGER_JOURNALMODE_OFF
43117 ** PAGER_JOURNALMODE_MEMORY
43118 ** PAGER_JOURNALMODE_WAL
43120 ** The journalmode is set to the value specified if the change is allowed.
43121 ** The change may be disallowed for the following reasons:
43123 ** * An in-memory database can only have its journal_mode set to _OFF
43124 ** or _MEMORY.
43126 ** * Temporary databases cannot have _WAL journalmode.
43128 ** The returned indicate the current (possibly updated) journal-mode.
43130 SQLITE_PRIVATE int sqlite3PagerSetJournalMode(Pager *pPager, int eMode){
43131 u8 eOld = pPager->journalMode; /* Prior journalmode */
43133 #ifdef SQLITE_DEBUG
43134 /* The print_pager_state() routine is intended to be used by the debugger
43135 ** only. We invoke it once here to suppress a compiler warning. */
43136 print_pager_state(pPager);
43137 #endif
43140 /* The eMode parameter is always valid */
43141 assert( eMode==PAGER_JOURNALMODE_DELETE
43142 || eMode==PAGER_JOURNALMODE_TRUNCATE
43143 || eMode==PAGER_JOURNALMODE_PERSIST
43144 || eMode==PAGER_JOURNALMODE_OFF
43145 || eMode==PAGER_JOURNALMODE_WAL
43146 || eMode==PAGER_JOURNALMODE_MEMORY );
43148 /* This routine is only called from the OP_JournalMode opcode, and
43149 ** the logic there will never allow a temporary file to be changed
43150 ** to WAL mode.
43152 assert( pPager->tempFile==0 || eMode!=PAGER_JOURNALMODE_WAL );
43154 /* Do allow the journalmode of an in-memory database to be set to
43155 ** anything other than MEMORY or OFF
43157 if( MEMDB ){
43158 assert( eOld==PAGER_JOURNALMODE_MEMORY || eOld==PAGER_JOURNALMODE_OFF );
43159 if( eMode!=PAGER_JOURNALMODE_MEMORY && eMode!=PAGER_JOURNALMODE_OFF ){
43160 eMode = eOld;
43164 if( eMode!=eOld ){
43166 /* Change the journal mode. */
43167 assert( pPager->eState!=PAGER_ERROR );
43168 pPager->journalMode = (u8)eMode;
43170 /* When transistioning from TRUNCATE or PERSIST to any other journal
43171 ** mode except WAL, unless the pager is in locking_mode=exclusive mode,
43172 ** delete the journal file.
43174 assert( (PAGER_JOURNALMODE_TRUNCATE & 5)==1 );
43175 assert( (PAGER_JOURNALMODE_PERSIST & 5)==1 );
43176 assert( (PAGER_JOURNALMODE_DELETE & 5)==0 );
43177 assert( (PAGER_JOURNALMODE_MEMORY & 5)==4 );
43178 assert( (PAGER_JOURNALMODE_OFF & 5)==0 );
43179 assert( (PAGER_JOURNALMODE_WAL & 5)==5 );
43181 assert( isOpen(pPager->fd) || pPager->exclusiveMode );
43182 if( !pPager->exclusiveMode && (eOld & 5)==1 && (eMode & 1)==0 ){
43184 /* In this case we would like to delete the journal file. If it is
43185 ** not possible, then that is not a problem. Deleting the journal file
43186 ** here is an optimization only.
43188 ** Before deleting the journal file, obtain a RESERVED lock on the
43189 ** database file. This ensures that the journal file is not deleted
43190 ** while it is in use by some other client.
43192 sqlite3OsClose(pPager->jfd);
43193 if( pPager->eLock>=RESERVED_LOCK ){
43194 sqlite3OsDelete(pPager->pVfs, pPager->zJournal, 0);
43195 }else{
43196 int rc = SQLITE_OK;
43197 int state = pPager->eState;
43198 assert( state==PAGER_OPEN || state==PAGER_READER );
43199 if( state==PAGER_OPEN ){
43200 rc = sqlite3PagerSharedLock(pPager);
43202 if( pPager->eState==PAGER_READER ){
43203 assert( rc==SQLITE_OK );
43204 rc = pagerLockDb(pPager, RESERVED_LOCK);
43206 if( rc==SQLITE_OK ){
43207 sqlite3OsDelete(pPager->pVfs, pPager->zJournal, 0);
43209 if( rc==SQLITE_OK && state==PAGER_READER ){
43210 pagerUnlockDb(pPager, SHARED_LOCK);
43211 }else if( state==PAGER_OPEN ){
43212 pager_unlock(pPager);
43214 assert( state==pPager->eState );
43219 /* Return the new journal mode */
43220 return (int)pPager->journalMode;
43224 ** Return the current journal mode.
43226 SQLITE_PRIVATE int sqlite3PagerGetJournalMode(Pager *pPager){
43227 return (int)pPager->journalMode;
43231 ** Return TRUE if the pager is in a state where it is OK to change the
43232 ** journalmode. Journalmode changes can only happen when the database
43233 ** is unmodified.
43235 SQLITE_PRIVATE int sqlite3PagerOkToChangeJournalMode(Pager *pPager){
43236 assert( assert_pager_state(pPager) );
43237 if( pPager->eState>=PAGER_WRITER_CACHEMOD ) return 0;
43238 if( NEVER(isOpen(pPager->jfd) && pPager->journalOff>0) ) return 0;
43239 return 1;
43243 ** Get/set the size-limit used for persistent journal files.
43245 ** Setting the size limit to -1 means no limit is enforced.
43246 ** An attempt to set a limit smaller than -1 is a no-op.
43248 SQLITE_PRIVATE i64 sqlite3PagerJournalSizeLimit(Pager *pPager, i64 iLimit){
43249 if( iLimit>=-1 ){
43250 pPager->journalSizeLimit = iLimit;
43252 return pPager->journalSizeLimit;
43256 ** Return a pointer to the pPager->pBackup variable. The backup module
43257 ** in backup.c maintains the content of this variable. This module
43258 ** uses it opaquely as an argument to sqlite3BackupRestart() and
43259 ** sqlite3BackupUpdate() only.
43261 SQLITE_PRIVATE sqlite3_backup **sqlite3PagerBackupPtr(Pager *pPager){
43262 return &pPager->pBackup;
43265 #ifndef SQLITE_OMIT_WAL
43267 ** This function is called when the user invokes "PRAGMA wal_checkpoint",
43268 ** "PRAGMA wal_blocking_checkpoint" or calls the sqlite3_wal_checkpoint()
43269 ** or wal_blocking_checkpoint() API functions.
43271 ** Parameter eMode is one of SQLITE_CHECKPOINT_PASSIVE, FULL or RESTART.
43273 SQLITE_PRIVATE int sqlite3PagerCheckpoint(Pager *pPager, int eMode, int *pnLog, int *pnCkpt){
43274 int rc = SQLITE_OK;
43275 if( pPager->pWal ){
43276 rc = sqlite3WalCheckpoint(pPager->pWal, eMode,
43277 pPager->xBusyHandler, pPager->pBusyHandlerArg,
43278 pPager->ckptSyncFlags, pPager->pageSize, (u8 *)pPager->pTmpSpace,
43279 pnLog, pnCkpt
43282 return rc;
43285 SQLITE_PRIVATE int sqlite3PagerWalCallback(Pager *pPager){
43286 return sqlite3WalCallback(pPager->pWal);
43290 ** Return true if the underlying VFS for the given pager supports the
43291 ** primitives necessary for write-ahead logging.
43293 SQLITE_PRIVATE int sqlite3PagerWalSupported(Pager *pPager){
43294 const sqlite3_io_methods *pMethods = pPager->fd->pMethods;
43295 return pPager->exclusiveMode || (pMethods->iVersion>=2 && pMethods->xShmMap);
43299 ** Attempt to take an exclusive lock on the database file. If a PENDING lock
43300 ** is obtained instead, immediately release it.
43302 static int pagerExclusiveLock(Pager *pPager){
43303 int rc; /* Return code */
43305 assert( pPager->eLock==SHARED_LOCK || pPager->eLock==EXCLUSIVE_LOCK );
43306 rc = pagerLockDb(pPager, EXCLUSIVE_LOCK);
43307 if( rc!=SQLITE_OK ){
43308 /* If the attempt to grab the exclusive lock failed, release the
43309 ** pending lock that may have been obtained instead. */
43310 pagerUnlockDb(pPager, SHARED_LOCK);
43313 return rc;
43317 ** Call sqlite3WalOpen() to open the WAL handle. If the pager is in
43318 ** exclusive-locking mode when this function is called, take an EXCLUSIVE
43319 ** lock on the database file and use heap-memory to store the wal-index
43320 ** in. Otherwise, use the normal shared-memory.
43322 static int pagerOpenWal(Pager *pPager){
43323 int rc = SQLITE_OK;
43325 assert( pPager->pWal==0 && pPager->tempFile==0 );
43326 assert( pPager->eLock==SHARED_LOCK || pPager->eLock==EXCLUSIVE_LOCK || pPager->noReadlock);
43328 /* If the pager is already in exclusive-mode, the WAL module will use
43329 ** heap-memory for the wal-index instead of the VFS shared-memory
43330 ** implementation. Take the exclusive lock now, before opening the WAL
43331 ** file, to make sure this is safe.
43333 if( pPager->exclusiveMode ){
43334 rc = pagerExclusiveLock(pPager);
43337 /* Open the connection to the log file. If this operation fails,
43338 ** (e.g. due to malloc() failure), return an error code.
43340 if( rc==SQLITE_OK ){
43341 rc = sqlite3WalOpen(pPager->pVfs,
43342 pPager->fd, pPager->zWal, pPager->exclusiveMode, &pPager->pWal
43346 return rc;
43351 ** The caller must be holding a SHARED lock on the database file to call
43352 ** this function.
43354 ** If the pager passed as the first argument is open on a real database
43355 ** file (not a temp file or an in-memory database), and the WAL file
43356 ** is not already open, make an attempt to open it now. If successful,
43357 ** return SQLITE_OK. If an error occurs or the VFS used by the pager does
43358 ** not support the xShmXXX() methods, return an error code. *pbOpen is
43359 ** not modified in either case.
43361 ** If the pager is open on a temp-file (or in-memory database), or if
43362 ** the WAL file is already open, set *pbOpen to 1 and return SQLITE_OK
43363 ** without doing anything.
43365 SQLITE_PRIVATE int sqlite3PagerOpenWal(
43366 Pager *pPager, /* Pager object */
43367 int *pbOpen /* OUT: Set to true if call is a no-op */
43369 int rc = SQLITE_OK; /* Return code */
43371 assert( assert_pager_state(pPager) );
43372 assert( pPager->eState==PAGER_OPEN || pbOpen );
43373 assert( pPager->eState==PAGER_READER || !pbOpen );
43374 assert( pbOpen==0 || *pbOpen==0 );
43375 assert( pbOpen!=0 || (!pPager->tempFile && !pPager->pWal) );
43377 if( !pPager->tempFile && !pPager->pWal ){
43378 if( !sqlite3PagerWalSupported(pPager) ) return SQLITE_CANTOPEN;
43380 /* Close any rollback journal previously open */
43381 sqlite3OsClose(pPager->jfd);
43383 rc = pagerOpenWal(pPager);
43384 if( rc==SQLITE_OK ){
43385 pPager->journalMode = PAGER_JOURNALMODE_WAL;
43386 pPager->eState = PAGER_OPEN;
43388 }else{
43389 *pbOpen = 1;
43392 return rc;
43396 ** This function is called to close the connection to the log file prior
43397 ** to switching from WAL to rollback mode.
43399 ** Before closing the log file, this function attempts to take an
43400 ** EXCLUSIVE lock on the database file. If this cannot be obtained, an
43401 ** error (SQLITE_BUSY) is returned and the log connection is not closed.
43402 ** If successful, the EXCLUSIVE lock is not released before returning.
43404 SQLITE_PRIVATE int sqlite3PagerCloseWal(Pager *pPager){
43405 int rc = SQLITE_OK;
43407 assert( pPager->journalMode==PAGER_JOURNALMODE_WAL );
43409 /* If the log file is not already open, but does exist in the file-system,
43410 ** it may need to be checkpointed before the connection can switch to
43411 ** rollback mode. Open it now so this can happen.
43413 if( !pPager->pWal ){
43414 int logexists = 0;
43415 rc = pagerLockDb(pPager, SHARED_LOCK);
43416 if( rc==SQLITE_OK ){
43417 rc = sqlite3OsAccess(
43418 pPager->pVfs, pPager->zWal, SQLITE_ACCESS_EXISTS, &logexists
43421 if( rc==SQLITE_OK && logexists ){
43422 rc = pagerOpenWal(pPager);
43426 /* Checkpoint and close the log. Because an EXCLUSIVE lock is held on
43427 ** the database file, the log and log-summary files will be deleted.
43429 if( rc==SQLITE_OK && pPager->pWal ){
43430 rc = pagerExclusiveLock(pPager);
43431 if( rc==SQLITE_OK ){
43432 rc = sqlite3WalClose(pPager->pWal, pPager->ckptSyncFlags,
43433 pPager->pageSize, (u8*)pPager->pTmpSpace);
43434 pPager->pWal = 0;
43437 return rc;
43440 #ifdef SQLITE_HAS_CODEC
43442 ** This function is called by the wal module when writing page content
43443 ** into the log file.
43445 ** This function returns a pointer to a buffer containing the encrypted
43446 ** page content. If a malloc fails, this function may return NULL.
43448 SQLITE_PRIVATE void *sqlite3PagerCodec(PgHdr *pPg){
43449 void *aData = 0;
43450 CODEC2(pPg->pPager, pPg->pData, pPg->pgno, 6, return 0, aData);
43451 return aData;
43453 #endif /* SQLITE_HAS_CODEC */
43455 #endif /* !SQLITE_OMIT_WAL */
43457 #endif /* SQLITE_OMIT_DISKIO */
43459 /************** End of pager.c ***********************************************/
43460 /************** Begin file wal.c *********************************************/
43462 ** 2010 February 1
43464 ** The author disclaims copyright to this source code. In place of
43465 ** a legal notice, here is a blessing:
43467 ** May you do good and not evil.
43468 ** May you find forgiveness for yourself and forgive others.
43469 ** May you share freely, never taking more than you give.
43471 *************************************************************************
43473 ** This file contains the implementation of a write-ahead log (WAL) used in
43474 ** "journal_mode=WAL" mode.
43476 ** WRITE-AHEAD LOG (WAL) FILE FORMAT
43478 ** A WAL file consists of a header followed by zero or more "frames".
43479 ** Each frame records the revised content of a single page from the
43480 ** database file. All changes to the database are recorded by writing
43481 ** frames into the WAL. Transactions commit when a frame is written that
43482 ** contains a commit marker. A single WAL can and usually does record
43483 ** multiple transactions. Periodically, the content of the WAL is
43484 ** transferred back into the database file in an operation called a
43485 ** "checkpoint".
43487 ** A single WAL file can be used multiple times. In other words, the
43488 ** WAL can fill up with frames and then be checkpointed and then new
43489 ** frames can overwrite the old ones. A WAL always grows from beginning
43490 ** toward the end. Checksums and counters attached to each frame are
43491 ** used to determine which frames within the WAL are valid and which
43492 ** are leftovers from prior checkpoints.
43494 ** The WAL header is 32 bytes in size and consists of the following eight
43495 ** big-endian 32-bit unsigned integer values:
43497 ** 0: Magic number. 0x377f0682 or 0x377f0683
43498 ** 4: File format version. Currently 3007000
43499 ** 8: Database page size. Example: 1024
43500 ** 12: Checkpoint sequence number
43501 ** 16: Salt-1, random integer incremented with each checkpoint
43502 ** 20: Salt-2, a different random integer changing with each ckpt
43503 ** 24: Checksum-1 (first part of checksum for first 24 bytes of header).
43504 ** 28: Checksum-2 (second part of checksum for first 24 bytes of header).
43506 ** Immediately following the wal-header are zero or more frames. Each
43507 ** frame consists of a 24-byte frame-header followed by a <page-size> bytes
43508 ** of page data. The frame-header is six big-endian 32-bit unsigned
43509 ** integer values, as follows:
43511 ** 0: Page number.
43512 ** 4: For commit records, the size of the database image in pages
43513 ** after the commit. For all other records, zero.
43514 ** 8: Salt-1 (copied from the header)
43515 ** 12: Salt-2 (copied from the header)
43516 ** 16: Checksum-1.
43517 ** 20: Checksum-2.
43519 ** A frame is considered valid if and only if the following conditions are
43520 ** true:
43522 ** (1) The salt-1 and salt-2 values in the frame-header match
43523 ** salt values in the wal-header
43525 ** (2) The checksum values in the final 8 bytes of the frame-header
43526 ** exactly match the checksum computed consecutively on the
43527 ** WAL header and the first 8 bytes and the content of all frames
43528 ** up to and including the current frame.
43530 ** The checksum is computed using 32-bit big-endian integers if the
43531 ** magic number in the first 4 bytes of the WAL is 0x377f0683 and it
43532 ** is computed using little-endian if the magic number is 0x377f0682.
43533 ** The checksum values are always stored in the frame header in a
43534 ** big-endian format regardless of which byte order is used to compute
43535 ** the checksum. The checksum is computed by interpreting the input as
43536 ** an even number of unsigned 32-bit integers: x[0] through x[N]. The
43537 ** algorithm used for the checksum is as follows:
43539 ** for i from 0 to n-1 step 2:
43540 ** s0 += x[i] + s1;
43541 ** s1 += x[i+1] + s0;
43542 ** endfor
43544 ** Note that s0 and s1 are both weighted checksums using fibonacci weights
43545 ** in reverse order (the largest fibonacci weight occurs on the first element
43546 ** of the sequence being summed.) The s1 value spans all 32-bit
43547 ** terms of the sequence whereas s0 omits the final term.
43549 ** On a checkpoint, the WAL is first VFS.xSync-ed, then valid content of the
43550 ** WAL is transferred into the database, then the database is VFS.xSync-ed.
43551 ** The VFS.xSync operations serve as write barriers - all writes launched
43552 ** before the xSync must complete before any write that launches after the
43553 ** xSync begins.
43555 ** After each checkpoint, the salt-1 value is incremented and the salt-2
43556 ** value is randomized. This prevents old and new frames in the WAL from
43557 ** being considered valid at the same time and being checkpointing together
43558 ** following a crash.
43560 ** READER ALGORITHM
43562 ** To read a page from the database (call it page number P), a reader
43563 ** first checks the WAL to see if it contains page P. If so, then the
43564 ** last valid instance of page P that is a followed by a commit frame
43565 ** or is a commit frame itself becomes the value read. If the WAL
43566 ** contains no copies of page P that are valid and which are a commit
43567 ** frame or are followed by a commit frame, then page P is read from
43568 ** the database file.
43570 ** To start a read transaction, the reader records the index of the last
43571 ** valid frame in the WAL. The reader uses this recorded "mxFrame" value
43572 ** for all subsequent read operations. New transactions can be appended
43573 ** to the WAL, but as long as the reader uses its original mxFrame value
43574 ** and ignores the newly appended content, it will see a consistent snapshot
43575 ** of the database from a single point in time. This technique allows
43576 ** multiple concurrent readers to view different versions of the database
43577 ** content simultaneously.
43579 ** The reader algorithm in the previous paragraphs works correctly, but
43580 ** because frames for page P can appear anywhere within the WAL, the
43581 ** reader has to scan the entire WAL looking for page P frames. If the
43582 ** WAL is large (multiple megabytes is typical) that scan can be slow,
43583 ** and read performance suffers. To overcome this problem, a separate
43584 ** data structure called the wal-index is maintained to expedite the
43585 ** search for frames of a particular page.
43587 ** WAL-INDEX FORMAT
43589 ** Conceptually, the wal-index is shared memory, though VFS implementations
43590 ** might choose to implement the wal-index using a mmapped file. Because
43591 ** the wal-index is shared memory, SQLite does not support journal_mode=WAL
43592 ** on a network filesystem. All users of the database must be able to
43593 ** share memory.
43595 ** The wal-index is transient. After a crash, the wal-index can (and should
43596 ** be) reconstructed from the original WAL file. In fact, the VFS is required
43597 ** to either truncate or zero the header of the wal-index when the last
43598 ** connection to it closes. Because the wal-index is transient, it can
43599 ** use an architecture-specific format; it does not have to be cross-platform.
43600 ** Hence, unlike the database and WAL file formats which store all values
43601 ** as big endian, the wal-index can store multi-byte values in the native
43602 ** byte order of the host computer.
43604 ** The purpose of the wal-index is to answer this question quickly: Given
43605 ** a page number P, return the index of the last frame for page P in the WAL,
43606 ** or return NULL if there are no frames for page P in the WAL.
43608 ** The wal-index consists of a header region, followed by an one or
43609 ** more index blocks.
43611 ** The wal-index header contains the total number of frames within the WAL
43612 ** in the the mxFrame field.
43614 ** Each index block except for the first contains information on
43615 ** HASHTABLE_NPAGE frames. The first index block contains information on
43616 ** HASHTABLE_NPAGE_ONE frames. The values of HASHTABLE_NPAGE_ONE and
43617 ** HASHTABLE_NPAGE are selected so that together the wal-index header and
43618 ** first index block are the same size as all other index blocks in the
43619 ** wal-index.
43621 ** Each index block contains two sections, a page-mapping that contains the
43622 ** database page number associated with each wal frame, and a hash-table
43623 ** that allows readers to query an index block for a specific page number.
43624 ** The page-mapping is an array of HASHTABLE_NPAGE (or HASHTABLE_NPAGE_ONE
43625 ** for the first index block) 32-bit page numbers. The first entry in the
43626 ** first index-block contains the database page number corresponding to the
43627 ** first frame in the WAL file. The first entry in the second index block
43628 ** in the WAL file corresponds to the (HASHTABLE_NPAGE_ONE+1)th frame in
43629 ** the log, and so on.
43631 ** The last index block in a wal-index usually contains less than the full
43632 ** complement of HASHTABLE_NPAGE (or HASHTABLE_NPAGE_ONE) page-numbers,
43633 ** depending on the contents of the WAL file. This does not change the
43634 ** allocated size of the page-mapping array - the page-mapping array merely
43635 ** contains unused entries.
43637 ** Even without using the hash table, the last frame for page P
43638 ** can be found by scanning the page-mapping sections of each index block
43639 ** starting with the last index block and moving toward the first, and
43640 ** within each index block, starting at the end and moving toward the
43641 ** beginning. The first entry that equals P corresponds to the frame
43642 ** holding the content for that page.
43644 ** The hash table consists of HASHTABLE_NSLOT 16-bit unsigned integers.
43645 ** HASHTABLE_NSLOT = 2*HASHTABLE_NPAGE, and there is one entry in the
43646 ** hash table for each page number in the mapping section, so the hash
43647 ** table is never more than half full. The expected number of collisions
43648 ** prior to finding a match is 1. Each entry of the hash table is an
43649 ** 1-based index of an entry in the mapping section of the same
43650 ** index block. Let K be the 1-based index of the largest entry in
43651 ** the mapping section. (For index blocks other than the last, K will
43652 ** always be exactly HASHTABLE_NPAGE (4096) and for the last index block
43653 ** K will be (mxFrame%HASHTABLE_NPAGE).) Unused slots of the hash table
43654 ** contain a value of 0.
43656 ** To look for page P in the hash table, first compute a hash iKey on
43657 ** P as follows:
43659 ** iKey = (P * 383) % HASHTABLE_NSLOT
43661 ** Then start scanning entries of the hash table, starting with iKey
43662 ** (wrapping around to the beginning when the end of the hash table is
43663 ** reached) until an unused hash slot is found. Let the first unused slot
43664 ** be at index iUnused. (iUnused might be less than iKey if there was
43665 ** wrap-around.) Because the hash table is never more than half full,
43666 ** the search is guaranteed to eventually hit an unused entry. Let
43667 ** iMax be the value between iKey and iUnused, closest to iUnused,
43668 ** where aHash[iMax]==P. If there is no iMax entry (if there exists
43669 ** no hash slot such that aHash[i]==p) then page P is not in the
43670 ** current index block. Otherwise the iMax-th mapping entry of the
43671 ** current index block corresponds to the last entry that references
43672 ** page P.
43674 ** A hash search begins with the last index block and moves toward the
43675 ** first index block, looking for entries corresponding to page P. On
43676 ** average, only two or three slots in each index block need to be
43677 ** examined in order to either find the last entry for page P, or to
43678 ** establish that no such entry exists in the block. Each index block
43679 ** holds over 4000 entries. So two or three index blocks are sufficient
43680 ** to cover a typical 10 megabyte WAL file, assuming 1K pages. 8 or 10
43681 ** comparisons (on average) suffice to either locate a frame in the
43682 ** WAL or to establish that the frame does not exist in the WAL. This
43683 ** is much faster than scanning the entire 10MB WAL.
43685 ** Note that entries are added in order of increasing K. Hence, one
43686 ** reader might be using some value K0 and a second reader that started
43687 ** at a later time (after additional transactions were added to the WAL
43688 ** and to the wal-index) might be using a different value K1, where K1>K0.
43689 ** Both readers can use the same hash table and mapping section to get
43690 ** the correct result. There may be entries in the hash table with
43691 ** K>K0 but to the first reader, those entries will appear to be unused
43692 ** slots in the hash table and so the first reader will get an answer as
43693 ** if no values greater than K0 had ever been inserted into the hash table
43694 ** in the first place - which is what reader one wants. Meanwhile, the
43695 ** second reader using K1 will see additional values that were inserted
43696 ** later, which is exactly what reader two wants.
43698 ** When a rollback occurs, the value of K is decreased. Hash table entries
43699 ** that correspond to frames greater than the new K value are removed
43700 ** from the hash table at this point.
43702 #ifndef SQLITE_OMIT_WAL
43706 ** Trace output macros
43708 #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
43709 SQLITE_PRIVATE int sqlite3WalTrace = 0;
43710 # define WALTRACE(X) if(sqlite3WalTrace) sqlite3DebugPrintf X
43711 #else
43712 # define WALTRACE(X)
43713 #endif
43716 ** The maximum (and only) versions of the wal and wal-index formats
43717 ** that may be interpreted by this version of SQLite.
43719 ** If a client begins recovering a WAL file and finds that (a) the checksum
43720 ** values in the wal-header are correct and (b) the version field is not
43721 ** WAL_MAX_VERSION, recovery fails and SQLite returns SQLITE_CANTOPEN.
43723 ** Similarly, if a client successfully reads a wal-index header (i.e. the
43724 ** checksum test is successful) and finds that the version field is not
43725 ** WALINDEX_MAX_VERSION, then no read-transaction is opened and SQLite
43726 ** returns SQLITE_CANTOPEN.
43728 #define WAL_MAX_VERSION 3007000
43729 #define WALINDEX_MAX_VERSION 3007000
43732 ** Indices of various locking bytes. WAL_NREADER is the number
43733 ** of available reader locks and should be at least 3.
43735 #define WAL_WRITE_LOCK 0
43736 #define WAL_ALL_BUT_WRITE 1
43737 #define WAL_CKPT_LOCK 1
43738 #define WAL_RECOVER_LOCK 2
43739 #define WAL_READ_LOCK(I) (3+(I))
43740 #define WAL_NREADER (SQLITE_SHM_NLOCK-3)
43743 /* Object declarations */
43744 typedef struct WalIndexHdr WalIndexHdr;
43745 typedef struct WalIterator WalIterator;
43746 typedef struct WalCkptInfo WalCkptInfo;
43750 ** The following object holds a copy of the wal-index header content.
43752 ** The actual header in the wal-index consists of two copies of this
43753 ** object.
43755 ** The szPage value can be any power of 2 between 512 and 32768, inclusive.
43756 ** Or it can be 1 to represent a 65536-byte page. The latter case was
43757 ** added in 3.7.1 when support for 64K pages was added.
43759 struct WalIndexHdr {
43760 u32 iVersion; /* Wal-index version */
43761 u32 unused; /* Unused (padding) field */
43762 u32 iChange; /* Counter incremented each transaction */
43763 u8 isInit; /* 1 when initialized */
43764 u8 bigEndCksum; /* True if checksums in WAL are big-endian */
43765 u16 szPage; /* Database page size in bytes. 1==64K */
43766 u32 mxFrame; /* Index of last valid frame in the WAL */
43767 u32 nPage; /* Size of database in pages */
43768 u32 aFrameCksum[2]; /* Checksum of last frame in log */
43769 u32 aSalt[2]; /* Two salt values copied from WAL header */
43770 u32 aCksum[2]; /* Checksum over all prior fields */
43774 ** A copy of the following object occurs in the wal-index immediately
43775 ** following the second copy of the WalIndexHdr. This object stores
43776 ** information used by checkpoint.
43778 ** nBackfill is the number of frames in the WAL that have been written
43779 ** back into the database. (We call the act of moving content from WAL to
43780 ** database "backfilling".) The nBackfill number is never greater than
43781 ** WalIndexHdr.mxFrame. nBackfill can only be increased by threads
43782 ** holding the WAL_CKPT_LOCK lock (which includes a recovery thread).
43783 ** However, a WAL_WRITE_LOCK thread can move the value of nBackfill from
43784 ** mxFrame back to zero when the WAL is reset.
43786 ** There is one entry in aReadMark[] for each reader lock. If a reader
43787 ** holds read-lock K, then the value in aReadMark[K] is no greater than
43788 ** the mxFrame for that reader. The value READMARK_NOT_USED (0xffffffff)
43789 ** for any aReadMark[] means that entry is unused. aReadMark[0] is
43790 ** a special case; its value is never used and it exists as a place-holder
43791 ** to avoid having to offset aReadMark[] indexs by one. Readers holding
43792 ** WAL_READ_LOCK(0) always ignore the entire WAL and read all content
43793 ** directly from the database.
43795 ** The value of aReadMark[K] may only be changed by a thread that
43796 ** is holding an exclusive lock on WAL_READ_LOCK(K). Thus, the value of
43797 ** aReadMark[K] cannot changed while there is a reader is using that mark
43798 ** since the reader will be holding a shared lock on WAL_READ_LOCK(K).
43800 ** The checkpointer may only transfer frames from WAL to database where
43801 ** the frame numbers are less than or equal to every aReadMark[] that is
43802 ** in use (that is, every aReadMark[j] for which there is a corresponding
43803 ** WAL_READ_LOCK(j)). New readers (usually) pick the aReadMark[] with the
43804 ** largest value and will increase an unused aReadMark[] to mxFrame if there
43805 ** is not already an aReadMark[] equal to mxFrame. The exception to the
43806 ** previous sentence is when nBackfill equals mxFrame (meaning that everything
43807 ** in the WAL has been backfilled into the database) then new readers
43808 ** will choose aReadMark[0] which has value 0 and hence such reader will
43809 ** get all their all content directly from the database file and ignore
43810 ** the WAL.
43812 ** Writers normally append new frames to the end of the WAL. However,
43813 ** if nBackfill equals mxFrame (meaning that all WAL content has been
43814 ** written back into the database) and if no readers are using the WAL
43815 ** (in other words, if there are no WAL_READ_LOCK(i) where i>0) then
43816 ** the writer will first "reset" the WAL back to the beginning and start
43817 ** writing new content beginning at frame 1.
43819 ** We assume that 32-bit loads are atomic and so no locks are needed in
43820 ** order to read from any aReadMark[] entries.
43822 struct WalCkptInfo {
43823 u32 nBackfill; /* Number of WAL frames backfilled into DB */
43824 u32 aReadMark[WAL_NREADER]; /* Reader marks */
43826 #define READMARK_NOT_USED 0xffffffff
43829 /* A block of WALINDEX_LOCK_RESERVED bytes beginning at
43830 ** WALINDEX_LOCK_OFFSET is reserved for locks. Since some systems
43831 ** only support mandatory file-locks, we do not read or write data
43832 ** from the region of the file on which locks are applied.
43834 #define WALINDEX_LOCK_OFFSET (sizeof(WalIndexHdr)*2 + sizeof(WalCkptInfo))
43835 #define WALINDEX_LOCK_RESERVED 16
43836 #define WALINDEX_HDR_SIZE (WALINDEX_LOCK_OFFSET+WALINDEX_LOCK_RESERVED)
43838 /* Size of header before each frame in wal */
43839 #define WAL_FRAME_HDRSIZE 24
43841 /* Size of write ahead log header, including checksum. */
43842 /* #define WAL_HDRSIZE 24 */
43843 #define WAL_HDRSIZE 32
43845 /* WAL magic value. Either this value, or the same value with the least
43846 ** significant bit also set (WAL_MAGIC | 0x00000001) is stored in 32-bit
43847 ** big-endian format in the first 4 bytes of a WAL file.
43849 ** If the LSB is set, then the checksums for each frame within the WAL
43850 ** file are calculated by treating all data as an array of 32-bit
43851 ** big-endian words. Otherwise, they are calculated by interpreting
43852 ** all data as 32-bit little-endian words.
43854 #define WAL_MAGIC 0x377f0682
43857 ** Return the offset of frame iFrame in the write-ahead log file,
43858 ** assuming a database page size of szPage bytes. The offset returned
43859 ** is to the start of the write-ahead log frame-header.
43861 #define walFrameOffset(iFrame, szPage) ( \
43862 WAL_HDRSIZE + ((iFrame)-1)*(i64)((szPage)+WAL_FRAME_HDRSIZE) \
43866 ** An open write-ahead log file is represented by an instance of the
43867 ** following object.
43869 struct Wal {
43870 sqlite3_vfs *pVfs; /* The VFS used to create pDbFd */
43871 sqlite3_file *pDbFd; /* File handle for the database file */
43872 sqlite3_file *pWalFd; /* File handle for WAL file */
43873 u32 iCallback; /* Value to pass to log callback (or 0) */
43874 int nWiData; /* Size of array apWiData */
43875 volatile u32 **apWiData; /* Pointer to wal-index content in memory */
43876 u32 szPage; /* Database page size */
43877 i16 readLock; /* Which read lock is being held. -1 for none */
43878 u8 exclusiveMode; /* Non-zero if connection is in exclusive mode */
43879 u8 writeLock; /* True if in a write transaction */
43880 u8 ckptLock; /* True if holding a checkpoint lock */
43881 u8 readOnly; /* True if the WAL file is open read-only */
43882 WalIndexHdr hdr; /* Wal-index header for current transaction */
43883 const char *zWalName; /* Name of WAL file */
43884 u32 nCkpt; /* Checkpoint sequence counter in the wal-header */
43885 #ifdef SQLITE_DEBUG
43886 u8 lockError; /* True if a locking error has occurred */
43887 #endif
43891 ** Candidate values for Wal.exclusiveMode.
43893 #define WAL_NORMAL_MODE 0
43894 #define WAL_EXCLUSIVE_MODE 1
43895 #define WAL_HEAPMEMORY_MODE 2
43898 ** Each page of the wal-index mapping contains a hash-table made up of
43899 ** an array of HASHTABLE_NSLOT elements of the following type.
43901 typedef u16 ht_slot;
43904 ** This structure is used to implement an iterator that loops through
43905 ** all frames in the WAL in database page order. Where two or more frames
43906 ** correspond to the same database page, the iterator visits only the
43907 ** frame most recently written to the WAL (in other words, the frame with
43908 ** the largest index).
43910 ** The internals of this structure are only accessed by:
43912 ** walIteratorInit() - Create a new iterator,
43913 ** walIteratorNext() - Step an iterator,
43914 ** walIteratorFree() - Free an iterator.
43916 ** This functionality is used by the checkpoint code (see walCheckpoint()).
43918 struct WalIterator {
43919 int iPrior; /* Last result returned from the iterator */
43920 int nSegment; /* Number of entries in aSegment[] */
43921 struct WalSegment {
43922 int iNext; /* Next slot in aIndex[] not yet returned */
43923 ht_slot *aIndex; /* i0, i1, i2... such that aPgno[iN] ascend */
43924 u32 *aPgno; /* Array of page numbers. */
43925 int nEntry; /* Nr. of entries in aPgno[] and aIndex[] */
43926 int iZero; /* Frame number associated with aPgno[0] */
43927 } aSegment[1]; /* One for every 32KB page in the wal-index */
43931 ** Define the parameters of the hash tables in the wal-index file. There
43932 ** is a hash-table following every HASHTABLE_NPAGE page numbers in the
43933 ** wal-index.
43935 ** Changing any of these constants will alter the wal-index format and
43936 ** create incompatibilities.
43938 #define HASHTABLE_NPAGE 4096 /* Must be power of 2 */
43939 #define HASHTABLE_HASH_1 383 /* Should be prime */
43940 #define HASHTABLE_NSLOT (HASHTABLE_NPAGE*2) /* Must be a power of 2 */
43943 ** The block of page numbers associated with the first hash-table in a
43944 ** wal-index is smaller than usual. This is so that there is a complete
43945 ** hash-table on each aligned 32KB page of the wal-index.
43947 #define HASHTABLE_NPAGE_ONE (HASHTABLE_NPAGE - (WALINDEX_HDR_SIZE/sizeof(u32)))
43949 /* The wal-index is divided into pages of WALINDEX_PGSZ bytes each. */
43950 #define WALINDEX_PGSZ ( \
43951 sizeof(ht_slot)*HASHTABLE_NSLOT + HASHTABLE_NPAGE*sizeof(u32) \
43955 ** Obtain a pointer to the iPage'th page of the wal-index. The wal-index
43956 ** is broken into pages of WALINDEX_PGSZ bytes. Wal-index pages are
43957 ** numbered from zero.
43959 ** If this call is successful, *ppPage is set to point to the wal-index
43960 ** page and SQLITE_OK is returned. If an error (an OOM or VFS error) occurs,
43961 ** then an SQLite error code is returned and *ppPage is set to 0.
43963 static int walIndexPage(Wal *pWal, int iPage, volatile u32 **ppPage){
43964 int rc = SQLITE_OK;
43966 /* Enlarge the pWal->apWiData[] array if required */
43967 if( pWal->nWiData<=iPage ){
43968 int nByte = sizeof(u32*)*(iPage+1);
43969 volatile u32 **apNew;
43970 apNew = (volatile u32 **)sqlite3_realloc((void *)pWal->apWiData, nByte);
43971 if( !apNew ){
43972 *ppPage = 0;
43973 return SQLITE_NOMEM;
43975 memset((void*)&apNew[pWal->nWiData], 0,
43976 sizeof(u32*)*(iPage+1-pWal->nWiData));
43977 pWal->apWiData = apNew;
43978 pWal->nWiData = iPage+1;
43981 /* Request a pointer to the required page from the VFS */
43982 if( pWal->apWiData[iPage]==0 ){
43983 if( pWal->exclusiveMode==WAL_HEAPMEMORY_MODE ){
43984 pWal->apWiData[iPage] = (u32 volatile *)sqlite3MallocZero(WALINDEX_PGSZ);
43985 if( !pWal->apWiData[iPage] ) rc = SQLITE_NOMEM;
43986 }else{
43987 rc = sqlite3OsShmMap(pWal->pDbFd, iPage, WALINDEX_PGSZ,
43988 pWal->writeLock, (void volatile **)&pWal->apWiData[iPage]
43993 *ppPage = pWal->apWiData[iPage];
43994 assert( iPage==0 || *ppPage || rc!=SQLITE_OK );
43995 return rc;
43999 ** Return a pointer to the WalCkptInfo structure in the wal-index.
44001 static volatile WalCkptInfo *walCkptInfo(Wal *pWal){
44002 assert( pWal->nWiData>0 && pWal->apWiData[0] );
44003 return (volatile WalCkptInfo*)&(pWal->apWiData[0][sizeof(WalIndexHdr)/2]);
44007 ** Return a pointer to the WalIndexHdr structure in the wal-index.
44009 static volatile WalIndexHdr *walIndexHdr(Wal *pWal){
44010 assert( pWal->nWiData>0 && pWal->apWiData[0] );
44011 return (volatile WalIndexHdr*)pWal->apWiData[0];
44015 ** The argument to this macro must be of type u32. On a little-endian
44016 ** architecture, it returns the u32 value that results from interpreting
44017 ** the 4 bytes as a big-endian value. On a big-endian architecture, it
44018 ** returns the value that would be produced by intepreting the 4 bytes
44019 ** of the input value as a little-endian integer.
44021 #define BYTESWAP32(x) ( \
44022 (((x)&0x000000FF)<<24) + (((x)&0x0000FF00)<<8) \
44023 + (((x)&0x00FF0000)>>8) + (((x)&0xFF000000)>>24) \
44027 ** Generate or extend an 8 byte checksum based on the data in
44028 ** array aByte[] and the initial values of aIn[0] and aIn[1] (or
44029 ** initial values of 0 and 0 if aIn==NULL).
44031 ** The checksum is written back into aOut[] before returning.
44033 ** nByte must be a positive multiple of 8.
44035 static void walChecksumBytes(
44036 int nativeCksum, /* True for native byte-order, false for non-native */
44037 u8 *a, /* Content to be checksummed */
44038 int nByte, /* Bytes of content in a[]. Must be a multiple of 8. */
44039 const u32 *aIn, /* Initial checksum value input */
44040 u32 *aOut /* OUT: Final checksum value output */
44042 u32 s1, s2;
44043 u32 *aData = (u32 *)a;
44044 u32 *aEnd = (u32 *)&a[nByte];
44046 if( aIn ){
44047 s1 = aIn[0];
44048 s2 = aIn[1];
44049 }else{
44050 s1 = s2 = 0;
44053 assert( nByte>=8 );
44054 assert( (nByte&0x00000007)==0 );
44056 if( nativeCksum ){
44057 do {
44058 s1 += *aData++ + s2;
44059 s2 += *aData++ + s1;
44060 }while( aData<aEnd );
44061 }else{
44062 do {
44063 s1 += BYTESWAP32(aData[0]) + s2;
44064 s2 += BYTESWAP32(aData[1]) + s1;
44065 aData += 2;
44066 }while( aData<aEnd );
44069 aOut[0] = s1;
44070 aOut[1] = s2;
44073 static void walShmBarrier(Wal *pWal){
44074 if( pWal->exclusiveMode!=WAL_HEAPMEMORY_MODE ){
44075 sqlite3OsShmBarrier(pWal->pDbFd);
44080 ** Write the header information in pWal->hdr into the wal-index.
44082 ** The checksum on pWal->hdr is updated before it is written.
44084 static void walIndexWriteHdr(Wal *pWal){
44085 volatile WalIndexHdr *aHdr = walIndexHdr(pWal);
44086 const int nCksum = offsetof(WalIndexHdr, aCksum);
44088 assert( pWal->writeLock );
44089 pWal->hdr.isInit = 1;
44090 pWal->hdr.iVersion = WALINDEX_MAX_VERSION;
44091 walChecksumBytes(1, (u8*)&pWal->hdr, nCksum, 0, pWal->hdr.aCksum);
44092 memcpy((void *)&aHdr[1], (void *)&pWal->hdr, sizeof(WalIndexHdr));
44093 walShmBarrier(pWal);
44094 memcpy((void *)&aHdr[0], (void *)&pWal->hdr, sizeof(WalIndexHdr));
44098 ** This function encodes a single frame header and writes it to a buffer
44099 ** supplied by the caller. A frame-header is made up of a series of
44100 ** 4-byte big-endian integers, as follows:
44102 ** 0: Page number.
44103 ** 4: For commit records, the size of the database image in pages
44104 ** after the commit. For all other records, zero.
44105 ** 8: Salt-1 (copied from the wal-header)
44106 ** 12: Salt-2 (copied from the wal-header)
44107 ** 16: Checksum-1.
44108 ** 20: Checksum-2.
44110 static void walEncodeFrame(
44111 Wal *pWal, /* The write-ahead log */
44112 u32 iPage, /* Database page number for frame */
44113 u32 nTruncate, /* New db size (or 0 for non-commit frames) */
44114 u8 *aData, /* Pointer to page data */
44115 u8 *aFrame /* OUT: Write encoded frame here */
44117 int nativeCksum; /* True for native byte-order checksums */
44118 u32 *aCksum = pWal->hdr.aFrameCksum;
44119 assert( WAL_FRAME_HDRSIZE==24 );
44120 sqlite3Put4byte(&aFrame[0], iPage);
44121 sqlite3Put4byte(&aFrame[4], nTruncate);
44122 memcpy(&aFrame[8], pWal->hdr.aSalt, 8);
44124 nativeCksum = (pWal->hdr.bigEndCksum==SQLITE_BIGENDIAN);
44125 walChecksumBytes(nativeCksum, aFrame, 8, aCksum, aCksum);
44126 walChecksumBytes(nativeCksum, aData, pWal->szPage, aCksum, aCksum);
44128 sqlite3Put4byte(&aFrame[16], aCksum[0]);
44129 sqlite3Put4byte(&aFrame[20], aCksum[1]);
44133 ** Check to see if the frame with header in aFrame[] and content
44134 ** in aData[] is valid. If it is a valid frame, fill *piPage and
44135 ** *pnTruncate and return true. Return if the frame is not valid.
44137 static int walDecodeFrame(
44138 Wal *pWal, /* The write-ahead log */
44139 u32 *piPage, /* OUT: Database page number for frame */
44140 u32 *pnTruncate, /* OUT: New db size (or 0 if not commit) */
44141 u8 *aData, /* Pointer to page data (for checksum) */
44142 u8 *aFrame /* Frame data */
44144 int nativeCksum; /* True for native byte-order checksums */
44145 u32 *aCksum = pWal->hdr.aFrameCksum;
44146 u32 pgno; /* Page number of the frame */
44147 assert( WAL_FRAME_HDRSIZE==24 );
44149 /* A frame is only valid if the salt values in the frame-header
44150 ** match the salt values in the wal-header.
44152 if( memcmp(&pWal->hdr.aSalt, &aFrame[8], 8)!=0 ){
44153 return 0;
44156 /* A frame is only valid if the page number is creater than zero.
44158 pgno = sqlite3Get4byte(&aFrame[0]);
44159 if( pgno==0 ){
44160 return 0;
44163 /* A frame is only valid if a checksum of the WAL header,
44164 ** all prior frams, the first 16 bytes of this frame-header,
44165 ** and the frame-data matches the checksum in the last 8
44166 ** bytes of this frame-header.
44168 nativeCksum = (pWal->hdr.bigEndCksum==SQLITE_BIGENDIAN);
44169 walChecksumBytes(nativeCksum, aFrame, 8, aCksum, aCksum);
44170 walChecksumBytes(nativeCksum, aData, pWal->szPage, aCksum, aCksum);
44171 if( aCksum[0]!=sqlite3Get4byte(&aFrame[16])
44172 || aCksum[1]!=sqlite3Get4byte(&aFrame[20])
44174 /* Checksum failed. */
44175 return 0;
44178 /* If we reach this point, the frame is valid. Return the page number
44179 ** and the new database size.
44181 *piPage = pgno;
44182 *pnTruncate = sqlite3Get4byte(&aFrame[4]);
44183 return 1;
44187 #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
44189 ** Names of locks. This routine is used to provide debugging output and is not
44190 ** a part of an ordinary build.
44192 static const char *walLockName(int lockIdx){
44193 if( lockIdx==WAL_WRITE_LOCK ){
44194 return "WRITE-LOCK";
44195 }else if( lockIdx==WAL_CKPT_LOCK ){
44196 return "CKPT-LOCK";
44197 }else if( lockIdx==WAL_RECOVER_LOCK ){
44198 return "RECOVER-LOCK";
44199 }else{
44200 static char zName[15];
44201 sqlite3_snprintf(sizeof(zName), zName, "READ-LOCK[%d]",
44202 lockIdx-WAL_READ_LOCK(0));
44203 return zName;
44206 #endif /*defined(SQLITE_TEST) || defined(SQLITE_DEBUG) */
44210 ** Set or release locks on the WAL. Locks are either shared or exclusive.
44211 ** A lock cannot be moved directly between shared and exclusive - it must go
44212 ** through the unlocked state first.
44214 ** In locking_mode=EXCLUSIVE, all of these routines become no-ops.
44216 static int walLockShared(Wal *pWal, int lockIdx){
44217 int rc;
44218 if( pWal->exclusiveMode ) return SQLITE_OK;
44219 rc = sqlite3OsShmLock(pWal->pDbFd, lockIdx, 1,
44220 SQLITE_SHM_LOCK | SQLITE_SHM_SHARED);
44221 WALTRACE(("WAL%p: acquire SHARED-%s %s\n", pWal,
44222 walLockName(lockIdx), rc ? "failed" : "ok"));
44223 VVA_ONLY( pWal->lockError = (u8)(rc!=SQLITE_OK && rc!=SQLITE_BUSY); )
44224 return rc;
44226 static void walUnlockShared(Wal *pWal, int lockIdx){
44227 if( pWal->exclusiveMode ) return;
44228 (void)sqlite3OsShmLock(pWal->pDbFd, lockIdx, 1,
44229 SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED);
44230 WALTRACE(("WAL%p: release SHARED-%s\n", pWal, walLockName(lockIdx)));
44232 static int walLockExclusive(Wal *pWal, int lockIdx, int n){
44233 int rc;
44234 if( pWal->exclusiveMode ) return SQLITE_OK;
44235 rc = sqlite3OsShmLock(pWal->pDbFd, lockIdx, n,
44236 SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE);
44237 WALTRACE(("WAL%p: acquire EXCLUSIVE-%s cnt=%d %s\n", pWal,
44238 walLockName(lockIdx), n, rc ? "failed" : "ok"));
44239 VVA_ONLY( pWal->lockError = (u8)(rc!=SQLITE_OK && rc!=SQLITE_BUSY); )
44240 return rc;
44242 static void walUnlockExclusive(Wal *pWal, int lockIdx, int n){
44243 if( pWal->exclusiveMode ) return;
44244 (void)sqlite3OsShmLock(pWal->pDbFd, lockIdx, n,
44245 SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE);
44246 WALTRACE(("WAL%p: release EXCLUSIVE-%s cnt=%d\n", pWal,
44247 walLockName(lockIdx), n));
44251 ** Compute a hash on a page number. The resulting hash value must land
44252 ** between 0 and (HASHTABLE_NSLOT-1). The walHashNext() function advances
44253 ** the hash to the next value in the event of a collision.
44255 static int walHash(u32 iPage){
44256 assert( iPage>0 );
44257 assert( (HASHTABLE_NSLOT & (HASHTABLE_NSLOT-1))==0 );
44258 return (iPage*HASHTABLE_HASH_1) & (HASHTABLE_NSLOT-1);
44260 static int walNextHash(int iPriorHash){
44261 return (iPriorHash+1)&(HASHTABLE_NSLOT-1);
44265 ** Return pointers to the hash table and page number array stored on
44266 ** page iHash of the wal-index. The wal-index is broken into 32KB pages
44267 ** numbered starting from 0.
44269 ** Set output variable *paHash to point to the start of the hash table
44270 ** in the wal-index file. Set *piZero to one less than the frame
44271 ** number of the first frame indexed by this hash table. If a
44272 ** slot in the hash table is set to N, it refers to frame number
44273 ** (*piZero+N) in the log.
44275 ** Finally, set *paPgno so that *paPgno[1] is the page number of the
44276 ** first frame indexed by the hash table, frame (*piZero+1).
44278 static int walHashGet(
44279 Wal *pWal, /* WAL handle */
44280 int iHash, /* Find the iHash'th table */
44281 volatile ht_slot **paHash, /* OUT: Pointer to hash index */
44282 volatile u32 **paPgno, /* OUT: Pointer to page number array */
44283 u32 *piZero /* OUT: Frame associated with *paPgno[0] */
44285 int rc; /* Return code */
44286 volatile u32 *aPgno;
44288 rc = walIndexPage(pWal, iHash, &aPgno);
44289 assert( rc==SQLITE_OK || iHash>0 );
44291 if( rc==SQLITE_OK ){
44292 u32 iZero;
44293 volatile ht_slot *aHash;
44295 aHash = (volatile ht_slot *)&aPgno[HASHTABLE_NPAGE];
44296 if( iHash==0 ){
44297 aPgno = &aPgno[WALINDEX_HDR_SIZE/sizeof(u32)];
44298 iZero = 0;
44299 }else{
44300 iZero = HASHTABLE_NPAGE_ONE + (iHash-1)*HASHTABLE_NPAGE;
44303 *paPgno = &aPgno[-1];
44304 *paHash = aHash;
44305 *piZero = iZero;
44307 return rc;
44311 ** Return the number of the wal-index page that contains the hash-table
44312 ** and page-number array that contain entries corresponding to WAL frame
44313 ** iFrame. The wal-index is broken up into 32KB pages. Wal-index pages
44314 ** are numbered starting from 0.
44316 static int walFramePage(u32 iFrame){
44317 int iHash = (iFrame+HASHTABLE_NPAGE-HASHTABLE_NPAGE_ONE-1) / HASHTABLE_NPAGE;
44318 assert( (iHash==0 || iFrame>HASHTABLE_NPAGE_ONE)
44319 && (iHash>=1 || iFrame<=HASHTABLE_NPAGE_ONE)
44320 && (iHash<=1 || iFrame>(HASHTABLE_NPAGE_ONE+HASHTABLE_NPAGE))
44321 && (iHash>=2 || iFrame<=HASHTABLE_NPAGE_ONE+HASHTABLE_NPAGE)
44322 && (iHash<=2 || iFrame>(HASHTABLE_NPAGE_ONE+2*HASHTABLE_NPAGE))
44324 return iHash;
44328 ** Return the page number associated with frame iFrame in this WAL.
44330 static u32 walFramePgno(Wal *pWal, u32 iFrame){
44331 int iHash = walFramePage(iFrame);
44332 if( iHash==0 ){
44333 return pWal->apWiData[0][WALINDEX_HDR_SIZE/sizeof(u32) + iFrame - 1];
44335 return pWal->apWiData[iHash][(iFrame-1-HASHTABLE_NPAGE_ONE)%HASHTABLE_NPAGE];
44339 ** Remove entries from the hash table that point to WAL slots greater
44340 ** than pWal->hdr.mxFrame.
44342 ** This function is called whenever pWal->hdr.mxFrame is decreased due
44343 ** to a rollback or savepoint.
44345 ** At most only the hash table containing pWal->hdr.mxFrame needs to be
44346 ** updated. Any later hash tables will be automatically cleared when
44347 ** pWal->hdr.mxFrame advances to the point where those hash tables are
44348 ** actually needed.
44350 static void walCleanupHash(Wal *pWal){
44351 volatile ht_slot *aHash = 0; /* Pointer to hash table to clear */
44352 volatile u32 *aPgno = 0; /* Page number array for hash table */
44353 u32 iZero = 0; /* frame == (aHash[x]+iZero) */
44354 int iLimit = 0; /* Zero values greater than this */
44355 int nByte; /* Number of bytes to zero in aPgno[] */
44356 int i; /* Used to iterate through aHash[] */
44358 assert( pWal->writeLock );
44359 testcase( pWal->hdr.mxFrame==HASHTABLE_NPAGE_ONE-1 );
44360 testcase( pWal->hdr.mxFrame==HASHTABLE_NPAGE_ONE );
44361 testcase( pWal->hdr.mxFrame==HASHTABLE_NPAGE_ONE+1 );
44363 if( pWal->hdr.mxFrame==0 ) return;
44365 /* Obtain pointers to the hash-table and page-number array containing
44366 ** the entry that corresponds to frame pWal->hdr.mxFrame. It is guaranteed
44367 ** that the page said hash-table and array reside on is already mapped.
44369 assert( pWal->nWiData>walFramePage(pWal->hdr.mxFrame) );
44370 assert( pWal->apWiData[walFramePage(pWal->hdr.mxFrame)] );
44371 walHashGet(pWal, walFramePage(pWal->hdr.mxFrame), &aHash, &aPgno, &iZero);
44373 /* Zero all hash-table entries that correspond to frame numbers greater
44374 ** than pWal->hdr.mxFrame.
44376 iLimit = pWal->hdr.mxFrame - iZero;
44377 assert( iLimit>0 );
44378 for(i=0; i<HASHTABLE_NSLOT; i++){
44379 if( aHash[i]>iLimit ){
44380 aHash[i] = 0;
44384 /* Zero the entries in the aPgno array that correspond to frames with
44385 ** frame numbers greater than pWal->hdr.mxFrame.
44387 nByte = (int)((char *)aHash - (char *)&aPgno[iLimit+1]);
44388 memset((void *)&aPgno[iLimit+1], 0, nByte);
44390 #ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
44391 /* Verify that the every entry in the mapping region is still reachable
44392 ** via the hash table even after the cleanup.
44394 if( iLimit ){
44395 int i; /* Loop counter */
44396 int iKey; /* Hash key */
44397 for(i=1; i<=iLimit; i++){
44398 for(iKey=walHash(aPgno[i]); aHash[iKey]; iKey=walNextHash(iKey)){
44399 if( aHash[iKey]==i ) break;
44401 assert( aHash[iKey]==i );
44404 #endif /* SQLITE_ENABLE_EXPENSIVE_ASSERT */
44409 ** Set an entry in the wal-index that will map database page number
44410 ** pPage into WAL frame iFrame.
44412 static int walIndexAppend(Wal *pWal, u32 iFrame, u32 iPage){
44413 int rc; /* Return code */
44414 u32 iZero = 0; /* One less than frame number of aPgno[1] */
44415 volatile u32 *aPgno = 0; /* Page number array */
44416 volatile ht_slot *aHash = 0; /* Hash table */
44418 rc = walHashGet(pWal, walFramePage(iFrame), &aHash, &aPgno, &iZero);
44420 /* Assuming the wal-index file was successfully mapped, populate the
44421 ** page number array and hash table entry.
44423 if( rc==SQLITE_OK ){
44424 int iKey; /* Hash table key */
44425 int idx; /* Value to write to hash-table slot */
44426 int nCollide; /* Number of hash collisions */
44428 idx = iFrame - iZero;
44429 assert( idx <= HASHTABLE_NSLOT/2 + 1 );
44431 /* If this is the first entry to be added to this hash-table, zero the
44432 ** entire hash table and aPgno[] array before proceding.
44434 if( idx==1 ){
44435 int nByte = (int)((u8 *)&aHash[HASHTABLE_NSLOT] - (u8 *)&aPgno[1]);
44436 memset((void*)&aPgno[1], 0, nByte);
44439 /* If the entry in aPgno[] is already set, then the previous writer
44440 ** must have exited unexpectedly in the middle of a transaction (after
44441 ** writing one or more dirty pages to the WAL to free up memory).
44442 ** Remove the remnants of that writers uncommitted transaction from
44443 ** the hash-table before writing any new entries.
44445 if( aPgno[idx] ){
44446 walCleanupHash(pWal);
44447 assert( !aPgno[idx] );
44450 /* Write the aPgno[] array entry and the hash-table slot. */
44451 nCollide = idx;
44452 for(iKey=walHash(iPage); aHash[iKey]; iKey=walNextHash(iKey)){
44453 if( (nCollide--)==0 ) return SQLITE_CORRUPT_BKPT;
44455 aPgno[idx] = iPage;
44456 aHash[iKey] = (ht_slot)idx;
44458 #ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
44459 /* Verify that the number of entries in the hash table exactly equals
44460 ** the number of entries in the mapping region.
44463 int i; /* Loop counter */
44464 int nEntry = 0; /* Number of entries in the hash table */
44465 for(i=0; i<HASHTABLE_NSLOT; i++){ if( aHash[i] ) nEntry++; }
44466 assert( nEntry==idx );
44469 /* Verify that the every entry in the mapping region is reachable
44470 ** via the hash table. This turns out to be a really, really expensive
44471 ** thing to check, so only do this occasionally - not on every
44472 ** iteration.
44474 if( (idx&0x3ff)==0 ){
44475 int i; /* Loop counter */
44476 for(i=1; i<=idx; i++){
44477 for(iKey=walHash(aPgno[i]); aHash[iKey]; iKey=walNextHash(iKey)){
44478 if( aHash[iKey]==i ) break;
44480 assert( aHash[iKey]==i );
44483 #endif /* SQLITE_ENABLE_EXPENSIVE_ASSERT */
44487 return rc;
44492 ** Recover the wal-index by reading the write-ahead log file.
44494 ** This routine first tries to establish an exclusive lock on the
44495 ** wal-index to prevent other threads/processes from doing anything
44496 ** with the WAL or wal-index while recovery is running. The
44497 ** WAL_RECOVER_LOCK is also held so that other threads will know
44498 ** that this thread is running recovery. If unable to establish
44499 ** the necessary locks, this routine returns SQLITE_BUSY.
44501 static int walIndexRecover(Wal *pWal){
44502 int rc; /* Return Code */
44503 i64 nSize; /* Size of log file */
44504 u32 aFrameCksum[2] = {0, 0};
44505 int iLock; /* Lock offset to lock for checkpoint */
44506 int nLock; /* Number of locks to hold */
44508 /* Obtain an exclusive lock on all byte in the locking range not already
44509 ** locked by the caller. The caller is guaranteed to have locked the
44510 ** WAL_WRITE_LOCK byte, and may have also locked the WAL_CKPT_LOCK byte.
44511 ** If successful, the same bytes that are locked here are unlocked before
44512 ** this function returns.
44514 assert( pWal->ckptLock==1 || pWal->ckptLock==0 );
44515 assert( WAL_ALL_BUT_WRITE==WAL_WRITE_LOCK+1 );
44516 assert( WAL_CKPT_LOCK==WAL_ALL_BUT_WRITE );
44517 assert( pWal->writeLock );
44518 iLock = WAL_ALL_BUT_WRITE + pWal->ckptLock;
44519 nLock = SQLITE_SHM_NLOCK - iLock;
44520 rc = walLockExclusive(pWal, iLock, nLock);
44521 if( rc ){
44522 return rc;
44524 WALTRACE(("WAL%p: recovery begin...\n", pWal));
44526 memset(&pWal->hdr, 0, sizeof(WalIndexHdr));
44528 rc = sqlite3OsFileSize(pWal->pWalFd, &nSize);
44529 if( rc!=SQLITE_OK ){
44530 goto recovery_error;
44533 if( nSize>WAL_HDRSIZE ){
44534 u8 aBuf[WAL_HDRSIZE]; /* Buffer to load WAL header into */
44535 u8 *aFrame = 0; /* Malloc'd buffer to load entire frame */
44536 int szFrame; /* Number of bytes in buffer aFrame[] */
44537 u8 *aData; /* Pointer to data part of aFrame buffer */
44538 int iFrame; /* Index of last frame read */
44539 i64 iOffset; /* Next offset to read from log file */
44540 int szPage; /* Page size according to the log */
44541 u32 magic; /* Magic value read from WAL header */
44542 u32 version; /* Magic value read from WAL header */
44544 /* Read in the WAL header. */
44545 rc = sqlite3OsRead(pWal->pWalFd, aBuf, WAL_HDRSIZE, 0);
44546 if( rc!=SQLITE_OK ){
44547 goto recovery_error;
44550 /* If the database page size is not a power of two, or is greater than
44551 ** SQLITE_MAX_PAGE_SIZE, conclude that the WAL file contains no valid
44552 ** data. Similarly, if the 'magic' value is invalid, ignore the whole
44553 ** WAL file.
44555 magic = sqlite3Get4byte(&aBuf[0]);
44556 szPage = sqlite3Get4byte(&aBuf[8]);
44557 if( (magic&0xFFFFFFFE)!=WAL_MAGIC
44558 || szPage&(szPage-1)
44559 || szPage>SQLITE_MAX_PAGE_SIZE
44560 || szPage<512
44562 goto finished;
44564 pWal->hdr.bigEndCksum = (u8)(magic&0x00000001);
44565 pWal->szPage = szPage;
44566 pWal->nCkpt = sqlite3Get4byte(&aBuf[12]);
44567 memcpy(&pWal->hdr.aSalt, &aBuf[16], 8);
44569 /* Verify that the WAL header checksum is correct */
44570 walChecksumBytes(pWal->hdr.bigEndCksum==SQLITE_BIGENDIAN,
44571 aBuf, WAL_HDRSIZE-2*4, 0, pWal->hdr.aFrameCksum
44573 if( pWal->hdr.aFrameCksum[0]!=sqlite3Get4byte(&aBuf[24])
44574 || pWal->hdr.aFrameCksum[1]!=sqlite3Get4byte(&aBuf[28])
44576 goto finished;
44579 /* Verify that the version number on the WAL format is one that
44580 ** are able to understand */
44581 version = sqlite3Get4byte(&aBuf[4]);
44582 if( version!=WAL_MAX_VERSION ){
44583 rc = SQLITE_CANTOPEN_BKPT;
44584 goto finished;
44587 /* Malloc a buffer to read frames into. */
44588 szFrame = szPage + WAL_FRAME_HDRSIZE;
44589 aFrame = (u8 *)sqlite3_malloc(szFrame);
44590 if( !aFrame ){
44591 rc = SQLITE_NOMEM;
44592 goto recovery_error;
44594 aData = &aFrame[WAL_FRAME_HDRSIZE];
44596 /* Read all frames from the log file. */
44597 iFrame = 0;
44598 for(iOffset=WAL_HDRSIZE; (iOffset+szFrame)<=nSize; iOffset+=szFrame){
44599 u32 pgno; /* Database page number for frame */
44600 u32 nTruncate; /* dbsize field from frame header */
44601 int isValid; /* True if this frame is valid */
44603 /* Read and decode the next log frame. */
44604 rc = sqlite3OsRead(pWal->pWalFd, aFrame, szFrame, iOffset);
44605 if( rc!=SQLITE_OK ) break;
44606 isValid = walDecodeFrame(pWal, &pgno, &nTruncate, aData, aFrame);
44607 if( !isValid ) break;
44608 rc = walIndexAppend(pWal, ++iFrame, pgno);
44609 if( rc!=SQLITE_OK ) break;
44611 /* If nTruncate is non-zero, this is a commit record. */
44612 if( nTruncate ){
44613 pWal->hdr.mxFrame = iFrame;
44614 pWal->hdr.nPage = nTruncate;
44615 pWal->hdr.szPage = (u16)((szPage&0xff00) | (szPage>>16));
44616 testcase( szPage<=32768 );
44617 testcase( szPage>=65536 );
44618 aFrameCksum[0] = pWal->hdr.aFrameCksum[0];
44619 aFrameCksum[1] = pWal->hdr.aFrameCksum[1];
44623 sqlite3_free(aFrame);
44626 finished:
44627 if( rc==SQLITE_OK ){
44628 volatile WalCkptInfo *pInfo;
44629 int i;
44630 pWal->hdr.aFrameCksum[0] = aFrameCksum[0];
44631 pWal->hdr.aFrameCksum[1] = aFrameCksum[1];
44632 walIndexWriteHdr(pWal);
44634 /* Reset the checkpoint-header. This is safe because this thread is
44635 ** currently holding locks that exclude all other readers, writers and
44636 ** checkpointers.
44638 pInfo = walCkptInfo(pWal);
44639 pInfo->nBackfill = 0;
44640 pInfo->aReadMark[0] = 0;
44641 for(i=1; i<WAL_NREADER; i++) pInfo->aReadMark[i] = READMARK_NOT_USED;
44643 /* If more than one frame was recovered from the log file, report an
44644 ** event via sqlite3_log(). This is to help with identifying performance
44645 ** problems caused by applications routinely shutting down without
44646 ** checkpointing the log file.
44648 if( pWal->hdr.nPage ){
44649 sqlite3_log(SQLITE_OK, "Recovered %d frames from WAL file %s",
44650 pWal->hdr.nPage, pWal->zWalName
44655 recovery_error:
44656 WALTRACE(("WAL%p: recovery %s\n", pWal, rc ? "failed" : "ok"));
44657 walUnlockExclusive(pWal, iLock, nLock);
44658 return rc;
44662 ** Close an open wal-index.
44664 static void walIndexClose(Wal *pWal, int isDelete){
44665 if( pWal->exclusiveMode==WAL_HEAPMEMORY_MODE ){
44666 int i;
44667 for(i=0; i<pWal->nWiData; i++){
44668 sqlite3_free((void *)pWal->apWiData[i]);
44669 pWal->apWiData[i] = 0;
44671 }else{
44672 sqlite3OsShmUnmap(pWal->pDbFd, isDelete);
44677 ** Open a connection to the WAL file zWalName. The database file must
44678 ** already be opened on connection pDbFd. The buffer that zWalName points
44679 ** to must remain valid for the lifetime of the returned Wal* handle.
44681 ** A SHARED lock should be held on the database file when this function
44682 ** is called. The purpose of this SHARED lock is to prevent any other
44683 ** client from unlinking the WAL or wal-index file. If another process
44684 ** were to do this just after this client opened one of these files, the
44685 ** system would be badly broken.
44687 ** If the log file is successfully opened, SQLITE_OK is returned and
44688 ** *ppWal is set to point to a new WAL handle. If an error occurs,
44689 ** an SQLite error code is returned and *ppWal is left unmodified.
44691 SQLITE_PRIVATE int sqlite3WalOpen(
44692 sqlite3_vfs *pVfs, /* vfs module to open wal and wal-index */
44693 sqlite3_file *pDbFd, /* The open database file */
44694 const char *zWalName, /* Name of the WAL file */
44695 int bNoShm, /* True to run in heap-memory mode */
44696 Wal **ppWal /* OUT: Allocated Wal handle */
44698 int rc; /* Return Code */
44699 Wal *pRet; /* Object to allocate and return */
44700 int flags; /* Flags passed to OsOpen() */
44702 assert( zWalName && zWalName[0] );
44703 assert( pDbFd );
44705 /* In the amalgamation, the os_unix.c and os_win.c source files come before
44706 ** this source file. Verify that the #defines of the locking byte offsets
44707 ** in os_unix.c and os_win.c agree with the WALINDEX_LOCK_OFFSET value.
44709 #ifdef WIN_SHM_BASE
44710 assert( WIN_SHM_BASE==WALINDEX_LOCK_OFFSET );
44711 #endif
44712 #ifdef UNIX_SHM_BASE
44713 assert( UNIX_SHM_BASE==WALINDEX_LOCK_OFFSET );
44714 #endif
44717 /* Allocate an instance of struct Wal to return. */
44718 *ppWal = 0;
44719 pRet = (Wal*)sqlite3MallocZero(sizeof(Wal) + pVfs->szOsFile);
44720 if( !pRet ){
44721 return SQLITE_NOMEM;
44724 pRet->pVfs = pVfs;
44725 pRet->pWalFd = (sqlite3_file *)&pRet[1];
44726 pRet->pDbFd = pDbFd;
44727 pRet->readLock = -1;
44728 pRet->zWalName = zWalName;
44729 pRet->exclusiveMode = (bNoShm ? WAL_HEAPMEMORY_MODE: WAL_NORMAL_MODE);
44731 /* Open file handle on the write-ahead log file. */
44732 flags = (SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|SQLITE_OPEN_WAL);
44733 rc = sqlite3OsOpen(pVfs, zWalName, pRet->pWalFd, flags, &flags);
44734 if( rc==SQLITE_OK && flags&SQLITE_OPEN_READONLY ){
44735 pRet->readOnly = 1;
44738 if( rc!=SQLITE_OK ){
44739 walIndexClose(pRet, 0);
44740 sqlite3OsClose(pRet->pWalFd);
44741 sqlite3_free(pRet);
44742 }else{
44743 *ppWal = pRet;
44744 WALTRACE(("WAL%d: opened\n", pRet));
44746 return rc;
44750 ** Find the smallest page number out of all pages held in the WAL that
44751 ** has not been returned by any prior invocation of this method on the
44752 ** same WalIterator object. Write into *piFrame the frame index where
44753 ** that page was last written into the WAL. Write into *piPage the page
44754 ** number.
44756 ** Return 0 on success. If there are no pages in the WAL with a page
44757 ** number larger than *piPage, then return 1.
44759 static int walIteratorNext(
44760 WalIterator *p, /* Iterator */
44761 u32 *piPage, /* OUT: The page number of the next page */
44762 u32 *piFrame /* OUT: Wal frame index of next page */
44764 u32 iMin; /* Result pgno must be greater than iMin */
44765 u32 iRet = 0xFFFFFFFF; /* 0xffffffff is never a valid page number */
44766 int i; /* For looping through segments */
44768 iMin = p->iPrior;
44769 assert( iMin<0xffffffff );
44770 for(i=p->nSegment-1; i>=0; i--){
44771 struct WalSegment *pSegment = &p->aSegment[i];
44772 while( pSegment->iNext<pSegment->nEntry ){
44773 u32 iPg = pSegment->aPgno[pSegment->aIndex[pSegment->iNext]];
44774 if( iPg>iMin ){
44775 if( iPg<iRet ){
44776 iRet = iPg;
44777 *piFrame = pSegment->iZero + pSegment->aIndex[pSegment->iNext];
44779 break;
44781 pSegment->iNext++;
44785 *piPage = p->iPrior = iRet;
44786 return (iRet==0xFFFFFFFF);
44790 ** This function merges two sorted lists into a single sorted list.
44792 ** aLeft[] and aRight[] are arrays of indices. The sort key is
44793 ** aContent[aLeft[]] and aContent[aRight[]]. Upon entry, the following
44794 ** is guaranteed for all J<K:
44796 ** aContent[aLeft[J]] < aContent[aLeft[K]]
44797 ** aContent[aRight[J]] < aContent[aRight[K]]
44799 ** This routine overwrites aRight[] with a new (probably longer) sequence
44800 ** of indices such that the aRight[] contains every index that appears in
44801 ** either aLeft[] or the old aRight[] and such that the second condition
44802 ** above is still met.
44804 ** The aContent[aLeft[X]] values will be unique for all X. And the
44805 ** aContent[aRight[X]] values will be unique too. But there might be
44806 ** one or more combinations of X and Y such that
44808 ** aLeft[X]!=aRight[Y] && aContent[aLeft[X]] == aContent[aRight[Y]]
44810 ** When that happens, omit the aLeft[X] and use the aRight[Y] index.
44812 static void walMerge(
44813 const u32 *aContent, /* Pages in wal - keys for the sort */
44814 ht_slot *aLeft, /* IN: Left hand input list */
44815 int nLeft, /* IN: Elements in array *paLeft */
44816 ht_slot **paRight, /* IN/OUT: Right hand input list */
44817 int *pnRight, /* IN/OUT: Elements in *paRight */
44818 ht_slot *aTmp /* Temporary buffer */
44820 int iLeft = 0; /* Current index in aLeft */
44821 int iRight = 0; /* Current index in aRight */
44822 int iOut = 0; /* Current index in output buffer */
44823 int nRight = *pnRight;
44824 ht_slot *aRight = *paRight;
44826 assert( nLeft>0 && nRight>0 );
44827 while( iRight<nRight || iLeft<nLeft ){
44828 ht_slot logpage;
44829 Pgno dbpage;
44831 if( (iLeft<nLeft)
44832 && (iRight>=nRight || aContent[aLeft[iLeft]]<aContent[aRight[iRight]])
44834 logpage = aLeft[iLeft++];
44835 }else{
44836 logpage = aRight[iRight++];
44838 dbpage = aContent[logpage];
44840 aTmp[iOut++] = logpage;
44841 if( iLeft<nLeft && aContent[aLeft[iLeft]]==dbpage ) iLeft++;
44843 assert( iLeft>=nLeft || aContent[aLeft[iLeft]]>dbpage );
44844 assert( iRight>=nRight || aContent[aRight[iRight]]>dbpage );
44847 *paRight = aLeft;
44848 *pnRight = iOut;
44849 memcpy(aLeft, aTmp, sizeof(aTmp[0])*iOut);
44853 ** Sort the elements in list aList using aContent[] as the sort key.
44854 ** Remove elements with duplicate keys, preferring to keep the
44855 ** larger aList[] values.
44857 ** The aList[] entries are indices into aContent[]. The values in
44858 ** aList[] are to be sorted so that for all J<K:
44860 ** aContent[aList[J]] < aContent[aList[K]]
44862 ** For any X and Y such that
44864 ** aContent[aList[X]] == aContent[aList[Y]]
44866 ** Keep the larger of the two values aList[X] and aList[Y] and discard
44867 ** the smaller.
44869 static void walMergesort(
44870 const u32 *aContent, /* Pages in wal */
44871 ht_slot *aBuffer, /* Buffer of at least *pnList items to use */
44872 ht_slot *aList, /* IN/OUT: List to sort */
44873 int *pnList /* IN/OUT: Number of elements in aList[] */
44875 struct Sublist {
44876 int nList; /* Number of elements in aList */
44877 ht_slot *aList; /* Pointer to sub-list content */
44880 const int nList = *pnList; /* Size of input list */
44881 int nMerge = 0; /* Number of elements in list aMerge */
44882 ht_slot *aMerge = 0; /* List to be merged */
44883 int iList; /* Index into input list */
44884 int iSub = 0; /* Index into aSub array */
44885 struct Sublist aSub[13]; /* Array of sub-lists */
44887 memset(aSub, 0, sizeof(aSub));
44888 assert( nList<=HASHTABLE_NPAGE && nList>0 );
44889 assert( HASHTABLE_NPAGE==(1<<(ArraySize(aSub)-1)) );
44891 for(iList=0; iList<nList; iList++){
44892 nMerge = 1;
44893 aMerge = &aList[iList];
44894 for(iSub=0; iList & (1<<iSub); iSub++){
44895 struct Sublist *p = &aSub[iSub];
44896 assert( p->aList && p->nList<=(1<<iSub) );
44897 assert( p->aList==&aList[iList&~((2<<iSub)-1)] );
44898 walMerge(aContent, p->aList, p->nList, &aMerge, &nMerge, aBuffer);
44900 aSub[iSub].aList = aMerge;
44901 aSub[iSub].nList = nMerge;
44904 for(iSub++; iSub<ArraySize(aSub); iSub++){
44905 if( nList & (1<<iSub) ){
44906 struct Sublist *p = &aSub[iSub];
44907 assert( p->nList<=(1<<iSub) );
44908 assert( p->aList==&aList[nList&~((2<<iSub)-1)] );
44909 walMerge(aContent, p->aList, p->nList, &aMerge, &nMerge, aBuffer);
44912 assert( aMerge==aList );
44913 *pnList = nMerge;
44915 #ifdef SQLITE_DEBUG
44917 int i;
44918 for(i=1; i<*pnList; i++){
44919 assert( aContent[aList[i]] > aContent[aList[i-1]] );
44922 #endif
44926 ** Free an iterator allocated by walIteratorInit().
44928 static void walIteratorFree(WalIterator *p){
44929 sqlite3ScratchFree(p);
44933 ** Construct a WalInterator object that can be used to loop over all
44934 ** pages in the WAL in ascending order. The caller must hold the checkpoint
44935 ** lock.
44937 ** On success, make *pp point to the newly allocated WalInterator object
44938 ** return SQLITE_OK. Otherwise, return an error code. If this routine
44939 ** returns an error, the value of *pp is undefined.
44941 ** The calling routine should invoke walIteratorFree() to destroy the
44942 ** WalIterator object when it has finished with it.
44944 static int walIteratorInit(Wal *pWal, WalIterator **pp){
44945 WalIterator *p; /* Return value */
44946 int nSegment; /* Number of segments to merge */
44947 u32 iLast; /* Last frame in log */
44948 int nByte; /* Number of bytes to allocate */
44949 int i; /* Iterator variable */
44950 ht_slot *aTmp; /* Temp space used by merge-sort */
44951 int rc = SQLITE_OK; /* Return Code */
44953 /* This routine only runs while holding the checkpoint lock. And
44954 ** it only runs if there is actually content in the log (mxFrame>0).
44956 assert( pWal->ckptLock && pWal->hdr.mxFrame>0 );
44957 iLast = pWal->hdr.mxFrame;
44959 /* Allocate space for the WalIterator object. */
44960 nSegment = walFramePage(iLast) + 1;
44961 nByte = sizeof(WalIterator)
44962 + (nSegment-1)*sizeof(struct WalSegment)
44963 + iLast*sizeof(ht_slot);
44964 p = (WalIterator *)sqlite3ScratchMalloc(nByte);
44965 if( !p ){
44966 return SQLITE_NOMEM;
44968 memset(p, 0, nByte);
44969 p->nSegment = nSegment;
44971 /* Allocate temporary space used by the merge-sort routine. This block
44972 ** of memory will be freed before this function returns.
44974 aTmp = (ht_slot *)sqlite3ScratchMalloc(
44975 sizeof(ht_slot) * (iLast>HASHTABLE_NPAGE?HASHTABLE_NPAGE:iLast)
44977 if( !aTmp ){
44978 rc = SQLITE_NOMEM;
44981 for(i=0; rc==SQLITE_OK && i<nSegment; i++){
44982 volatile ht_slot *aHash;
44983 u32 iZero;
44984 volatile u32 *aPgno;
44986 rc = walHashGet(pWal, i, &aHash, &aPgno, &iZero);
44987 if( rc==SQLITE_OK ){
44988 int j; /* Counter variable */
44989 int nEntry; /* Number of entries in this segment */
44990 ht_slot *aIndex; /* Sorted index for this segment */
44992 aPgno++;
44993 if( (i+1)==nSegment ){
44994 nEntry = (int)(iLast - iZero);
44995 }else{
44996 nEntry = (int)((u32*)aHash - (u32*)aPgno);
44998 aIndex = &((ht_slot *)&p->aSegment[p->nSegment])[iZero];
44999 iZero++;
45001 for(j=0; j<nEntry; j++){
45002 aIndex[j] = (ht_slot)j;
45004 walMergesort((u32 *)aPgno, aTmp, aIndex, &nEntry);
45005 p->aSegment[i].iZero = iZero;
45006 p->aSegment[i].nEntry = nEntry;
45007 p->aSegment[i].aIndex = aIndex;
45008 p->aSegment[i].aPgno = (u32 *)aPgno;
45011 sqlite3ScratchFree(aTmp);
45013 if( rc!=SQLITE_OK ){
45014 walIteratorFree(p);
45016 *pp = p;
45017 return rc;
45021 ** Attempt to obtain the exclusive WAL lock defined by parameters lockIdx and
45022 ** n. If the attempt fails and parameter xBusy is not NULL, then it is a
45023 ** busy-handler function. Invoke it and retry the lock until either the
45024 ** lock is successfully obtained or the busy-handler returns 0.
45026 static int walBusyLock(
45027 Wal *pWal, /* WAL connection */
45028 int (*xBusy)(void*), /* Function to call when busy */
45029 void *pBusyArg, /* Context argument for xBusyHandler */
45030 int lockIdx, /* Offset of first byte to lock */
45031 int n /* Number of bytes to lock */
45033 int rc;
45034 do {
45035 rc = walLockExclusive(pWal, lockIdx, n);
45036 }while( xBusy && rc==SQLITE_BUSY && xBusy(pBusyArg) );
45037 return rc;
45041 ** The cache of the wal-index header must be valid to call this function.
45042 ** Return the page-size in bytes used by the database.
45044 static int walPagesize(Wal *pWal){
45045 return (pWal->hdr.szPage&0xfe00) + ((pWal->hdr.szPage&0x0001)<<16);
45049 ** Copy as much content as we can from the WAL back into the database file
45050 ** in response to an sqlite3_wal_checkpoint() request or the equivalent.
45052 ** The amount of information copies from WAL to database might be limited
45053 ** by active readers. This routine will never overwrite a database page
45054 ** that a concurrent reader might be using.
45056 ** All I/O barrier operations (a.k.a fsyncs) occur in this routine when
45057 ** SQLite is in WAL-mode in synchronous=NORMAL. That means that if
45058 ** checkpoints are always run by a background thread or background
45059 ** process, foreground threads will never block on a lengthy fsync call.
45061 ** Fsync is called on the WAL before writing content out of the WAL and
45062 ** into the database. This ensures that if the new content is persistent
45063 ** in the WAL and can be recovered following a power-loss or hard reset.
45065 ** Fsync is also called on the database file if (and only if) the entire
45066 ** WAL content is copied into the database file. This second fsync makes
45067 ** it safe to delete the WAL since the new content will persist in the
45068 ** database file.
45070 ** This routine uses and updates the nBackfill field of the wal-index header.
45071 ** This is the only routine tha will increase the value of nBackfill.
45072 ** (A WAL reset or recovery will revert nBackfill to zero, but not increase
45073 ** its value.)
45075 ** The caller must be holding sufficient locks to ensure that no other
45076 ** checkpoint is running (in any other thread or process) at the same
45077 ** time.
45079 static int walCheckpoint(
45080 Wal *pWal, /* Wal connection */
45081 int eMode, /* One of PASSIVE, FULL or RESTART */
45082 int (*xBusyCall)(void*), /* Function to call when busy */
45083 void *pBusyArg, /* Context argument for xBusyHandler */
45084 int sync_flags, /* Flags for OsSync() (or 0) */
45085 u8 *zBuf /* Temporary buffer to use */
45087 int rc; /* Return code */
45088 int szPage; /* Database page-size */
45089 WalIterator *pIter = 0; /* Wal iterator context */
45090 u32 iDbpage = 0; /* Next database page to write */
45091 u32 iFrame = 0; /* Wal frame containing data for iDbpage */
45092 u32 mxSafeFrame; /* Max frame that can be backfilled */
45093 u32 mxPage; /* Max database page to write */
45094 int i; /* Loop counter */
45095 volatile WalCkptInfo *pInfo; /* The checkpoint status information */
45096 int (*xBusy)(void*) = 0; /* Function to call when waiting for locks */
45098 szPage = walPagesize(pWal);
45099 testcase( szPage<=32768 );
45100 testcase( szPage>=65536 );
45101 pInfo = walCkptInfo(pWal);
45102 if( pInfo->nBackfill>=pWal->hdr.mxFrame ) return SQLITE_OK;
45104 /* Allocate the iterator */
45105 rc = walIteratorInit(pWal, &pIter);
45106 if( rc!=SQLITE_OK ){
45107 return rc;
45109 assert( pIter );
45111 if( eMode!=SQLITE_CHECKPOINT_PASSIVE ) xBusy = xBusyCall;
45113 /* Compute in mxSafeFrame the index of the last frame of the WAL that is
45114 ** safe to write into the database. Frames beyond mxSafeFrame might
45115 ** overwrite database pages that are in use by active readers and thus
45116 ** cannot be backfilled from the WAL.
45118 mxSafeFrame = pWal->hdr.mxFrame;
45119 mxPage = pWal->hdr.nPage;
45120 for(i=1; i<WAL_NREADER; i++){
45121 u32 y = pInfo->aReadMark[i];
45122 if( mxSafeFrame>y ){
45123 assert( y<=pWal->hdr.mxFrame );
45124 rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_READ_LOCK(i), 1);
45125 if( rc==SQLITE_OK ){
45126 pInfo->aReadMark[i] = READMARK_NOT_USED;
45127 walUnlockExclusive(pWal, WAL_READ_LOCK(i), 1);
45128 }else if( rc==SQLITE_BUSY ){
45129 mxSafeFrame = y;
45130 xBusy = 0;
45131 }else{
45132 goto walcheckpoint_out;
45137 if( pInfo->nBackfill<mxSafeFrame
45138 && (rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_READ_LOCK(0), 1))==SQLITE_OK
45140 i64 nSize; /* Current size of database file */
45141 u32 nBackfill = pInfo->nBackfill;
45143 /* Sync the WAL to disk */
45144 if( sync_flags ){
45145 rc = sqlite3OsSync(pWal->pWalFd, sync_flags);
45148 /* If the database file may grow as a result of this checkpoint, hint
45149 ** about the eventual size of the db file to the VFS layer.
45151 if( rc==SQLITE_OK ){
45152 i64 nReq = ((i64)mxPage * szPage);
45153 rc = sqlite3OsFileSize(pWal->pDbFd, &nSize);
45154 if( rc==SQLITE_OK && nSize<nReq ){
45155 sqlite3OsFileControl(pWal->pDbFd, SQLITE_FCNTL_SIZE_HINT, &nReq);
45159 /* Iterate through the contents of the WAL, copying data to the db file. */
45160 while( rc==SQLITE_OK && 0==walIteratorNext(pIter, &iDbpage, &iFrame) ){
45161 i64 iOffset;
45162 assert( walFramePgno(pWal, iFrame)==iDbpage );
45163 if( iFrame<=nBackfill || iFrame>mxSafeFrame || iDbpage>mxPage ) continue;
45164 iOffset = walFrameOffset(iFrame, szPage) + WAL_FRAME_HDRSIZE;
45165 /* testcase( IS_BIG_INT(iOffset) ); // requires a 4GiB WAL file */
45166 rc = sqlite3OsRead(pWal->pWalFd, zBuf, szPage, iOffset);
45167 if( rc!=SQLITE_OK ) break;
45168 iOffset = (iDbpage-1)*(i64)szPage;
45169 testcase( IS_BIG_INT(iOffset) );
45170 rc = sqlite3OsWrite(pWal->pDbFd, zBuf, szPage, iOffset);
45171 if( rc!=SQLITE_OK ) break;
45174 /* If work was actually accomplished... */
45175 if( rc==SQLITE_OK ){
45176 if( mxSafeFrame==walIndexHdr(pWal)->mxFrame ){
45177 i64 szDb = pWal->hdr.nPage*(i64)szPage;
45178 testcase( IS_BIG_INT(szDb) );
45179 rc = sqlite3OsTruncate(pWal->pDbFd, szDb);
45180 if( rc==SQLITE_OK && sync_flags ){
45181 rc = sqlite3OsSync(pWal->pDbFd, sync_flags);
45184 if( rc==SQLITE_OK ){
45185 pInfo->nBackfill = mxSafeFrame;
45189 /* Release the reader lock held while backfilling */
45190 walUnlockExclusive(pWal, WAL_READ_LOCK(0), 1);
45193 if( rc==SQLITE_BUSY ){
45194 /* Reset the return code so as not to report a checkpoint failure
45195 ** just because there are active readers. */
45196 rc = SQLITE_OK;
45199 /* If this is an SQLITE_CHECKPOINT_RESTART operation, and the entire wal
45200 ** file has been copied into the database file, then block until all
45201 ** readers have finished using the wal file. This ensures that the next
45202 ** process to write to the database restarts the wal file.
45204 if( rc==SQLITE_OK && eMode!=SQLITE_CHECKPOINT_PASSIVE ){
45205 assert( pWal->writeLock );
45206 if( pInfo->nBackfill<pWal->hdr.mxFrame ){
45207 rc = SQLITE_BUSY;
45208 }else if( eMode==SQLITE_CHECKPOINT_RESTART ){
45209 assert( mxSafeFrame==pWal->hdr.mxFrame );
45210 rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_READ_LOCK(1), WAL_NREADER-1);
45211 if( rc==SQLITE_OK ){
45212 walUnlockExclusive(pWal, WAL_READ_LOCK(1), WAL_NREADER-1);
45217 walcheckpoint_out:
45218 walIteratorFree(pIter);
45219 return rc;
45223 ** Close a connection to a log file.
45225 SQLITE_PRIVATE int sqlite3WalClose(
45226 Wal *pWal, /* Wal to close */
45227 int sync_flags, /* Flags to pass to OsSync() (or 0) */
45228 int nBuf,
45229 u8 *zBuf /* Buffer of at least nBuf bytes */
45231 int rc = SQLITE_OK;
45232 if( pWal ){
45233 int isDelete = 0; /* True to unlink wal and wal-index files */
45235 /* If an EXCLUSIVE lock can be obtained on the database file (using the
45236 ** ordinary, rollback-mode locking methods, this guarantees that the
45237 ** connection associated with this log file is the only connection to
45238 ** the database. In this case checkpoint the database and unlink both
45239 ** the wal and wal-index files.
45241 ** The EXCLUSIVE lock is not released before returning.
45243 rc = sqlite3OsLock(pWal->pDbFd, SQLITE_LOCK_EXCLUSIVE);
45244 if( rc==SQLITE_OK ){
45245 if( pWal->exclusiveMode==WAL_NORMAL_MODE ){
45246 pWal->exclusiveMode = WAL_EXCLUSIVE_MODE;
45248 rc = sqlite3WalCheckpoint(
45249 pWal, SQLITE_CHECKPOINT_PASSIVE, 0, 0, sync_flags, nBuf, zBuf, 0, 0
45251 if( rc==SQLITE_OK ){
45252 isDelete = 1;
45256 walIndexClose(pWal, isDelete);
45257 sqlite3OsClose(pWal->pWalFd);
45258 if( isDelete ){
45259 sqlite3OsDelete(pWal->pVfs, pWal->zWalName, 0);
45261 WALTRACE(("WAL%p: closed\n", pWal));
45262 sqlite3_free((void *)pWal->apWiData);
45263 sqlite3_free(pWal);
45265 return rc;
45269 ** Try to read the wal-index header. Return 0 on success and 1 if
45270 ** there is a problem.
45272 ** The wal-index is in shared memory. Another thread or process might
45273 ** be writing the header at the same time this procedure is trying to
45274 ** read it, which might result in inconsistency. A dirty read is detected
45275 ** by verifying that both copies of the header are the same and also by
45276 ** a checksum on the header.
45278 ** If and only if the read is consistent and the header is different from
45279 ** pWal->hdr, then pWal->hdr is updated to the content of the new header
45280 ** and *pChanged is set to 1.
45282 ** If the checksum cannot be verified return non-zero. If the header
45283 ** is read successfully and the checksum verified, return zero.
45285 static int walIndexTryHdr(Wal *pWal, int *pChanged){
45286 u32 aCksum[2]; /* Checksum on the header content */
45287 WalIndexHdr h1, h2; /* Two copies of the header content */
45288 WalIndexHdr volatile *aHdr; /* Header in shared memory */
45290 /* The first page of the wal-index must be mapped at this point. */
45291 assert( pWal->nWiData>0 && pWal->apWiData[0] );
45293 /* Read the header. This might happen concurrently with a write to the
45294 ** same area of shared memory on a different CPU in a SMP,
45295 ** meaning it is possible that an inconsistent snapshot is read
45296 ** from the file. If this happens, return non-zero.
45298 ** There are two copies of the header at the beginning of the wal-index.
45299 ** When reading, read [0] first then [1]. Writes are in the reverse order.
45300 ** Memory barriers are used to prevent the compiler or the hardware from
45301 ** reordering the reads and writes.
45303 aHdr = walIndexHdr(pWal);
45304 memcpy(&h1, (void *)&aHdr[0], sizeof(h1));
45305 walShmBarrier(pWal);
45306 memcpy(&h2, (void *)&aHdr[1], sizeof(h2));
45308 if( memcmp(&h1, &h2, sizeof(h1))!=0 ){
45309 return 1; /* Dirty read */
45311 if( h1.isInit==0 ){
45312 return 1; /* Malformed header - probably all zeros */
45314 walChecksumBytes(1, (u8*)&h1, sizeof(h1)-sizeof(h1.aCksum), 0, aCksum);
45315 if( aCksum[0]!=h1.aCksum[0] || aCksum[1]!=h1.aCksum[1] ){
45316 return 1; /* Checksum does not match */
45319 if( memcmp(&pWal->hdr, &h1, sizeof(WalIndexHdr)) ){
45320 *pChanged = 1;
45321 memcpy(&pWal->hdr, &h1, sizeof(WalIndexHdr));
45322 pWal->szPage = (pWal->hdr.szPage&0xfe00) + ((pWal->hdr.szPage&0x0001)<<16);
45323 testcase( pWal->szPage<=32768 );
45324 testcase( pWal->szPage>=65536 );
45327 /* The header was successfully read. Return zero. */
45328 return 0;
45332 ** Read the wal-index header from the wal-index and into pWal->hdr.
45333 ** If the wal-header appears to be corrupt, try to reconstruct the
45334 ** wal-index from the WAL before returning.
45336 ** Set *pChanged to 1 if the wal-index header value in pWal->hdr is
45337 ** changed by this opertion. If pWal->hdr is unchanged, set *pChanged
45338 ** to 0.
45340 ** If the wal-index header is successfully read, return SQLITE_OK.
45341 ** Otherwise an SQLite error code.
45343 static int walIndexReadHdr(Wal *pWal, int *pChanged){
45344 int rc; /* Return code */
45345 int badHdr; /* True if a header read failed */
45346 volatile u32 *page0; /* Chunk of wal-index containing header */
45348 /* Ensure that page 0 of the wal-index (the page that contains the
45349 ** wal-index header) is mapped. Return early if an error occurs here.
45351 assert( pChanged );
45352 rc = walIndexPage(pWal, 0, &page0);
45353 if( rc!=SQLITE_OK ){
45354 return rc;
45356 assert( page0 || pWal->writeLock==0 );
45358 /* If the first page of the wal-index has been mapped, try to read the
45359 ** wal-index header immediately, without holding any lock. This usually
45360 ** works, but may fail if the wal-index header is corrupt or currently
45361 ** being modified by another thread or process.
45363 badHdr = (page0 ? walIndexTryHdr(pWal, pChanged) : 1);
45365 /* If the first attempt failed, it might have been due to a race
45366 ** with a writer. So get a WRITE lock and try again.
45368 assert( badHdr==0 || pWal->writeLock==0 );
45369 if( badHdr && SQLITE_OK==(rc = walLockExclusive(pWal, WAL_WRITE_LOCK, 1)) ){
45370 pWal->writeLock = 1;
45371 if( SQLITE_OK==(rc = walIndexPage(pWal, 0, &page0)) ){
45372 badHdr = walIndexTryHdr(pWal, pChanged);
45373 if( badHdr ){
45374 /* If the wal-index header is still malformed even while holding
45375 ** a WRITE lock, it can only mean that the header is corrupted and
45376 ** needs to be reconstructed. So run recovery to do exactly that.
45378 rc = walIndexRecover(pWal);
45379 *pChanged = 1;
45382 pWal->writeLock = 0;
45383 walUnlockExclusive(pWal, WAL_WRITE_LOCK, 1);
45386 /* If the header is read successfully, check the version number to make
45387 ** sure the wal-index was not constructed with some future format that
45388 ** this version of SQLite cannot understand.
45390 if( badHdr==0 && pWal->hdr.iVersion!=WALINDEX_MAX_VERSION ){
45391 rc = SQLITE_CANTOPEN_BKPT;
45394 return rc;
45398 ** This is the value that walTryBeginRead returns when it needs to
45399 ** be retried.
45401 #define WAL_RETRY (-1)
45404 ** Attempt to start a read transaction. This might fail due to a race or
45405 ** other transient condition. When that happens, it returns WAL_RETRY to
45406 ** indicate to the caller that it is safe to retry immediately.
45408 ** On success return SQLITE_OK. On a permanent failure (such an
45409 ** I/O error or an SQLITE_BUSY because another process is running
45410 ** recovery) return a positive error code.
45412 ** The useWal parameter is true to force the use of the WAL and disable
45413 ** the case where the WAL is bypassed because it has been completely
45414 ** checkpointed. If useWal==0 then this routine calls walIndexReadHdr()
45415 ** to make a copy of the wal-index header into pWal->hdr. If the
45416 ** wal-index header has changed, *pChanged is set to 1 (as an indication
45417 ** to the caller that the local paget cache is obsolete and needs to be
45418 ** flushed.) When useWal==1, the wal-index header is assumed to already
45419 ** be loaded and the pChanged parameter is unused.
45421 ** The caller must set the cnt parameter to the number of prior calls to
45422 ** this routine during the current read attempt that returned WAL_RETRY.
45423 ** This routine will start taking more aggressive measures to clear the
45424 ** race conditions after multiple WAL_RETRY returns, and after an excessive
45425 ** number of errors will ultimately return SQLITE_PROTOCOL. The
45426 ** SQLITE_PROTOCOL return indicates that some other process has gone rogue
45427 ** and is not honoring the locking protocol. There is a vanishingly small
45428 ** chance that SQLITE_PROTOCOL could be returned because of a run of really
45429 ** bad luck when there is lots of contention for the wal-index, but that
45430 ** possibility is so small that it can be safely neglected, we believe.
45432 ** On success, this routine obtains a read lock on
45433 ** WAL_READ_LOCK(pWal->readLock). The pWal->readLock integer is
45434 ** in the range 0 <= pWal->readLock < WAL_NREADER. If pWal->readLock==(-1)
45435 ** that means the Wal does not hold any read lock. The reader must not
45436 ** access any database page that is modified by a WAL frame up to and
45437 ** including frame number aReadMark[pWal->readLock]. The reader will
45438 ** use WAL frames up to and including pWal->hdr.mxFrame if pWal->readLock>0
45439 ** Or if pWal->readLock==0, then the reader will ignore the WAL
45440 ** completely and get all content directly from the database file.
45441 ** If the useWal parameter is 1 then the WAL will never be ignored and
45442 ** this routine will always set pWal->readLock>0 on success.
45443 ** When the read transaction is completed, the caller must release the
45444 ** lock on WAL_READ_LOCK(pWal->readLock) and set pWal->readLock to -1.
45446 ** This routine uses the nBackfill and aReadMark[] fields of the header
45447 ** to select a particular WAL_READ_LOCK() that strives to let the
45448 ** checkpoint process do as much work as possible. This routine might
45449 ** update values of the aReadMark[] array in the header, but if it does
45450 ** so it takes care to hold an exclusive lock on the corresponding
45451 ** WAL_READ_LOCK() while changing values.
45453 static int walTryBeginRead(Wal *pWal, int *pChanged, int useWal, int cnt){
45454 volatile WalCkptInfo *pInfo; /* Checkpoint information in wal-index */
45455 u32 mxReadMark; /* Largest aReadMark[] value */
45456 int mxI; /* Index of largest aReadMark[] value */
45457 int i; /* Loop counter */
45458 int rc = SQLITE_OK; /* Return code */
45460 assert( pWal->readLock<0 ); /* Not currently locked */
45462 /* Take steps to avoid spinning forever if there is a protocol error.
45464 ** Circumstances that cause a RETRY should only last for the briefest
45465 ** instances of time. No I/O or other system calls are done while the
45466 ** locks are held, so the locks should not be held for very long. But
45467 ** if we are unlucky, another process that is holding a lock might get
45468 ** paged out or take a page-fault that is time-consuming to resolve,
45469 ** during the few nanoseconds that it is holding the lock. In that case,
45470 ** it might take longer than normal for the lock to free.
45472 ** After 5 RETRYs, we begin calling sqlite3OsSleep(). The first few
45473 ** calls to sqlite3OsSleep() have a delay of 1 microsecond. Really this
45474 ** is more of a scheduler yield than an actual delay. But on the 10th
45475 ** an subsequent retries, the delays start becoming longer and longer,
45476 ** so that on the 100th (and last) RETRY we delay for 21 milliseconds.
45477 ** The total delay time before giving up is less than 1 second.
45479 if( cnt>5 ){
45480 int nDelay = 1; /* Pause time in microseconds */
45481 if( cnt>100 ){
45482 VVA_ONLY( pWal->lockError = 1; )
45483 return SQLITE_PROTOCOL;
45485 if( cnt>=10 ) nDelay = (cnt-9)*238; /* Max delay 21ms. Total delay 996ms */
45486 sqlite3OsSleep(pWal->pVfs, nDelay);
45489 if( !useWal ){
45490 rc = walIndexReadHdr(pWal, pChanged);
45491 if( rc==SQLITE_BUSY ){
45492 /* If there is not a recovery running in another thread or process
45493 ** then convert BUSY errors to WAL_RETRY. If recovery is known to
45494 ** be running, convert BUSY to BUSY_RECOVERY. There is a race here
45495 ** which might cause WAL_RETRY to be returned even if BUSY_RECOVERY
45496 ** would be technically correct. But the race is benign since with
45497 ** WAL_RETRY this routine will be called again and will probably be
45498 ** right on the second iteration.
45500 if( pWal->apWiData[0]==0 ){
45501 /* This branch is taken when the xShmMap() method returns SQLITE_BUSY.
45502 ** We assume this is a transient condition, so return WAL_RETRY. The
45503 ** xShmMap() implementation used by the default unix and win32 VFS
45504 ** modules may return SQLITE_BUSY due to a race condition in the
45505 ** code that determines whether or not the shared-memory region
45506 ** must be zeroed before the requested page is returned.
45508 rc = WAL_RETRY;
45509 }else if( SQLITE_OK==(rc = walLockShared(pWal, WAL_RECOVER_LOCK)) ){
45510 walUnlockShared(pWal, WAL_RECOVER_LOCK);
45511 rc = WAL_RETRY;
45512 }else if( rc==SQLITE_BUSY ){
45513 rc = SQLITE_BUSY_RECOVERY;
45516 if( rc!=SQLITE_OK ){
45517 return rc;
45521 pInfo = walCkptInfo(pWal);
45522 if( !useWal && pInfo->nBackfill==pWal->hdr.mxFrame ){
45523 /* The WAL has been completely backfilled (or it is empty).
45524 ** and can be safely ignored.
45526 rc = walLockShared(pWal, WAL_READ_LOCK(0));
45527 walShmBarrier(pWal);
45528 if( rc==SQLITE_OK ){
45529 if( memcmp((void *)walIndexHdr(pWal), &pWal->hdr, sizeof(WalIndexHdr)) ){
45530 /* It is not safe to allow the reader to continue here if frames
45531 ** may have been appended to the log before READ_LOCK(0) was obtained.
45532 ** When holding READ_LOCK(0), the reader ignores the entire log file,
45533 ** which implies that the database file contains a trustworthy
45534 ** snapshoT. Since holding READ_LOCK(0) prevents a checkpoint from
45535 ** happening, this is usually correct.
45537 ** However, if frames have been appended to the log (or if the log
45538 ** is wrapped and written for that matter) before the READ_LOCK(0)
45539 ** is obtained, that is not necessarily true. A checkpointer may
45540 ** have started to backfill the appended frames but crashed before
45541 ** it finished. Leaving a corrupt image in the database file.
45543 walUnlockShared(pWal, WAL_READ_LOCK(0));
45544 return WAL_RETRY;
45546 pWal->readLock = 0;
45547 return SQLITE_OK;
45548 }else if( rc!=SQLITE_BUSY ){
45549 return rc;
45553 /* If we get this far, it means that the reader will want to use
45554 ** the WAL to get at content from recent commits. The job now is
45555 ** to select one of the aReadMark[] entries that is closest to
45556 ** but not exceeding pWal->hdr.mxFrame and lock that entry.
45558 mxReadMark = 0;
45559 mxI = 0;
45560 for(i=1; i<WAL_NREADER; i++){
45561 u32 thisMark = pInfo->aReadMark[i];
45562 if( mxReadMark<=thisMark && thisMark<=pWal->hdr.mxFrame ){
45563 assert( thisMark!=READMARK_NOT_USED );
45564 mxReadMark = thisMark;
45565 mxI = i;
45568 /* There was once an "if" here. The extra "{" is to preserve indentation. */
45570 if( mxReadMark < pWal->hdr.mxFrame || mxI==0 ){
45571 for(i=1; i<WAL_NREADER; i++){
45572 rc = walLockExclusive(pWal, WAL_READ_LOCK(i), 1);
45573 if( rc==SQLITE_OK ){
45574 mxReadMark = pInfo->aReadMark[i] = pWal->hdr.mxFrame;
45575 mxI = i;
45576 walUnlockExclusive(pWal, WAL_READ_LOCK(i), 1);
45577 break;
45578 }else if( rc!=SQLITE_BUSY ){
45579 return rc;
45583 if( mxI==0 ){
45584 assert( rc==SQLITE_BUSY );
45585 return WAL_RETRY;
45588 rc = walLockShared(pWal, WAL_READ_LOCK(mxI));
45589 if( rc ){
45590 return rc==SQLITE_BUSY ? WAL_RETRY : rc;
45592 /* Now that the read-lock has been obtained, check that neither the
45593 ** value in the aReadMark[] array or the contents of the wal-index
45594 ** header have changed.
45596 ** It is necessary to check that the wal-index header did not change
45597 ** between the time it was read and when the shared-lock was obtained
45598 ** on WAL_READ_LOCK(mxI) was obtained to account for the possibility
45599 ** that the log file may have been wrapped by a writer, or that frames
45600 ** that occur later in the log than pWal->hdr.mxFrame may have been
45601 ** copied into the database by a checkpointer. If either of these things
45602 ** happened, then reading the database with the current value of
45603 ** pWal->hdr.mxFrame risks reading a corrupted snapshot. So, retry
45604 ** instead.
45606 ** This does not guarantee that the copy of the wal-index header is up to
45607 ** date before proceeding. That would not be possible without somehow
45608 ** blocking writers. It only guarantees that a dangerous checkpoint or
45609 ** log-wrap (either of which would require an exclusive lock on
45610 ** WAL_READ_LOCK(mxI)) has not occurred since the snapshot was valid.
45612 walShmBarrier(pWal);
45613 if( pInfo->aReadMark[mxI]!=mxReadMark
45614 || memcmp((void *)walIndexHdr(pWal), &pWal->hdr, sizeof(WalIndexHdr))
45616 walUnlockShared(pWal, WAL_READ_LOCK(mxI));
45617 return WAL_RETRY;
45618 }else{
45619 assert( mxReadMark<=pWal->hdr.mxFrame );
45620 pWal->readLock = (i16)mxI;
45623 return rc;
45627 ** Begin a read transaction on the database.
45629 ** This routine used to be called sqlite3OpenSnapshot() and with good reason:
45630 ** it takes a snapshot of the state of the WAL and wal-index for the current
45631 ** instant in time. The current thread will continue to use this snapshot.
45632 ** Other threads might append new content to the WAL and wal-index but
45633 ** that extra content is ignored by the current thread.
45635 ** If the database contents have changes since the previous read
45636 ** transaction, then *pChanged is set to 1 before returning. The
45637 ** Pager layer will use this to know that is cache is stale and
45638 ** needs to be flushed.
45640 SQLITE_PRIVATE int sqlite3WalBeginReadTransaction(Wal *pWal, int *pChanged){
45641 int rc; /* Return code */
45642 int cnt = 0; /* Number of TryBeginRead attempts */
45645 rc = walTryBeginRead(pWal, pChanged, 0, ++cnt);
45646 }while( rc==WAL_RETRY );
45647 testcase( (rc&0xff)==SQLITE_BUSY );
45648 testcase( (rc&0xff)==SQLITE_IOERR );
45649 testcase( rc==SQLITE_PROTOCOL );
45650 testcase( rc==SQLITE_OK );
45651 return rc;
45655 ** Finish with a read transaction. All this does is release the
45656 ** read-lock.
45658 SQLITE_PRIVATE void sqlite3WalEndReadTransaction(Wal *pWal){
45659 sqlite3WalEndWriteTransaction(pWal);
45660 if( pWal->readLock>=0 ){
45661 walUnlockShared(pWal, WAL_READ_LOCK(pWal->readLock));
45662 pWal->readLock = -1;
45667 ** Read a page from the WAL, if it is present in the WAL and if the
45668 ** current read transaction is configured to use the WAL.
45670 ** The *pInWal is set to 1 if the requested page is in the WAL and
45671 ** has been loaded. Or *pInWal is set to 0 if the page was not in
45672 ** the WAL and needs to be read out of the database.
45674 SQLITE_PRIVATE int sqlite3WalRead(
45675 Wal *pWal, /* WAL handle */
45676 Pgno pgno, /* Database page number to read data for */
45677 int *pInWal, /* OUT: True if data is read from WAL */
45678 int nOut, /* Size of buffer pOut in bytes */
45679 u8 *pOut /* Buffer to write page data to */
45681 u32 iRead = 0; /* If !=0, WAL frame to return data from */
45682 u32 iLast = pWal->hdr.mxFrame; /* Last page in WAL for this reader */
45683 int iHash; /* Used to loop through N hash tables */
45685 /* This routine is only be called from within a read transaction. */
45686 assert( pWal->readLock>=0 || pWal->lockError );
45688 /* If the "last page" field of the wal-index header snapshot is 0, then
45689 ** no data will be read from the wal under any circumstances. Return early
45690 ** in this case as an optimization. Likewise, if pWal->readLock==0,
45691 ** then the WAL is ignored by the reader so return early, as if the
45692 ** WAL were empty.
45694 if( iLast==0 || pWal->readLock==0 ){
45695 *pInWal = 0;
45696 return SQLITE_OK;
45699 /* Search the hash table or tables for an entry matching page number
45700 ** pgno. Each iteration of the following for() loop searches one
45701 ** hash table (each hash table indexes up to HASHTABLE_NPAGE frames).
45703 ** This code might run concurrently to the code in walIndexAppend()
45704 ** that adds entries to the wal-index (and possibly to this hash
45705 ** table). This means the value just read from the hash
45706 ** slot (aHash[iKey]) may have been added before or after the
45707 ** current read transaction was opened. Values added after the
45708 ** read transaction was opened may have been written incorrectly -
45709 ** i.e. these slots may contain garbage data. However, we assume
45710 ** that any slots written before the current read transaction was
45711 ** opened remain unmodified.
45713 ** For the reasons above, the if(...) condition featured in the inner
45714 ** loop of the following block is more stringent that would be required
45715 ** if we had exclusive access to the hash-table:
45717 ** (aPgno[iFrame]==pgno):
45718 ** This condition filters out normal hash-table collisions.
45720 ** (iFrame<=iLast):
45721 ** This condition filters out entries that were added to the hash
45722 ** table after the current read-transaction had started.
45724 for(iHash=walFramePage(iLast); iHash>=0 && iRead==0; iHash--){
45725 volatile ht_slot *aHash; /* Pointer to hash table */
45726 volatile u32 *aPgno; /* Pointer to array of page numbers */
45727 u32 iZero; /* Frame number corresponding to aPgno[0] */
45728 int iKey; /* Hash slot index */
45729 int nCollide; /* Number of hash collisions remaining */
45730 int rc; /* Error code */
45732 rc = walHashGet(pWal, iHash, &aHash, &aPgno, &iZero);
45733 if( rc!=SQLITE_OK ){
45734 return rc;
45736 nCollide = HASHTABLE_NSLOT;
45737 for(iKey=walHash(pgno); aHash[iKey]; iKey=walNextHash(iKey)){
45738 u32 iFrame = aHash[iKey] + iZero;
45739 if( iFrame<=iLast && aPgno[aHash[iKey]]==pgno ){
45740 assert( iFrame>iRead );
45741 iRead = iFrame;
45743 if( (nCollide--)==0 ){
45744 return SQLITE_CORRUPT_BKPT;
45749 #ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
45750 /* If expensive assert() statements are available, do a linear search
45751 ** of the wal-index file content. Make sure the results agree with the
45752 ** result obtained using the hash indexes above. */
45754 u32 iRead2 = 0;
45755 u32 iTest;
45756 for(iTest=iLast; iTest>0; iTest--){
45757 if( walFramePgno(pWal, iTest)==pgno ){
45758 iRead2 = iTest;
45759 break;
45762 assert( iRead==iRead2 );
45764 #endif
45766 /* If iRead is non-zero, then it is the log frame number that contains the
45767 ** required page. Read and return data from the log file.
45769 if( iRead ){
45770 int sz;
45771 i64 iOffset;
45772 sz = pWal->hdr.szPage;
45773 sz = (pWal->hdr.szPage&0xfe00) + ((pWal->hdr.szPage&0x0001)<<16);
45774 testcase( sz<=32768 );
45775 testcase( sz>=65536 );
45776 iOffset = walFrameOffset(iRead, sz) + WAL_FRAME_HDRSIZE;
45777 *pInWal = 1;
45778 /* testcase( IS_BIG_INT(iOffset) ); // requires a 4GiB WAL */
45779 return sqlite3OsRead(pWal->pWalFd, pOut, nOut, iOffset);
45782 *pInWal = 0;
45783 return SQLITE_OK;
45788 ** Return the size of the database in pages (or zero, if unknown).
45790 SQLITE_PRIVATE Pgno sqlite3WalDbsize(Wal *pWal){
45791 if( pWal && ALWAYS(pWal->readLock>=0) ){
45792 return pWal->hdr.nPage;
45794 return 0;
45799 ** This function starts a write transaction on the WAL.
45801 ** A read transaction must have already been started by a prior call
45802 ** to sqlite3WalBeginReadTransaction().
45804 ** If another thread or process has written into the database since
45805 ** the read transaction was started, then it is not possible for this
45806 ** thread to write as doing so would cause a fork. So this routine
45807 ** returns SQLITE_BUSY in that case and no write transaction is started.
45809 ** There can only be a single writer active at a time.
45811 SQLITE_PRIVATE int sqlite3WalBeginWriteTransaction(Wal *pWal){
45812 int rc;
45814 /* Cannot start a write transaction without first holding a read
45815 ** transaction. */
45816 assert( pWal->readLock>=0 );
45818 if( pWal->readOnly ){
45819 return SQLITE_READONLY;
45822 /* Only one writer allowed at a time. Get the write lock. Return
45823 ** SQLITE_BUSY if unable.
45825 rc = walLockExclusive(pWal, WAL_WRITE_LOCK, 1);
45826 if( rc ){
45827 return rc;
45829 pWal->writeLock = 1;
45831 /* If another connection has written to the database file since the
45832 ** time the read transaction on this connection was started, then
45833 ** the write is disallowed.
45835 if( memcmp(&pWal->hdr, (void *)walIndexHdr(pWal), sizeof(WalIndexHdr))!=0 ){
45836 walUnlockExclusive(pWal, WAL_WRITE_LOCK, 1);
45837 pWal->writeLock = 0;
45838 rc = SQLITE_BUSY;
45841 return rc;
45845 ** End a write transaction. The commit has already been done. This
45846 ** routine merely releases the lock.
45848 SQLITE_PRIVATE int sqlite3WalEndWriteTransaction(Wal *pWal){
45849 if( pWal->writeLock ){
45850 walUnlockExclusive(pWal, WAL_WRITE_LOCK, 1);
45851 pWal->writeLock = 0;
45853 return SQLITE_OK;
45857 ** If any data has been written (but not committed) to the log file, this
45858 ** function moves the write-pointer back to the start of the transaction.
45860 ** Additionally, the callback function is invoked for each frame written
45861 ** to the WAL since the start of the transaction. If the callback returns
45862 ** other than SQLITE_OK, it is not invoked again and the error code is
45863 ** returned to the caller.
45865 ** Otherwise, if the callback function does not return an error, this
45866 ** function returns SQLITE_OK.
45868 SQLITE_PRIVATE int sqlite3WalUndo(Wal *pWal, int (*xUndo)(void *, Pgno), void *pUndoCtx){
45869 int rc = SQLITE_OK;
45870 if( ALWAYS(pWal->writeLock) ){
45871 Pgno iMax = pWal->hdr.mxFrame;
45872 Pgno iFrame;
45874 /* Restore the clients cache of the wal-index header to the state it
45875 ** was in before the client began writing to the database.
45877 memcpy(&pWal->hdr, (void *)walIndexHdr(pWal), sizeof(WalIndexHdr));
45879 for(iFrame=pWal->hdr.mxFrame+1;
45880 ALWAYS(rc==SQLITE_OK) && iFrame<=iMax;
45881 iFrame++
45883 /* This call cannot fail. Unless the page for which the page number
45884 ** is passed as the second argument is (a) in the cache and
45885 ** (b) has an outstanding reference, then xUndo is either a no-op
45886 ** (if (a) is false) or simply expels the page from the cache (if (b)
45887 ** is false).
45889 ** If the upper layer is doing a rollback, it is guaranteed that there
45890 ** are no outstanding references to any page other than page 1. And
45891 ** page 1 is never written to the log until the transaction is
45892 ** committed. As a result, the call to xUndo may not fail.
45894 assert( walFramePgno(pWal, iFrame)!=1 );
45895 rc = xUndo(pUndoCtx, walFramePgno(pWal, iFrame));
45897 walCleanupHash(pWal);
45899 assert( rc==SQLITE_OK );
45900 return rc;
45904 ** Argument aWalData must point to an array of WAL_SAVEPOINT_NDATA u32
45905 ** values. This function populates the array with values required to
45906 ** "rollback" the write position of the WAL handle back to the current
45907 ** point in the event of a savepoint rollback (via WalSavepointUndo()).
45909 SQLITE_PRIVATE void sqlite3WalSavepoint(Wal *pWal, u32 *aWalData){
45910 assert( pWal->writeLock );
45911 aWalData[0] = pWal->hdr.mxFrame;
45912 aWalData[1] = pWal->hdr.aFrameCksum[0];
45913 aWalData[2] = pWal->hdr.aFrameCksum[1];
45914 aWalData[3] = pWal->nCkpt;
45918 ** Move the write position of the WAL back to the point identified by
45919 ** the values in the aWalData[] array. aWalData must point to an array
45920 ** of WAL_SAVEPOINT_NDATA u32 values that has been previously populated
45921 ** by a call to WalSavepoint().
45923 SQLITE_PRIVATE int sqlite3WalSavepointUndo(Wal *pWal, u32 *aWalData){
45924 int rc = SQLITE_OK;
45926 assert( pWal->writeLock );
45927 assert( aWalData[3]!=pWal->nCkpt || aWalData[0]<=pWal->hdr.mxFrame );
45929 if( aWalData[3]!=pWal->nCkpt ){
45930 /* This savepoint was opened immediately after the write-transaction
45931 ** was started. Right after that, the writer decided to wrap around
45932 ** to the start of the log. Update the savepoint values to match.
45934 aWalData[0] = 0;
45935 aWalData[3] = pWal->nCkpt;
45938 if( aWalData[0]<pWal->hdr.mxFrame ){
45939 pWal->hdr.mxFrame = aWalData[0];
45940 pWal->hdr.aFrameCksum[0] = aWalData[1];
45941 pWal->hdr.aFrameCksum[1] = aWalData[2];
45942 walCleanupHash(pWal);
45945 return rc;
45949 ** This function is called just before writing a set of frames to the log
45950 ** file (see sqlite3WalFrames()). It checks to see if, instead of appending
45951 ** to the current log file, it is possible to overwrite the start of the
45952 ** existing log file with the new frames (i.e. "reset" the log). If so,
45953 ** it sets pWal->hdr.mxFrame to 0. Otherwise, pWal->hdr.mxFrame is left
45954 ** unchanged.
45956 ** SQLITE_OK is returned if no error is encountered (regardless of whether
45957 ** or not pWal->hdr.mxFrame is modified). An SQLite error code is returned
45958 ** if an error occurs.
45960 static int walRestartLog(Wal *pWal){
45961 int rc = SQLITE_OK;
45962 int cnt;
45964 if( pWal->readLock==0 ){
45965 volatile WalCkptInfo *pInfo = walCkptInfo(pWal);
45966 assert( pInfo->nBackfill==pWal->hdr.mxFrame );
45967 if( pInfo->nBackfill>0 ){
45968 u32 salt1;
45969 sqlite3_randomness(4, &salt1);
45970 rc = walLockExclusive(pWal, WAL_READ_LOCK(1), WAL_NREADER-1);
45971 if( rc==SQLITE_OK ){
45972 /* If all readers are using WAL_READ_LOCK(0) (in other words if no
45973 ** readers are currently using the WAL), then the transactions
45974 ** frames will overwrite the start of the existing log. Update the
45975 ** wal-index header to reflect this.
45977 ** In theory it would be Ok to update the cache of the header only
45978 ** at this point. But updating the actual wal-index header is also
45979 ** safe and means there is no special case for sqlite3WalUndo()
45980 ** to handle if this transaction is rolled back.
45982 int i; /* Loop counter */
45983 u32 *aSalt = pWal->hdr.aSalt; /* Big-endian salt values */
45984 pWal->nCkpt++;
45985 pWal->hdr.mxFrame = 0;
45986 sqlite3Put4byte((u8*)&aSalt[0], 1 + sqlite3Get4byte((u8*)&aSalt[0]));
45987 aSalt[1] = salt1;
45988 walIndexWriteHdr(pWal);
45989 pInfo->nBackfill = 0;
45990 for(i=1; i<WAL_NREADER; i++) pInfo->aReadMark[i] = READMARK_NOT_USED;
45991 assert( pInfo->aReadMark[0]==0 );
45992 walUnlockExclusive(pWal, WAL_READ_LOCK(1), WAL_NREADER-1);
45993 }else if( rc!=SQLITE_BUSY ){
45994 return rc;
45997 walUnlockShared(pWal, WAL_READ_LOCK(0));
45998 pWal->readLock = -1;
45999 cnt = 0;
46001 int notUsed;
46002 rc = walTryBeginRead(pWal, &notUsed, 1, ++cnt);
46003 }while( rc==WAL_RETRY );
46004 assert( (rc&0xff)!=SQLITE_BUSY ); /* BUSY not possible when useWal==1 */
46005 testcase( (rc&0xff)==SQLITE_IOERR );
46006 testcase( rc==SQLITE_PROTOCOL );
46007 testcase( rc==SQLITE_OK );
46009 return rc;
46013 ** Write a set of frames to the log. The caller must hold the write-lock
46014 ** on the log file (obtained using sqlite3WalBeginWriteTransaction()).
46016 SQLITE_PRIVATE int sqlite3WalFrames(
46017 Wal *pWal, /* Wal handle to write to */
46018 int szPage, /* Database page-size in bytes */
46019 PgHdr *pList, /* List of dirty pages to write */
46020 Pgno nTruncate, /* Database size after this commit */
46021 int isCommit, /* True if this is a commit */
46022 int sync_flags /* Flags to pass to OsSync() (or 0) */
46024 int rc; /* Used to catch return codes */
46025 u32 iFrame; /* Next frame address */
46026 u8 aFrame[WAL_FRAME_HDRSIZE]; /* Buffer to assemble frame-header in */
46027 PgHdr *p; /* Iterator to run through pList with. */
46028 PgHdr *pLast = 0; /* Last frame in list */
46029 int nLast = 0; /* Number of extra copies of last page */
46031 assert( pList );
46032 assert( pWal->writeLock );
46034 #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
46035 { int cnt; for(cnt=0, p=pList; p; p=p->pDirty, cnt++){}
46036 WALTRACE(("WAL%p: frame write begin. %d frames. mxFrame=%d. %s\n",
46037 pWal, cnt, pWal->hdr.mxFrame, isCommit ? "Commit" : "Spill"));
46039 #endif
46041 /* See if it is possible to write these frames into the start of the
46042 ** log file, instead of appending to it at pWal->hdr.mxFrame.
46044 if( SQLITE_OK!=(rc = walRestartLog(pWal)) ){
46045 return rc;
46048 /* If this is the first frame written into the log, write the WAL
46049 ** header to the start of the WAL file. See comments at the top of
46050 ** this source file for a description of the WAL header format.
46052 iFrame = pWal->hdr.mxFrame;
46053 if( iFrame==0 ){
46054 u8 aWalHdr[WAL_HDRSIZE]; /* Buffer to assemble wal-header in */
46055 u32 aCksum[2]; /* Checksum for wal-header */
46057 sqlite3Put4byte(&aWalHdr[0], (WAL_MAGIC | SQLITE_BIGENDIAN));
46058 sqlite3Put4byte(&aWalHdr[4], WAL_MAX_VERSION);
46059 sqlite3Put4byte(&aWalHdr[8], szPage);
46060 sqlite3Put4byte(&aWalHdr[12], pWal->nCkpt);
46061 sqlite3_randomness(8, pWal->hdr.aSalt);
46062 memcpy(&aWalHdr[16], pWal->hdr.aSalt, 8);
46063 walChecksumBytes(1, aWalHdr, WAL_HDRSIZE-2*4, 0, aCksum);
46064 sqlite3Put4byte(&aWalHdr[24], aCksum[0]);
46065 sqlite3Put4byte(&aWalHdr[28], aCksum[1]);
46067 pWal->szPage = szPage;
46068 pWal->hdr.bigEndCksum = SQLITE_BIGENDIAN;
46069 pWal->hdr.aFrameCksum[0] = aCksum[0];
46070 pWal->hdr.aFrameCksum[1] = aCksum[1];
46072 rc = sqlite3OsWrite(pWal->pWalFd, aWalHdr, sizeof(aWalHdr), 0);
46073 WALTRACE(("WAL%p: wal-header write %s\n", pWal, rc ? "failed" : "ok"));
46074 if( rc!=SQLITE_OK ){
46075 return rc;
46078 assert( (int)pWal->szPage==szPage );
46080 /* Write the log file. */
46081 for(p=pList; p; p=p->pDirty){
46082 u32 nDbsize; /* Db-size field for frame header */
46083 i64 iOffset; /* Write offset in log file */
46084 void *pData;
46086 iOffset = walFrameOffset(++iFrame, szPage);
46087 /* testcase( IS_BIG_INT(iOffset) ); // requires a 4GiB WAL */
46089 /* Populate and write the frame header */
46090 nDbsize = (isCommit && p->pDirty==0) ? nTruncate : 0;
46091 #if defined(SQLITE_HAS_CODEC)
46092 if( (pData = sqlite3PagerCodec(p))==0 ) return SQLITE_NOMEM;
46093 #else
46094 pData = p->pData;
46095 #endif
46096 walEncodeFrame(pWal, p->pgno, nDbsize, pData, aFrame);
46097 rc = sqlite3OsWrite(pWal->pWalFd, aFrame, sizeof(aFrame), iOffset);
46098 if( rc!=SQLITE_OK ){
46099 return rc;
46102 /* Write the page data */
46103 rc = sqlite3OsWrite(pWal->pWalFd, pData, szPage, iOffset+sizeof(aFrame));
46104 if( rc!=SQLITE_OK ){
46105 return rc;
46107 pLast = p;
46110 /* Sync the log file if the 'isSync' flag was specified. */
46111 if( sync_flags ){
46112 i64 iSegment = sqlite3OsSectorSize(pWal->pWalFd);
46113 i64 iOffset = walFrameOffset(iFrame+1, szPage);
46115 assert( isCommit );
46116 assert( iSegment>0 );
46118 iSegment = (((iOffset+iSegment-1)/iSegment) * iSegment);
46119 while( iOffset<iSegment ){
46120 void *pData;
46121 #if defined(SQLITE_HAS_CODEC)
46122 if( (pData = sqlite3PagerCodec(pLast))==0 ) return SQLITE_NOMEM;
46123 #else
46124 pData = pLast->pData;
46125 #endif
46126 walEncodeFrame(pWal, pLast->pgno, nTruncate, pData, aFrame);
46127 /* testcase( IS_BIG_INT(iOffset) ); // requires a 4GiB WAL */
46128 rc = sqlite3OsWrite(pWal->pWalFd, aFrame, sizeof(aFrame), iOffset);
46129 if( rc!=SQLITE_OK ){
46130 return rc;
46132 iOffset += WAL_FRAME_HDRSIZE;
46133 rc = sqlite3OsWrite(pWal->pWalFd, pData, szPage, iOffset);
46134 if( rc!=SQLITE_OK ){
46135 return rc;
46137 nLast++;
46138 iOffset += szPage;
46141 rc = sqlite3OsSync(pWal->pWalFd, sync_flags);
46144 /* Append data to the wal-index. It is not necessary to lock the
46145 ** wal-index to do this as the SQLITE_SHM_WRITE lock held on the wal-index
46146 ** guarantees that there are no other writers, and no data that may
46147 ** be in use by existing readers is being overwritten.
46149 iFrame = pWal->hdr.mxFrame;
46150 for(p=pList; p && rc==SQLITE_OK; p=p->pDirty){
46151 iFrame++;
46152 rc = walIndexAppend(pWal, iFrame, p->pgno);
46154 while( nLast>0 && rc==SQLITE_OK ){
46155 iFrame++;
46156 nLast--;
46157 rc = walIndexAppend(pWal, iFrame, pLast->pgno);
46160 if( rc==SQLITE_OK ){
46161 /* Update the private copy of the header. */
46162 pWal->hdr.szPage = (u16)((szPage&0xff00) | (szPage>>16));
46163 testcase( szPage<=32768 );
46164 testcase( szPage>=65536 );
46165 pWal->hdr.mxFrame = iFrame;
46166 if( isCommit ){
46167 pWal->hdr.iChange++;
46168 pWal->hdr.nPage = nTruncate;
46170 /* If this is a commit, update the wal-index header too. */
46171 if( isCommit ){
46172 walIndexWriteHdr(pWal);
46173 pWal->iCallback = iFrame;
46177 WALTRACE(("WAL%p: frame write %s\n", pWal, rc ? "failed" : "ok"));
46178 return rc;
46182 ** This routine is called to implement sqlite3_wal_checkpoint() and
46183 ** related interfaces.
46185 ** Obtain a CHECKPOINT lock and then backfill as much information as
46186 ** we can from WAL into the database.
46188 ** If parameter xBusy is not NULL, it is a pointer to a busy-handler
46189 ** callback. In this case this function runs a blocking checkpoint.
46191 SQLITE_PRIVATE int sqlite3WalCheckpoint(
46192 Wal *pWal, /* Wal connection */
46193 int eMode, /* PASSIVE, FULL or RESTART */
46194 int (*xBusy)(void*), /* Function to call when busy */
46195 void *pBusyArg, /* Context argument for xBusyHandler */
46196 int sync_flags, /* Flags to sync db file with (or 0) */
46197 int nBuf, /* Size of temporary buffer */
46198 u8 *zBuf, /* Temporary buffer to use */
46199 int *pnLog, /* OUT: Number of frames in WAL */
46200 int *pnCkpt /* OUT: Number of backfilled frames in WAL */
46202 int rc; /* Return code */
46203 int isChanged = 0; /* True if a new wal-index header is loaded */
46204 int eMode2 = eMode; /* Mode to pass to walCheckpoint() */
46206 assert( pWal->ckptLock==0 );
46207 assert( pWal->writeLock==0 );
46209 WALTRACE(("WAL%p: checkpoint begins\n", pWal));
46210 rc = walLockExclusive(pWal, WAL_CKPT_LOCK, 1);
46211 if( rc ){
46212 /* Usually this is SQLITE_BUSY meaning that another thread or process
46213 ** is already running a checkpoint, or maybe a recovery. But it might
46214 ** also be SQLITE_IOERR. */
46215 return rc;
46217 pWal->ckptLock = 1;
46219 /* If this is a blocking-checkpoint, then obtain the write-lock as well
46220 ** to prevent any writers from running while the checkpoint is underway.
46221 ** This has to be done before the call to walIndexReadHdr() below.
46223 ** If the writer lock cannot be obtained, then a passive checkpoint is
46224 ** run instead. Since the checkpointer is not holding the writer lock,
46225 ** there is no point in blocking waiting for any readers. Assuming no
46226 ** other error occurs, this function will return SQLITE_BUSY to the caller.
46228 if( eMode!=SQLITE_CHECKPOINT_PASSIVE ){
46229 rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_WRITE_LOCK, 1);
46230 if( rc==SQLITE_OK ){
46231 pWal->writeLock = 1;
46232 }else if( rc==SQLITE_BUSY ){
46233 eMode2 = SQLITE_CHECKPOINT_PASSIVE;
46234 rc = SQLITE_OK;
46238 /* Read the wal-index header. */
46239 if( rc==SQLITE_OK ){
46240 rc = walIndexReadHdr(pWal, &isChanged);
46243 /* Copy data from the log to the database file. */
46244 if( rc==SQLITE_OK ){
46245 if( pWal->hdr.mxFrame && walPagesize(pWal)!=nBuf ){
46246 rc = SQLITE_CORRUPT_BKPT;
46247 }else{
46248 rc = walCheckpoint(pWal, eMode2, xBusy, pBusyArg, sync_flags, zBuf);
46251 /* If no error occurred, set the output variables. */
46252 if( rc==SQLITE_OK || rc==SQLITE_BUSY ){
46253 if( pnLog ) *pnLog = (int)pWal->hdr.mxFrame;
46254 if( pnCkpt ) *pnCkpt = (int)(walCkptInfo(pWal)->nBackfill);
46258 if( isChanged ){
46259 /* If a new wal-index header was loaded before the checkpoint was
46260 ** performed, then the pager-cache associated with pWal is now
46261 ** out of date. So zero the cached wal-index header to ensure that
46262 ** next time the pager opens a snapshot on this database it knows that
46263 ** the cache needs to be reset.
46265 memset(&pWal->hdr, 0, sizeof(WalIndexHdr));
46268 /* Release the locks. */
46269 sqlite3WalEndWriteTransaction(pWal);
46270 walUnlockExclusive(pWal, WAL_CKPT_LOCK, 1);
46271 pWal->ckptLock = 0;
46272 WALTRACE(("WAL%p: checkpoint %s\n", pWal, rc ? "failed" : "ok"));
46273 return (rc==SQLITE_OK && eMode!=eMode2 ? SQLITE_BUSY : rc);
46276 /* Return the value to pass to a sqlite3_wal_hook callback, the
46277 ** number of frames in the WAL at the point of the last commit since
46278 ** sqlite3WalCallback() was called. If no commits have occurred since
46279 ** the last call, then return 0.
46281 SQLITE_PRIVATE int sqlite3WalCallback(Wal *pWal){
46282 u32 ret = 0;
46283 if( pWal ){
46284 ret = pWal->iCallback;
46285 pWal->iCallback = 0;
46287 return (int)ret;
46291 ** This function is called to change the WAL subsystem into or out
46292 ** of locking_mode=EXCLUSIVE.
46294 ** If op is zero, then attempt to change from locking_mode=EXCLUSIVE
46295 ** into locking_mode=NORMAL. This means that we must acquire a lock
46296 ** on the pWal->readLock byte. If the WAL is already in locking_mode=NORMAL
46297 ** or if the acquisition of the lock fails, then return 0. If the
46298 ** transition out of exclusive-mode is successful, return 1. This
46299 ** operation must occur while the pager is still holding the exclusive
46300 ** lock on the main database file.
46302 ** If op is one, then change from locking_mode=NORMAL into
46303 ** locking_mode=EXCLUSIVE. This means that the pWal->readLock must
46304 ** be released. Return 1 if the transition is made and 0 if the
46305 ** WAL is already in exclusive-locking mode - meaning that this
46306 ** routine is a no-op. The pager must already hold the exclusive lock
46307 ** on the main database file before invoking this operation.
46309 ** If op is negative, then do a dry-run of the op==1 case but do
46310 ** not actually change anything. The pager uses this to see if it
46311 ** should acquire the database exclusive lock prior to invoking
46312 ** the op==1 case.
46314 SQLITE_PRIVATE int sqlite3WalExclusiveMode(Wal *pWal, int op){
46315 int rc;
46316 assert( pWal->writeLock==0 );
46317 assert( pWal->exclusiveMode!=WAL_HEAPMEMORY_MODE || op==-1 );
46319 /* pWal->readLock is usually set, but might be -1 if there was a
46320 ** prior error while attempting to acquire are read-lock. This cannot
46321 ** happen if the connection is actually in exclusive mode (as no xShmLock
46322 ** locks are taken in this case). Nor should the pager attempt to
46323 ** upgrade to exclusive-mode following such an error.
46325 assert( pWal->readLock>=0 || pWal->lockError );
46326 assert( pWal->readLock>=0 || (op<=0 && pWal->exclusiveMode==0) );
46328 if( op==0 ){
46329 if( pWal->exclusiveMode ){
46330 pWal->exclusiveMode = 0;
46331 if( walLockShared(pWal, WAL_READ_LOCK(pWal->readLock))!=SQLITE_OK ){
46332 pWal->exclusiveMode = 1;
46334 rc = pWal->exclusiveMode==0;
46335 }else{
46336 /* Already in locking_mode=NORMAL */
46337 rc = 0;
46339 }else if( op>0 ){
46340 assert( pWal->exclusiveMode==0 );
46341 assert( pWal->readLock>=0 );
46342 walUnlockShared(pWal, WAL_READ_LOCK(pWal->readLock));
46343 pWal->exclusiveMode = 1;
46344 rc = 1;
46345 }else{
46346 rc = pWal->exclusiveMode==0;
46348 return rc;
46352 ** Return true if the argument is non-NULL and the WAL module is using
46353 ** heap-memory for the wal-index. Otherwise, if the argument is NULL or the
46354 ** WAL module is using shared-memory, return false.
46356 SQLITE_PRIVATE int sqlite3WalHeapMemory(Wal *pWal){
46357 return (pWal && pWal->exclusiveMode==WAL_HEAPMEMORY_MODE );
46360 #endif /* #ifndef SQLITE_OMIT_WAL */
46362 /************** End of wal.c *************************************************/
46363 /************** Begin file btmutex.c *****************************************/
46365 ** 2007 August 27
46367 ** The author disclaims copyright to this source code. In place of
46368 ** a legal notice, here is a blessing:
46370 ** May you do good and not evil.
46371 ** May you find forgiveness for yourself and forgive others.
46372 ** May you share freely, never taking more than you give.
46374 *************************************************************************
46376 ** This file contains code used to implement mutexes on Btree objects.
46377 ** This code really belongs in btree.c. But btree.c is getting too
46378 ** big and we want to break it down some. This packaged seemed like
46379 ** a good breakout.
46381 /************** Include btreeInt.h in the middle of btmutex.c ****************/
46382 /************** Begin file btreeInt.h ****************************************/
46384 ** 2004 April 6
46386 ** The author disclaims copyright to this source code. In place of
46387 ** a legal notice, here is a blessing:
46389 ** May you do good and not evil.
46390 ** May you find forgiveness for yourself and forgive others.
46391 ** May you share freely, never taking more than you give.
46393 *************************************************************************
46394 ** This file implements a external (disk-based) database using BTrees.
46395 ** For a detailed discussion of BTrees, refer to
46397 ** Donald E. Knuth, THE ART OF COMPUTER PROGRAMMING, Volume 3:
46398 ** "Sorting And Searching", pages 473-480. Addison-Wesley
46399 ** Publishing Company, Reading, Massachusetts.
46401 ** The basic idea is that each page of the file contains N database
46402 ** entries and N+1 pointers to subpages.
46404 ** ----------------------------------------------------------------
46405 ** | Ptr(0) | Key(0) | Ptr(1) | Key(1) | ... | Key(N-1) | Ptr(N) |
46406 ** ----------------------------------------------------------------
46408 ** All of the keys on the page that Ptr(0) points to have values less
46409 ** than Key(0). All of the keys on page Ptr(1) and its subpages have
46410 ** values greater than Key(0) and less than Key(1). All of the keys
46411 ** on Ptr(N) and its subpages have values greater than Key(N-1). And
46412 ** so forth.
46414 ** Finding a particular key requires reading O(log(M)) pages from the
46415 ** disk where M is the number of entries in the tree.
46417 ** In this implementation, a single file can hold one or more separate
46418 ** BTrees. Each BTree is identified by the index of its root page. The
46419 ** key and data for any entry are combined to form the "payload". A
46420 ** fixed amount of payload can be carried directly on the database
46421 ** page. If the payload is larger than the preset amount then surplus
46422 ** bytes are stored on overflow pages. The payload for an entry
46423 ** and the preceding pointer are combined to form a "Cell". Each
46424 ** page has a small header which contains the Ptr(N) pointer and other
46425 ** information such as the size of key and data.
46427 ** FORMAT DETAILS
46429 ** The file is divided into pages. The first page is called page 1,
46430 ** the second is page 2, and so forth. A page number of zero indicates
46431 ** "no such page". The page size can be any power of 2 between 512 and 65536.
46432 ** Each page can be either a btree page, a freelist page, an overflow
46433 ** page, or a pointer-map page.
46435 ** The first page is always a btree page. The first 100 bytes of the first
46436 ** page contain a special header (the "file header") that describes the file.
46437 ** The format of the file header is as follows:
46439 ** OFFSET SIZE DESCRIPTION
46440 ** 0 16 Header string: "SQLite format 3\000"
46441 ** 16 2 Page size in bytes.
46442 ** 18 1 File format write version
46443 ** 19 1 File format read version
46444 ** 20 1 Bytes of unused space at the end of each page
46445 ** 21 1 Max embedded payload fraction
46446 ** 22 1 Min embedded payload fraction
46447 ** 23 1 Min leaf payload fraction
46448 ** 24 4 File change counter
46449 ** 28 4 Reserved for future use
46450 ** 32 4 First freelist page
46451 ** 36 4 Number of freelist pages in the file
46452 ** 40 60 15 4-byte meta values passed to higher layers
46454 ** 40 4 Schema cookie
46455 ** 44 4 File format of schema layer
46456 ** 48 4 Size of page cache
46457 ** 52 4 Largest root-page (auto/incr_vacuum)
46458 ** 56 4 1=UTF-8 2=UTF16le 3=UTF16be
46459 ** 60 4 User version
46460 ** 64 4 Incremental vacuum mode
46461 ** 68 4 unused
46462 ** 72 4 unused
46463 ** 76 4 unused
46465 ** All of the integer values are big-endian (most significant byte first).
46467 ** The file change counter is incremented when the database is changed
46468 ** This counter allows other processes to know when the file has changed
46469 ** and thus when they need to flush their cache.
46471 ** The max embedded payload fraction is the amount of the total usable
46472 ** space in a page that can be consumed by a single cell for standard
46473 ** B-tree (non-LEAFDATA) tables. A value of 255 means 100%. The default
46474 ** is to limit the maximum cell size so that at least 4 cells will fit
46475 ** on one page. Thus the default max embedded payload fraction is 64.
46477 ** If the payload for a cell is larger than the max payload, then extra
46478 ** payload is spilled to overflow pages. Once an overflow page is allocated,
46479 ** as many bytes as possible are moved into the overflow pages without letting
46480 ** the cell size drop below the min embedded payload fraction.
46482 ** The min leaf payload fraction is like the min embedded payload fraction
46483 ** except that it applies to leaf nodes in a LEAFDATA tree. The maximum
46484 ** payload fraction for a LEAFDATA tree is always 100% (or 255) and it
46485 ** not specified in the header.
46487 ** Each btree pages is divided into three sections: The header, the
46488 ** cell pointer array, and the cell content area. Page 1 also has a 100-byte
46489 ** file header that occurs before the page header.
46491 ** |----------------|
46492 ** | file header | 100 bytes. Page 1 only.
46493 ** |----------------|
46494 ** | page header | 8 bytes for leaves. 12 bytes for interior nodes
46495 ** |----------------|
46496 ** | cell pointer | | 2 bytes per cell. Sorted order.
46497 ** | array | | Grows downward
46498 ** | | v
46499 ** |----------------|
46500 ** | unallocated |
46501 ** | space |
46502 ** |----------------| ^ Grows upwards
46503 ** | cell content | | Arbitrary order interspersed with freeblocks.
46504 ** | area | | and free space fragments.
46505 ** |----------------|
46507 ** The page headers looks like this:
46509 ** OFFSET SIZE DESCRIPTION
46510 ** 0 1 Flags. 1: intkey, 2: zerodata, 4: leafdata, 8: leaf
46511 ** 1 2 byte offset to the first freeblock
46512 ** 3 2 number of cells on this page
46513 ** 5 2 first byte of the cell content area
46514 ** 7 1 number of fragmented free bytes
46515 ** 8 4 Right child (the Ptr(N) value). Omitted on leaves.
46517 ** The flags define the format of this btree page. The leaf flag means that
46518 ** this page has no children. The zerodata flag means that this page carries
46519 ** only keys and no data. The intkey flag means that the key is a integer
46520 ** which is stored in the key size entry of the cell header rather than in
46521 ** the payload area.
46523 ** The cell pointer array begins on the first byte after the page header.
46524 ** The cell pointer array contains zero or more 2-byte numbers which are
46525 ** offsets from the beginning of the page to the cell content in the cell
46526 ** content area. The cell pointers occur in sorted order. The system strives
46527 ** to keep free space after the last cell pointer so that new cells can
46528 ** be easily added without having to defragment the page.
46530 ** Cell content is stored at the very end of the page and grows toward the
46531 ** beginning of the page.
46533 ** Unused space within the cell content area is collected into a linked list of
46534 ** freeblocks. Each freeblock is at least 4 bytes in size. The byte offset
46535 ** to the first freeblock is given in the header. Freeblocks occur in
46536 ** increasing order. Because a freeblock must be at least 4 bytes in size,
46537 ** any group of 3 or fewer unused bytes in the cell content area cannot
46538 ** exist on the freeblock chain. A group of 3 or fewer free bytes is called
46539 ** a fragment. The total number of bytes in all fragments is recorded.
46540 ** in the page header at offset 7.
46542 ** SIZE DESCRIPTION
46543 ** 2 Byte offset of the next freeblock
46544 ** 2 Bytes in this freeblock
46546 ** Cells are of variable length. Cells are stored in the cell content area at
46547 ** the end of the page. Pointers to the cells are in the cell pointer array
46548 ** that immediately follows the page header. Cells is not necessarily
46549 ** contiguous or in order, but cell pointers are contiguous and in order.
46551 ** Cell content makes use of variable length integers. A variable
46552 ** length integer is 1 to 9 bytes where the lower 7 bits of each
46553 ** byte are used. The integer consists of all bytes that have bit 8 set and
46554 ** the first byte with bit 8 clear. The most significant byte of the integer
46555 ** appears first. A variable-length integer may not be more than 9 bytes long.
46556 ** As a special case, all 8 bytes of the 9th byte are used as data. This
46557 ** allows a 64-bit integer to be encoded in 9 bytes.
46559 ** 0x00 becomes 0x00000000
46560 ** 0x7f becomes 0x0000007f
46561 ** 0x81 0x00 becomes 0x00000080
46562 ** 0x82 0x00 becomes 0x00000100
46563 ** 0x80 0x7f becomes 0x0000007f
46564 ** 0x8a 0x91 0xd1 0xac 0x78 becomes 0x12345678
46565 ** 0x81 0x81 0x81 0x81 0x01 becomes 0x10204081
46567 ** Variable length integers are used for rowids and to hold the number of
46568 ** bytes of key and data in a btree cell.
46570 ** The content of a cell looks like this:
46572 ** SIZE DESCRIPTION
46573 ** 4 Page number of the left child. Omitted if leaf flag is set.
46574 ** var Number of bytes of data. Omitted if the zerodata flag is set.
46575 ** var Number of bytes of key. Or the key itself if intkey flag is set.
46576 ** * Payload
46577 ** 4 First page of the overflow chain. Omitted if no overflow
46579 ** Overflow pages form a linked list. Each page except the last is completely
46580 ** filled with data (pagesize - 4 bytes). The last page can have as little
46581 ** as 1 byte of data.
46583 ** SIZE DESCRIPTION
46584 ** 4 Page number of next overflow page
46585 ** * Data
46587 ** Freelist pages come in two subtypes: trunk pages and leaf pages. The
46588 ** file header points to the first in a linked list of trunk page. Each trunk
46589 ** page points to multiple leaf pages. The content of a leaf page is
46590 ** unspecified. A trunk page looks like this:
46592 ** SIZE DESCRIPTION
46593 ** 4 Page number of next trunk page
46594 ** 4 Number of leaf pointers on this page
46595 ** * zero or more pages numbers of leaves
46599 /* The following value is the maximum cell size assuming a maximum page
46600 ** size give above.
46602 #define MX_CELL_SIZE(pBt) ((int)(pBt->pageSize-8))
46604 /* The maximum number of cells on a single page of the database. This
46605 ** assumes a minimum cell size of 6 bytes (4 bytes for the cell itself
46606 ** plus 2 bytes for the index to the cell in the page header). Such
46607 ** small cells will be rare, but they are possible.
46609 #define MX_CELL(pBt) ((pBt->pageSize-8)/6)
46611 /* Forward declarations */
46612 typedef struct MemPage MemPage;
46613 typedef struct BtLock BtLock;
46616 ** This is a magic string that appears at the beginning of every
46617 ** SQLite database in order to identify the file as a real database.
46619 ** You can change this value at compile-time by specifying a
46620 ** -DSQLITE_FILE_HEADER="..." on the compiler command-line. The
46621 ** header must be exactly 16 bytes including the zero-terminator so
46622 ** the string itself should be 15 characters long. If you change
46623 ** the header, then your custom library will not be able to read
46624 ** databases generated by the standard tools and the standard tools
46625 ** will not be able to read databases created by your custom library.
46627 #ifndef SQLITE_FILE_HEADER /* 123456789 123456 */
46628 # define SQLITE_FILE_HEADER "SQLite format 3"
46629 #endif
46632 ** Page type flags. An ORed combination of these flags appear as the
46633 ** first byte of on-disk image of every BTree page.
46635 #define PTF_INTKEY 0x01
46636 #define PTF_ZERODATA 0x02
46637 #define PTF_LEAFDATA 0x04
46638 #define PTF_LEAF 0x08
46641 ** As each page of the file is loaded into memory, an instance of the following
46642 ** structure is appended and initialized to zero. This structure stores
46643 ** information about the page that is decoded from the raw file page.
46645 ** The pParent field points back to the parent page. This allows us to
46646 ** walk up the BTree from any leaf to the root. Care must be taken to
46647 ** unref() the parent page pointer when this page is no longer referenced.
46648 ** The pageDestructor() routine handles that chore.
46650 ** Access to all fields of this structure is controlled by the mutex
46651 ** stored in MemPage.pBt->mutex.
46653 struct MemPage {
46654 u8 isInit; /* True if previously initialized. MUST BE FIRST! */
46655 u8 nOverflow; /* Number of overflow cell bodies in aCell[] */
46656 u8 intKey; /* True if intkey flag is set */
46657 u8 leaf; /* True if leaf flag is set */
46658 u8 hasData; /* True if this page stores data */
46659 u8 hdrOffset; /* 100 for page 1. 0 otherwise */
46660 u8 childPtrSize; /* 0 if leaf==1. 4 if leaf==0 */
46661 u16 maxLocal; /* Copy of BtShared.maxLocal or BtShared.maxLeaf */
46662 u16 minLocal; /* Copy of BtShared.minLocal or BtShared.minLeaf */
46663 u16 cellOffset; /* Index in aData of first cell pointer */
46664 u16 nFree; /* Number of free bytes on the page */
46665 u16 nCell; /* Number of cells on this page, local and ovfl */
46666 u16 maskPage; /* Mask for page offset */
46667 struct _OvflCell { /* Cells that will not fit on aData[] */
46668 u8 *pCell; /* Pointers to the body of the overflow cell */
46669 u16 idx; /* Insert this cell before idx-th non-overflow cell */
46670 } aOvfl[5];
46671 BtShared *pBt; /* Pointer to BtShared that this page is part of */
46672 u8 *aData; /* Pointer to disk image of the page data */
46673 DbPage *pDbPage; /* Pager page handle */
46674 Pgno pgno; /* Page number for this page */
46678 ** The in-memory image of a disk page has the auxiliary information appended
46679 ** to the end. EXTRA_SIZE is the number of bytes of space needed to hold
46680 ** that extra information.
46682 #define EXTRA_SIZE sizeof(MemPage)
46685 ** A linked list of the following structures is stored at BtShared.pLock.
46686 ** Locks are added (or upgraded from READ_LOCK to WRITE_LOCK) when a cursor
46687 ** is opened on the table with root page BtShared.iTable. Locks are removed
46688 ** from this list when a transaction is committed or rolled back, or when
46689 ** a btree handle is closed.
46691 struct BtLock {
46692 Btree *pBtree; /* Btree handle holding this lock */
46693 Pgno iTable; /* Root page of table */
46694 u8 eLock; /* READ_LOCK or WRITE_LOCK */
46695 BtLock *pNext; /* Next in BtShared.pLock list */
46698 /* Candidate values for BtLock.eLock */
46699 #define READ_LOCK 1
46700 #define WRITE_LOCK 2
46702 /* A Btree handle
46704 ** A database connection contains a pointer to an instance of
46705 ** this object for every database file that it has open. This structure
46706 ** is opaque to the database connection. The database connection cannot
46707 ** see the internals of this structure and only deals with pointers to
46708 ** this structure.
46710 ** For some database files, the same underlying database cache might be
46711 ** shared between multiple connections. In that case, each connection
46712 ** has it own instance of this object. But each instance of this object
46713 ** points to the same BtShared object. The database cache and the
46714 ** schema associated with the database file are all contained within
46715 ** the BtShared object.
46717 ** All fields in this structure are accessed under sqlite3.mutex.
46718 ** The pBt pointer itself may not be changed while there exists cursors
46719 ** in the referenced BtShared that point back to this Btree since those
46720 ** cursors have to go through this Btree to find their BtShared and
46721 ** they often do so without holding sqlite3.mutex.
46723 struct Btree {
46724 sqlite3 *db; /* The database connection holding this btree */
46725 BtShared *pBt; /* Sharable content of this btree */
46726 u8 inTrans; /* TRANS_NONE, TRANS_READ or TRANS_WRITE */
46727 u8 sharable; /* True if we can share pBt with another db */
46728 u8 locked; /* True if db currently has pBt locked */
46729 int wantToLock; /* Number of nested calls to sqlite3BtreeEnter() */
46730 int nBackup; /* Number of backup operations reading this btree */
46731 Btree *pNext; /* List of other sharable Btrees from the same db */
46732 Btree *pPrev; /* Back pointer of the same list */
46733 #ifndef SQLITE_OMIT_SHARED_CACHE
46734 BtLock lock; /* Object used to lock page 1 */
46735 #endif
46739 ** Btree.inTrans may take one of the following values.
46741 ** If the shared-data extension is enabled, there may be multiple users
46742 ** of the Btree structure. At most one of these may open a write transaction,
46743 ** but any number may have active read transactions.
46745 #define TRANS_NONE 0
46746 #define TRANS_READ 1
46747 #define TRANS_WRITE 2
46750 ** An instance of this object represents a single database file.
46752 ** A single database file can be in use as the same time by two
46753 ** or more database connections. When two or more connections are
46754 ** sharing the same database file, each connection has it own
46755 ** private Btree object for the file and each of those Btrees points
46756 ** to this one BtShared object. BtShared.nRef is the number of
46757 ** connections currently sharing this database file.
46759 ** Fields in this structure are accessed under the BtShared.mutex
46760 ** mutex, except for nRef and pNext which are accessed under the
46761 ** global SQLITE_MUTEX_STATIC_MASTER mutex. The pPager field
46762 ** may not be modified once it is initially set as long as nRef>0.
46763 ** The pSchema field may be set once under BtShared.mutex and
46764 ** thereafter is unchanged as long as nRef>0.
46766 ** isPending:
46768 ** If a BtShared client fails to obtain a write-lock on a database
46769 ** table (because there exists one or more read-locks on the table),
46770 ** the shared-cache enters 'pending-lock' state and isPending is
46771 ** set to true.
46773 ** The shared-cache leaves the 'pending lock' state when either of
46774 ** the following occur:
46776 ** 1) The current writer (BtShared.pWriter) concludes its transaction, OR
46777 ** 2) The number of locks held by other connections drops to zero.
46779 ** while in the 'pending-lock' state, no connection may start a new
46780 ** transaction.
46782 ** This feature is included to help prevent writer-starvation.
46784 struct BtShared {
46785 Pager *pPager; /* The page cache */
46786 sqlite3 *db; /* Database connection currently using this Btree */
46787 BtCursor *pCursor; /* A list of all open cursors */
46788 MemPage *pPage1; /* First page of the database */
46789 u8 readOnly; /* True if the underlying file is readonly */
46790 u8 pageSizeFixed; /* True if the page size can no longer be changed */
46791 u8 secureDelete; /* True if secure_delete is enabled */
46792 u8 initiallyEmpty; /* Database is empty at start of transaction */
46793 u8 openFlags; /* Flags to sqlite3BtreeOpen() */
46794 #ifndef SQLITE_OMIT_AUTOVACUUM
46795 u8 autoVacuum; /* True if auto-vacuum is enabled */
46796 u8 incrVacuum; /* True if incr-vacuum is enabled */
46797 #endif
46798 u8 inTransaction; /* Transaction state */
46799 u8 doNotUseWAL; /* If true, do not open write-ahead-log file */
46800 u16 maxLocal; /* Maximum local payload in non-LEAFDATA tables */
46801 u16 minLocal; /* Minimum local payload in non-LEAFDATA tables */
46802 u16 maxLeaf; /* Maximum local payload in a LEAFDATA table */
46803 u16 minLeaf; /* Minimum local payload in a LEAFDATA table */
46804 u32 pageSize; /* Total number of bytes on a page */
46805 u32 usableSize; /* Number of usable bytes on each page */
46806 int nTransaction; /* Number of open transactions (read + write) */
46807 u32 nPage; /* Number of pages in the database */
46808 void *pSchema; /* Pointer to space allocated by sqlite3BtreeSchema() */
46809 void (*xFreeSchema)(void*); /* Destructor for BtShared.pSchema */
46810 sqlite3_mutex *mutex; /* Non-recursive mutex required to access this object */
46811 Bitvec *pHasContent; /* Set of pages moved to free-list this transaction */
46812 #ifndef SQLITE_OMIT_SHARED_CACHE
46813 int nRef; /* Number of references to this structure */
46814 BtShared *pNext; /* Next on a list of sharable BtShared structs */
46815 BtLock *pLock; /* List of locks held on this shared-btree struct */
46816 Btree *pWriter; /* Btree with currently open write transaction */
46817 u8 isExclusive; /* True if pWriter has an EXCLUSIVE lock on the db */
46818 u8 isPending; /* If waiting for read-locks to clear */
46819 #endif
46820 u8 *pTmpSpace; /* BtShared.pageSize bytes of space for tmp use */
46824 ** An instance of the following structure is used to hold information
46825 ** about a cell. The parseCellPtr() function fills in this structure
46826 ** based on information extract from the raw disk page.
46828 typedef struct CellInfo CellInfo;
46829 struct CellInfo {
46830 i64 nKey; /* The key for INTKEY tables, or number of bytes in key */
46831 u8 *pCell; /* Pointer to the start of cell content */
46832 u32 nData; /* Number of bytes of data */
46833 u32 nPayload; /* Total amount of payload */
46834 u16 nHeader; /* Size of the cell content header in bytes */
46835 u16 nLocal; /* Amount of payload held locally */
46836 u16 iOverflow; /* Offset to overflow page number. Zero if no overflow */
46837 u16 nSize; /* Size of the cell content on the main b-tree page */
46841 ** Maximum depth of an SQLite B-Tree structure. Any B-Tree deeper than
46842 ** this will be declared corrupt. This value is calculated based on a
46843 ** maximum database size of 2^31 pages a minimum fanout of 2 for a
46844 ** root-node and 3 for all other internal nodes.
46846 ** If a tree that appears to be taller than this is encountered, it is
46847 ** assumed that the database is corrupt.
46849 #define BTCURSOR_MAX_DEPTH 20
46852 ** A cursor is a pointer to a particular entry within a particular
46853 ** b-tree within a database file.
46855 ** The entry is identified by its MemPage and the index in
46856 ** MemPage.aCell[] of the entry.
46858 ** A single database file can shared by two more database connections,
46859 ** but cursors cannot be shared. Each cursor is associated with a
46860 ** particular database connection identified BtCursor.pBtree.db.
46862 ** Fields in this structure are accessed under the BtShared.mutex
46863 ** found at self->pBt->mutex.
46865 struct BtCursor {
46866 Btree *pBtree; /* The Btree to which this cursor belongs */
46867 BtShared *pBt; /* The BtShared this cursor points to */
46868 BtCursor *pNext, *pPrev; /* Forms a linked list of all cursors */
46869 struct KeyInfo *pKeyInfo; /* Argument passed to comparison function */
46870 Pgno pgnoRoot; /* The root page of this tree */
46871 sqlite3_int64 cachedRowid; /* Next rowid cache. 0 means not valid */
46872 CellInfo info; /* A parse of the cell we are pointing at */
46873 i64 nKey; /* Size of pKey, or last integer key */
46874 void *pKey; /* Saved key that was cursor's last known position */
46875 int skipNext; /* Prev() is noop if negative. Next() is noop if positive */
46876 u8 wrFlag; /* True if writable */
46877 u8 atLast; /* Cursor pointing to the last entry */
46878 u8 validNKey; /* True if info.nKey is valid */
46879 u8 eState; /* One of the CURSOR_XXX constants (see below) */
46880 #ifndef SQLITE_OMIT_INCRBLOB
46881 Pgno *aOverflow; /* Cache of overflow page locations */
46882 u8 isIncrblobHandle; /* True if this cursor is an incr. io handle */
46883 #endif
46884 i16 iPage; /* Index of current page in apPage */
46885 u16 aiIdx[BTCURSOR_MAX_DEPTH]; /* Current index in apPage[i] */
46886 MemPage *apPage[BTCURSOR_MAX_DEPTH]; /* Pages from root to current page */
46890 ** Potential values for BtCursor.eState.
46892 ** CURSOR_VALID:
46893 ** Cursor points to a valid entry. getPayload() etc. may be called.
46895 ** CURSOR_INVALID:
46896 ** Cursor does not point to a valid entry. This can happen (for example)
46897 ** because the table is empty or because BtreeCursorFirst() has not been
46898 ** called.
46900 ** CURSOR_REQUIRESEEK:
46901 ** The table that this cursor was opened on still exists, but has been
46902 ** modified since the cursor was last used. The cursor position is saved
46903 ** in variables BtCursor.pKey and BtCursor.nKey. When a cursor is in
46904 ** this state, restoreCursorPosition() can be called to attempt to
46905 ** seek the cursor to the saved position.
46907 ** CURSOR_FAULT:
46908 ** A unrecoverable error (an I/O error or a malloc failure) has occurred
46909 ** on a different connection that shares the BtShared cache with this
46910 ** cursor. The error has left the cache in an inconsistent state.
46911 ** Do nothing else with this cursor. Any attempt to use the cursor
46912 ** should return the error code stored in BtCursor.skip
46914 #define CURSOR_INVALID 0
46915 #define CURSOR_VALID 1
46916 #define CURSOR_REQUIRESEEK 2
46917 #define CURSOR_FAULT 3
46920 ** The database page the PENDING_BYTE occupies. This page is never used.
46922 # define PENDING_BYTE_PAGE(pBt) PAGER_MJ_PGNO(pBt)
46925 ** These macros define the location of the pointer-map entry for a
46926 ** database page. The first argument to each is the number of usable
46927 ** bytes on each page of the database (often 1024). The second is the
46928 ** page number to look up in the pointer map.
46930 ** PTRMAP_PAGENO returns the database page number of the pointer-map
46931 ** page that stores the required pointer. PTRMAP_PTROFFSET returns
46932 ** the offset of the requested map entry.
46934 ** If the pgno argument passed to PTRMAP_PAGENO is a pointer-map page,
46935 ** then pgno is returned. So (pgno==PTRMAP_PAGENO(pgsz, pgno)) can be
46936 ** used to test if pgno is a pointer-map page. PTRMAP_ISPAGE implements
46937 ** this test.
46939 #define PTRMAP_PAGENO(pBt, pgno) ptrmapPageno(pBt, pgno)
46940 #define PTRMAP_PTROFFSET(pgptrmap, pgno) (5*(pgno-pgptrmap-1))
46941 #define PTRMAP_ISPAGE(pBt, pgno) (PTRMAP_PAGENO((pBt),(pgno))==(pgno))
46944 ** The pointer map is a lookup table that identifies the parent page for
46945 ** each child page in the database file. The parent page is the page that
46946 ** contains a pointer to the child. Every page in the database contains
46947 ** 0 or 1 parent pages. (In this context 'database page' refers
46948 ** to any page that is not part of the pointer map itself.) Each pointer map
46949 ** entry consists of a single byte 'type' and a 4 byte parent page number.
46950 ** The PTRMAP_XXX identifiers below are the valid types.
46952 ** The purpose of the pointer map is to facility moving pages from one
46953 ** position in the file to another as part of autovacuum. When a page
46954 ** is moved, the pointer in its parent must be updated to point to the
46955 ** new location. The pointer map is used to locate the parent page quickly.
46957 ** PTRMAP_ROOTPAGE: The database page is a root-page. The page-number is not
46958 ** used in this case.
46960 ** PTRMAP_FREEPAGE: The database page is an unused (free) page. The page-number
46961 ** is not used in this case.
46963 ** PTRMAP_OVERFLOW1: The database page is the first page in a list of
46964 ** overflow pages. The page number identifies the page that
46965 ** contains the cell with a pointer to this overflow page.
46967 ** PTRMAP_OVERFLOW2: The database page is the second or later page in a list of
46968 ** overflow pages. The page-number identifies the previous
46969 ** page in the overflow page list.
46971 ** PTRMAP_BTREE: The database page is a non-root btree page. The page number
46972 ** identifies the parent page in the btree.
46974 #define PTRMAP_ROOTPAGE 1
46975 #define PTRMAP_FREEPAGE 2
46976 #define PTRMAP_OVERFLOW1 3
46977 #define PTRMAP_OVERFLOW2 4
46978 #define PTRMAP_BTREE 5
46980 /* A bunch of assert() statements to check the transaction state variables
46981 ** of handle p (type Btree*) are internally consistent.
46983 #define btreeIntegrity(p) \
46984 assert( p->pBt->inTransaction!=TRANS_NONE || p->pBt->nTransaction==0 ); \
46985 assert( p->pBt->inTransaction>=p->inTrans );
46989 ** The ISAUTOVACUUM macro is used within balance_nonroot() to determine
46990 ** if the database supports auto-vacuum or not. Because it is used
46991 ** within an expression that is an argument to another macro
46992 ** (sqliteMallocRaw), it is not possible to use conditional compilation.
46993 ** So, this macro is defined instead.
46995 #ifndef SQLITE_OMIT_AUTOVACUUM
46996 #define ISAUTOVACUUM (pBt->autoVacuum)
46997 #else
46998 #define ISAUTOVACUUM 0
46999 #endif
47003 ** This structure is passed around through all the sanity checking routines
47004 ** in order to keep track of some global state information.
47006 typedef struct IntegrityCk IntegrityCk;
47007 struct IntegrityCk {
47008 BtShared *pBt; /* The tree being checked out */
47009 Pager *pPager; /* The associated pager. Also accessible by pBt->pPager */
47010 Pgno nPage; /* Number of pages in the database */
47011 int *anRef; /* Number of times each page is referenced */
47012 int mxErr; /* Stop accumulating errors when this reaches zero */
47013 int nErr; /* Number of messages written to zErrMsg so far */
47014 int mallocFailed; /* A memory allocation error has occurred */
47015 StrAccum errMsg; /* Accumulate the error message text here */
47019 ** Read or write a two- and four-byte big-endian integer values.
47021 #define get2byte(x) ((x)[0]<<8 | (x)[1])
47022 #define put2byte(p,v) ((p)[0] = (u8)((v)>>8), (p)[1] = (u8)(v))
47023 #define get4byte sqlite3Get4byte
47024 #define put4byte sqlite3Put4byte
47026 /************** End of btreeInt.h ********************************************/
47027 /************** Continuing where we left off in btmutex.c ********************/
47028 #ifndef SQLITE_OMIT_SHARED_CACHE
47029 #if SQLITE_THREADSAFE
47032 ** Obtain the BtShared mutex associated with B-Tree handle p. Also,
47033 ** set BtShared.db to the database handle associated with p and the
47034 ** p->locked boolean to true.
47036 static void lockBtreeMutex(Btree *p){
47037 assert( p->locked==0 );
47038 assert( sqlite3_mutex_notheld(p->pBt->mutex) );
47039 assert( sqlite3_mutex_held(p->db->mutex) );
47041 sqlite3_mutex_enter(p->pBt->mutex);
47042 p->pBt->db = p->db;
47043 p->locked = 1;
47047 ** Release the BtShared mutex associated with B-Tree handle p and
47048 ** clear the p->locked boolean.
47050 static void unlockBtreeMutex(Btree *p){
47051 BtShared *pBt = p->pBt;
47052 assert( p->locked==1 );
47053 assert( sqlite3_mutex_held(pBt->mutex) );
47054 assert( sqlite3_mutex_held(p->db->mutex) );
47055 assert( p->db==pBt->db );
47057 sqlite3_mutex_leave(pBt->mutex);
47058 p->locked = 0;
47062 ** Enter a mutex on the given BTree object.
47064 ** If the object is not sharable, then no mutex is ever required
47065 ** and this routine is a no-op. The underlying mutex is non-recursive.
47066 ** But we keep a reference count in Btree.wantToLock so the behavior
47067 ** of this interface is recursive.
47069 ** To avoid deadlocks, multiple Btrees are locked in the same order
47070 ** by all database connections. The p->pNext is a list of other
47071 ** Btrees belonging to the same database connection as the p Btree
47072 ** which need to be locked after p. If we cannot get a lock on
47073 ** p, then first unlock all of the others on p->pNext, then wait
47074 ** for the lock to become available on p, then relock all of the
47075 ** subsequent Btrees that desire a lock.
47077 SQLITE_PRIVATE void sqlite3BtreeEnter(Btree *p){
47078 Btree *pLater;
47080 /* Some basic sanity checking on the Btree. The list of Btrees
47081 ** connected by pNext and pPrev should be in sorted order by
47082 ** Btree.pBt value. All elements of the list should belong to
47083 ** the same connection. Only shared Btrees are on the list. */
47084 assert( p->pNext==0 || p->pNext->pBt>p->pBt );
47085 assert( p->pPrev==0 || p->pPrev->pBt<p->pBt );
47086 assert( p->pNext==0 || p->pNext->db==p->db );
47087 assert( p->pPrev==0 || p->pPrev->db==p->db );
47088 assert( p->sharable || (p->pNext==0 && p->pPrev==0) );
47090 /* Check for locking consistency */
47091 assert( !p->locked || p->wantToLock>0 );
47092 assert( p->sharable || p->wantToLock==0 );
47094 /* We should already hold a lock on the database connection */
47095 assert( sqlite3_mutex_held(p->db->mutex) );
47097 /* Unless the database is sharable and unlocked, then BtShared.db
47098 ** should already be set correctly. */
47099 assert( (p->locked==0 && p->sharable) || p->pBt->db==p->db );
47101 if( !p->sharable ) return;
47102 p->wantToLock++;
47103 if( p->locked ) return;
47105 /* In most cases, we should be able to acquire the lock we
47106 ** want without having to go throught the ascending lock
47107 ** procedure that follows. Just be sure not to block.
47109 if( sqlite3_mutex_try(p->pBt->mutex)==SQLITE_OK ){
47110 p->pBt->db = p->db;
47111 p->locked = 1;
47112 return;
47115 /* To avoid deadlock, first release all locks with a larger
47116 ** BtShared address. Then acquire our lock. Then reacquire
47117 ** the other BtShared locks that we used to hold in ascending
47118 ** order.
47120 for(pLater=p->pNext; pLater; pLater=pLater->pNext){
47121 assert( pLater->sharable );
47122 assert( pLater->pNext==0 || pLater->pNext->pBt>pLater->pBt );
47123 assert( !pLater->locked || pLater->wantToLock>0 );
47124 if( pLater->locked ){
47125 unlockBtreeMutex(pLater);
47128 lockBtreeMutex(p);
47129 for(pLater=p->pNext; pLater; pLater=pLater->pNext){
47130 if( pLater->wantToLock ){
47131 lockBtreeMutex(pLater);
47137 ** Exit the recursive mutex on a Btree.
47139 SQLITE_PRIVATE void sqlite3BtreeLeave(Btree *p){
47140 if( p->sharable ){
47141 assert( p->wantToLock>0 );
47142 p->wantToLock--;
47143 if( p->wantToLock==0 ){
47144 unlockBtreeMutex(p);
47149 #ifndef NDEBUG
47151 ** Return true if the BtShared mutex is held on the btree, or if the
47152 ** B-Tree is not marked as sharable.
47154 ** This routine is used only from within assert() statements.
47156 SQLITE_PRIVATE int sqlite3BtreeHoldsMutex(Btree *p){
47157 assert( p->sharable==0 || p->locked==0 || p->wantToLock>0 );
47158 assert( p->sharable==0 || p->locked==0 || p->db==p->pBt->db );
47159 assert( p->sharable==0 || p->locked==0 || sqlite3_mutex_held(p->pBt->mutex) );
47160 assert( p->sharable==0 || p->locked==0 || sqlite3_mutex_held(p->db->mutex) );
47162 return (p->sharable==0 || p->locked);
47164 #endif
47167 #ifndef SQLITE_OMIT_INCRBLOB
47169 ** Enter and leave a mutex on a Btree given a cursor owned by that
47170 ** Btree. These entry points are used by incremental I/O and can be
47171 ** omitted if that module is not used.
47173 SQLITE_PRIVATE void sqlite3BtreeEnterCursor(BtCursor *pCur){
47174 sqlite3BtreeEnter(pCur->pBtree);
47176 SQLITE_PRIVATE void sqlite3BtreeLeaveCursor(BtCursor *pCur){
47177 sqlite3BtreeLeave(pCur->pBtree);
47179 #endif /* SQLITE_OMIT_INCRBLOB */
47183 ** Enter the mutex on every Btree associated with a database
47184 ** connection. This is needed (for example) prior to parsing
47185 ** a statement since we will be comparing table and column names
47186 ** against all schemas and we do not want those schemas being
47187 ** reset out from under us.
47189 ** There is a corresponding leave-all procedures.
47191 ** Enter the mutexes in accending order by BtShared pointer address
47192 ** to avoid the possibility of deadlock when two threads with
47193 ** two or more btrees in common both try to lock all their btrees
47194 ** at the same instant.
47196 SQLITE_PRIVATE void sqlite3BtreeEnterAll(sqlite3 *db){
47197 int i;
47198 Btree *p;
47199 assert( sqlite3_mutex_held(db->mutex) );
47200 for(i=0; i<db->nDb; i++){
47201 p = db->aDb[i].pBt;
47202 if( p ) sqlite3BtreeEnter(p);
47205 SQLITE_PRIVATE void sqlite3BtreeLeaveAll(sqlite3 *db){
47206 int i;
47207 Btree *p;
47208 assert( sqlite3_mutex_held(db->mutex) );
47209 for(i=0; i<db->nDb; i++){
47210 p = db->aDb[i].pBt;
47211 if( p ) sqlite3BtreeLeave(p);
47216 ** Return true if a particular Btree requires a lock. Return FALSE if
47217 ** no lock is ever required since it is not sharable.
47219 SQLITE_PRIVATE int sqlite3BtreeSharable(Btree *p){
47220 return p->sharable;
47223 #ifndef NDEBUG
47225 ** Return true if the current thread holds the database connection
47226 ** mutex and all required BtShared mutexes.
47228 ** This routine is used inside assert() statements only.
47230 SQLITE_PRIVATE int sqlite3BtreeHoldsAllMutexes(sqlite3 *db){
47231 int i;
47232 if( !sqlite3_mutex_held(db->mutex) ){
47233 return 0;
47235 for(i=0; i<db->nDb; i++){
47236 Btree *p;
47237 p = db->aDb[i].pBt;
47238 if( p && p->sharable &&
47239 (p->wantToLock==0 || !sqlite3_mutex_held(p->pBt->mutex)) ){
47240 return 0;
47243 return 1;
47245 #endif /* NDEBUG */
47247 #ifndef NDEBUG
47249 ** Return true if the correct mutexes are held for accessing the
47250 ** db->aDb[iDb].pSchema structure. The mutexes required for schema
47251 ** access are:
47253 ** (1) The mutex on db
47254 ** (2) if iDb!=1, then the mutex on db->aDb[iDb].pBt.
47256 ** If pSchema is not NULL, then iDb is computed from pSchema and
47257 ** db using sqlite3SchemaToIndex().
47259 SQLITE_PRIVATE int sqlite3SchemaMutexHeld(sqlite3 *db, int iDb, Schema *pSchema){
47260 Btree *p;
47261 assert( db!=0 );
47262 if( pSchema ) iDb = sqlite3SchemaToIndex(db, pSchema);
47263 assert( iDb>=0 && iDb<db->nDb );
47264 if( !sqlite3_mutex_held(db->mutex) ) return 0;
47265 if( iDb==1 ) return 1;
47266 p = db->aDb[iDb].pBt;
47267 assert( p!=0 );
47268 return p->sharable==0 || p->locked==1;
47270 #endif /* NDEBUG */
47272 #else /* SQLITE_THREADSAFE>0 above. SQLITE_THREADSAFE==0 below */
47274 ** The following are special cases for mutex enter routines for use
47275 ** in single threaded applications that use shared cache. Except for
47276 ** these two routines, all mutex operations are no-ops in that case and
47277 ** are null #defines in btree.h.
47279 ** If shared cache is disabled, then all btree mutex routines, including
47280 ** the ones below, are no-ops and are null #defines in btree.h.
47283 SQLITE_PRIVATE void sqlite3BtreeEnter(Btree *p){
47284 p->pBt->db = p->db;
47286 SQLITE_PRIVATE void sqlite3BtreeEnterAll(sqlite3 *db){
47287 int i;
47288 for(i=0; i<db->nDb; i++){
47289 Btree *p = db->aDb[i].pBt;
47290 if( p ){
47291 p->pBt->db = p->db;
47295 #endif /* if SQLITE_THREADSAFE */
47296 #endif /* ifndef SQLITE_OMIT_SHARED_CACHE */
47298 /************** End of btmutex.c *********************************************/
47299 /************** Begin file btree.c *******************************************/
47301 ** 2004 April 6
47303 ** The author disclaims copyright to this source code. In place of
47304 ** a legal notice, here is a blessing:
47306 ** May you do good and not evil.
47307 ** May you find forgiveness for yourself and forgive others.
47308 ** May you share freely, never taking more than you give.
47310 *************************************************************************
47311 ** This file implements a external (disk-based) database using BTrees.
47312 ** See the header comment on "btreeInt.h" for additional information.
47313 ** Including a description of file format and an overview of operation.
47317 ** The header string that appears at the beginning of every
47318 ** SQLite database.
47320 static const char zMagicHeader[] = SQLITE_FILE_HEADER;
47323 ** Set this global variable to 1 to enable tracing using the TRACE
47324 ** macro.
47326 #if 0
47327 int sqlite3BtreeTrace=1; /* True to enable tracing */
47328 # define TRACE(X) if(sqlite3BtreeTrace){printf X;fflush(stdout);}
47329 #else
47330 # define TRACE(X)
47331 #endif
47334 ** Extract a 2-byte big-endian integer from an array of unsigned bytes.
47335 ** But if the value is zero, make it 65536.
47337 ** This routine is used to extract the "offset to cell content area" value
47338 ** from the header of a btree page. If the page size is 65536 and the page
47339 ** is empty, the offset should be 65536, but the 2-byte value stores zero.
47340 ** This routine makes the necessary adjustment to 65536.
47342 #define get2byteNotZero(X) (((((int)get2byte(X))-1)&0xffff)+1)
47344 #ifndef SQLITE_OMIT_SHARED_CACHE
47346 ** A list of BtShared objects that are eligible for participation
47347 ** in shared cache. This variable has file scope during normal builds,
47348 ** but the test harness needs to access it so we make it global for
47349 ** test builds.
47351 ** Access to this variable is protected by SQLITE_MUTEX_STATIC_MASTER.
47353 #ifdef SQLITE_TEST
47354 SQLITE_PRIVATE BtShared *SQLITE_WSD sqlite3SharedCacheList = 0;
47355 #else
47356 static BtShared *SQLITE_WSD sqlite3SharedCacheList = 0;
47357 #endif
47358 #endif /* SQLITE_OMIT_SHARED_CACHE */
47360 #ifndef SQLITE_OMIT_SHARED_CACHE
47362 ** Enable or disable the shared pager and schema features.
47364 ** This routine has no effect on existing database connections.
47365 ** The shared cache setting effects only future calls to
47366 ** sqlite3_open(), sqlite3_open16(), or sqlite3_open_v2().
47368 SQLITE_API int sqlite3_enable_shared_cache(int enable){
47369 sqlite3GlobalConfig.sharedCacheEnabled = enable;
47370 return SQLITE_OK;
47372 #endif
47376 #ifdef SQLITE_OMIT_SHARED_CACHE
47378 ** The functions querySharedCacheTableLock(), setSharedCacheTableLock(),
47379 ** and clearAllSharedCacheTableLocks()
47380 ** manipulate entries in the BtShared.pLock linked list used to store
47381 ** shared-cache table level locks. If the library is compiled with the
47382 ** shared-cache feature disabled, then there is only ever one user
47383 ** of each BtShared structure and so this locking is not necessary.
47384 ** So define the lock related functions as no-ops.
47386 #define querySharedCacheTableLock(a,b,c) SQLITE_OK
47387 #define setSharedCacheTableLock(a,b,c) SQLITE_OK
47388 #define clearAllSharedCacheTableLocks(a)
47389 #define downgradeAllSharedCacheTableLocks(a)
47390 #define hasSharedCacheTableLock(a,b,c,d) 1
47391 #define hasReadConflicts(a, b) 0
47392 #endif
47394 #ifndef SQLITE_OMIT_SHARED_CACHE
47396 #ifdef SQLITE_DEBUG
47398 **** This function is only used as part of an assert() statement. ***
47400 ** Check to see if pBtree holds the required locks to read or write to the
47401 ** table with root page iRoot. Return 1 if it does and 0 if not.
47403 ** For example, when writing to a table with root-page iRoot via
47404 ** Btree connection pBtree:
47406 ** assert( hasSharedCacheTableLock(pBtree, iRoot, 0, WRITE_LOCK) );
47408 ** When writing to an index that resides in a sharable database, the
47409 ** caller should have first obtained a lock specifying the root page of
47410 ** the corresponding table. This makes things a bit more complicated,
47411 ** as this module treats each table as a separate structure. To determine
47412 ** the table corresponding to the index being written, this
47413 ** function has to search through the database schema.
47415 ** Instead of a lock on the table/index rooted at page iRoot, the caller may
47416 ** hold a write-lock on the schema table (root page 1). This is also
47417 ** acceptable.
47419 static int hasSharedCacheTableLock(
47420 Btree *pBtree, /* Handle that must hold lock */
47421 Pgno iRoot, /* Root page of b-tree */
47422 int isIndex, /* True if iRoot is the root of an index b-tree */
47423 int eLockType /* Required lock type (READ_LOCK or WRITE_LOCK) */
47425 Schema *pSchema = (Schema *)pBtree->pBt->pSchema;
47426 Pgno iTab = 0;
47427 BtLock *pLock;
47429 /* If this database is not shareable, or if the client is reading
47430 ** and has the read-uncommitted flag set, then no lock is required.
47431 ** Return true immediately.
47433 if( (pBtree->sharable==0)
47434 || (eLockType==READ_LOCK && (pBtree->db->flags & SQLITE_ReadUncommitted))
47436 return 1;
47439 /* If the client is reading or writing an index and the schema is
47440 ** not loaded, then it is too difficult to actually check to see if
47441 ** the correct locks are held. So do not bother - just return true.
47442 ** This case does not come up very often anyhow.
47444 if( isIndex && (!pSchema || (pSchema->flags&DB_SchemaLoaded)==0) ){
47445 return 1;
47448 /* Figure out the root-page that the lock should be held on. For table
47449 ** b-trees, this is just the root page of the b-tree being read or
47450 ** written. For index b-trees, it is the root page of the associated
47451 ** table. */
47452 if( isIndex ){
47453 HashElem *p;
47454 for(p=sqliteHashFirst(&pSchema->idxHash); p; p=sqliteHashNext(p)){
47455 Index *pIdx = (Index *)sqliteHashData(p);
47456 if( pIdx->tnum==(int)iRoot ){
47457 iTab = pIdx->pTable->tnum;
47460 }else{
47461 iTab = iRoot;
47464 /* Search for the required lock. Either a write-lock on root-page iTab, a
47465 ** write-lock on the schema table, or (if the client is reading) a
47466 ** read-lock on iTab will suffice. Return 1 if any of these are found. */
47467 for(pLock=pBtree->pBt->pLock; pLock; pLock=pLock->pNext){
47468 if( pLock->pBtree==pBtree
47469 && (pLock->iTable==iTab || (pLock->eLock==WRITE_LOCK && pLock->iTable==1))
47470 && pLock->eLock>=eLockType
47472 return 1;
47476 /* Failed to find the required lock. */
47477 return 0;
47479 #endif /* SQLITE_DEBUG */
47481 #ifdef SQLITE_DEBUG
47483 **** This function may be used as part of assert() statements only. ****
47485 ** Return true if it would be illegal for pBtree to write into the
47486 ** table or index rooted at iRoot because other shared connections are
47487 ** simultaneously reading that same table or index.
47489 ** It is illegal for pBtree to write if some other Btree object that
47490 ** shares the same BtShared object is currently reading or writing
47491 ** the iRoot table. Except, if the other Btree object has the
47492 ** read-uncommitted flag set, then it is OK for the other object to
47493 ** have a read cursor.
47495 ** For example, before writing to any part of the table or index
47496 ** rooted at page iRoot, one should call:
47498 ** assert( !hasReadConflicts(pBtree, iRoot) );
47500 static int hasReadConflicts(Btree *pBtree, Pgno iRoot){
47501 BtCursor *p;
47502 for(p=pBtree->pBt->pCursor; p; p=p->pNext){
47503 if( p->pgnoRoot==iRoot
47504 && p->pBtree!=pBtree
47505 && 0==(p->pBtree->db->flags & SQLITE_ReadUncommitted)
47507 return 1;
47510 return 0;
47512 #endif /* #ifdef SQLITE_DEBUG */
47515 ** Query to see if Btree handle p may obtain a lock of type eLock
47516 ** (READ_LOCK or WRITE_LOCK) on the table with root-page iTab. Return
47517 ** SQLITE_OK if the lock may be obtained (by calling
47518 ** setSharedCacheTableLock()), or SQLITE_LOCKED if not.
47520 static int querySharedCacheTableLock(Btree *p, Pgno iTab, u8 eLock){
47521 BtShared *pBt = p->pBt;
47522 BtLock *pIter;
47524 assert( sqlite3BtreeHoldsMutex(p) );
47525 assert( eLock==READ_LOCK || eLock==WRITE_LOCK );
47526 assert( p->db!=0 );
47527 assert( !(p->db->flags&SQLITE_ReadUncommitted)||eLock==WRITE_LOCK||iTab==1 );
47529 /* If requesting a write-lock, then the Btree must have an open write
47530 ** transaction on this file. And, obviously, for this to be so there
47531 ** must be an open write transaction on the file itself.
47533 assert( eLock==READ_LOCK || (p==pBt->pWriter && p->inTrans==TRANS_WRITE) );
47534 assert( eLock==READ_LOCK || pBt->inTransaction==TRANS_WRITE );
47536 /* This routine is a no-op if the shared-cache is not enabled */
47537 if( !p->sharable ){
47538 return SQLITE_OK;
47541 /* If some other connection is holding an exclusive lock, the
47542 ** requested lock may not be obtained.
47544 if( pBt->pWriter!=p && pBt->isExclusive ){
47545 sqlite3ConnectionBlocked(p->db, pBt->pWriter->db);
47546 return SQLITE_LOCKED_SHAREDCACHE;
47549 for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
47550 /* The condition (pIter->eLock!=eLock) in the following if(...)
47551 ** statement is a simplification of:
47553 ** (eLock==WRITE_LOCK || pIter->eLock==WRITE_LOCK)
47555 ** since we know that if eLock==WRITE_LOCK, then no other connection
47556 ** may hold a WRITE_LOCK on any table in this file (since there can
47557 ** only be a single writer).
47559 assert( pIter->eLock==READ_LOCK || pIter->eLock==WRITE_LOCK );
47560 assert( eLock==READ_LOCK || pIter->pBtree==p || pIter->eLock==READ_LOCK);
47561 if( pIter->pBtree!=p && pIter->iTable==iTab && pIter->eLock!=eLock ){
47562 sqlite3ConnectionBlocked(p->db, pIter->pBtree->db);
47563 if( eLock==WRITE_LOCK ){
47564 assert( p==pBt->pWriter );
47565 pBt->isPending = 1;
47567 return SQLITE_LOCKED_SHAREDCACHE;
47570 return SQLITE_OK;
47572 #endif /* !SQLITE_OMIT_SHARED_CACHE */
47574 #ifndef SQLITE_OMIT_SHARED_CACHE
47576 ** Add a lock on the table with root-page iTable to the shared-btree used
47577 ** by Btree handle p. Parameter eLock must be either READ_LOCK or
47578 ** WRITE_LOCK.
47580 ** This function assumes the following:
47582 ** (a) The specified Btree object p is connected to a sharable
47583 ** database (one with the BtShared.sharable flag set), and
47585 ** (b) No other Btree objects hold a lock that conflicts
47586 ** with the requested lock (i.e. querySharedCacheTableLock() has
47587 ** already been called and returned SQLITE_OK).
47589 ** SQLITE_OK is returned if the lock is added successfully. SQLITE_NOMEM
47590 ** is returned if a malloc attempt fails.
47592 static int setSharedCacheTableLock(Btree *p, Pgno iTable, u8 eLock){
47593 BtShared *pBt = p->pBt;
47594 BtLock *pLock = 0;
47595 BtLock *pIter;
47597 assert( sqlite3BtreeHoldsMutex(p) );
47598 assert( eLock==READ_LOCK || eLock==WRITE_LOCK );
47599 assert( p->db!=0 );
47601 /* A connection with the read-uncommitted flag set will never try to
47602 ** obtain a read-lock using this function. The only read-lock obtained
47603 ** by a connection in read-uncommitted mode is on the sqlite_master
47604 ** table, and that lock is obtained in BtreeBeginTrans(). */
47605 assert( 0==(p->db->flags&SQLITE_ReadUncommitted) || eLock==WRITE_LOCK );
47607 /* This function should only be called on a sharable b-tree after it
47608 ** has been determined that no other b-tree holds a conflicting lock. */
47609 assert( p->sharable );
47610 assert( SQLITE_OK==querySharedCacheTableLock(p, iTable, eLock) );
47612 /* First search the list for an existing lock on this table. */
47613 for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
47614 if( pIter->iTable==iTable && pIter->pBtree==p ){
47615 pLock = pIter;
47616 break;
47620 /* If the above search did not find a BtLock struct associating Btree p
47621 ** with table iTable, allocate one and link it into the list.
47623 if( !pLock ){
47624 pLock = (BtLock *)sqlite3MallocZero(sizeof(BtLock));
47625 if( !pLock ){
47626 return SQLITE_NOMEM;
47628 pLock->iTable = iTable;
47629 pLock->pBtree = p;
47630 pLock->pNext = pBt->pLock;
47631 pBt->pLock = pLock;
47634 /* Set the BtLock.eLock variable to the maximum of the current lock
47635 ** and the requested lock. This means if a write-lock was already held
47636 ** and a read-lock requested, we don't incorrectly downgrade the lock.
47638 assert( WRITE_LOCK>READ_LOCK );
47639 if( eLock>pLock->eLock ){
47640 pLock->eLock = eLock;
47643 return SQLITE_OK;
47645 #endif /* !SQLITE_OMIT_SHARED_CACHE */
47647 #ifndef SQLITE_OMIT_SHARED_CACHE
47649 ** Release all the table locks (locks obtained via calls to
47650 ** the setSharedCacheTableLock() procedure) held by Btree object p.
47652 ** This function assumes that Btree p has an open read or write
47653 ** transaction. If it does not, then the BtShared.isPending variable
47654 ** may be incorrectly cleared.
47656 static void clearAllSharedCacheTableLocks(Btree *p){
47657 BtShared *pBt = p->pBt;
47658 BtLock **ppIter = &pBt->pLock;
47660 assert( sqlite3BtreeHoldsMutex(p) );
47661 assert( p->sharable || 0==*ppIter );
47662 assert( p->inTrans>0 );
47664 while( *ppIter ){
47665 BtLock *pLock = *ppIter;
47666 assert( pBt->isExclusive==0 || pBt->pWriter==pLock->pBtree );
47667 assert( pLock->pBtree->inTrans>=pLock->eLock );
47668 if( pLock->pBtree==p ){
47669 *ppIter = pLock->pNext;
47670 assert( pLock->iTable!=1 || pLock==&p->lock );
47671 if( pLock->iTable!=1 ){
47672 sqlite3_free(pLock);
47674 }else{
47675 ppIter = &pLock->pNext;
47679 assert( pBt->isPending==0 || pBt->pWriter );
47680 if( pBt->pWriter==p ){
47681 pBt->pWriter = 0;
47682 pBt->isExclusive = 0;
47683 pBt->isPending = 0;
47684 }else if( pBt->nTransaction==2 ){
47685 /* This function is called when Btree p is concluding its
47686 ** transaction. If there currently exists a writer, and p is not
47687 ** that writer, then the number of locks held by connections other
47688 ** than the writer must be about to drop to zero. In this case
47689 ** set the isPending flag to 0.
47691 ** If there is not currently a writer, then BtShared.isPending must
47692 ** be zero already. So this next line is harmless in that case.
47694 pBt->isPending = 0;
47699 ** This function changes all write-locks held by Btree p into read-locks.
47701 static void downgradeAllSharedCacheTableLocks(Btree *p){
47702 BtShared *pBt = p->pBt;
47703 if( pBt->pWriter==p ){
47704 BtLock *pLock;
47705 pBt->pWriter = 0;
47706 pBt->isExclusive = 0;
47707 pBt->isPending = 0;
47708 for(pLock=pBt->pLock; pLock; pLock=pLock->pNext){
47709 assert( pLock->eLock==READ_LOCK || pLock->pBtree==p );
47710 pLock->eLock = READ_LOCK;
47715 #endif /* SQLITE_OMIT_SHARED_CACHE */
47717 static void releasePage(MemPage *pPage); /* Forward reference */
47720 ***** This routine is used inside of assert() only ****
47722 ** Verify that the cursor holds the mutex on its BtShared
47724 #ifdef SQLITE_DEBUG
47725 static int cursorHoldsMutex(BtCursor *p){
47726 return sqlite3_mutex_held(p->pBt->mutex);
47728 #endif
47731 #ifndef SQLITE_OMIT_INCRBLOB
47733 ** Invalidate the overflow page-list cache for cursor pCur, if any.
47735 static void invalidateOverflowCache(BtCursor *pCur){
47736 assert( cursorHoldsMutex(pCur) );
47737 sqlite3_free(pCur->aOverflow);
47738 pCur->aOverflow = 0;
47742 ** Invalidate the overflow page-list cache for all cursors opened
47743 ** on the shared btree structure pBt.
47745 static void invalidateAllOverflowCache(BtShared *pBt){
47746 BtCursor *p;
47747 assert( sqlite3_mutex_held(pBt->mutex) );
47748 for(p=pBt->pCursor; p; p=p->pNext){
47749 invalidateOverflowCache(p);
47754 ** This function is called before modifying the contents of a table
47755 ** to invalidate any incrblob cursors that are open on the
47756 ** row or one of the rows being modified.
47758 ** If argument isClearTable is true, then the entire contents of the
47759 ** table is about to be deleted. In this case invalidate all incrblob
47760 ** cursors open on any row within the table with root-page pgnoRoot.
47762 ** Otherwise, if argument isClearTable is false, then the row with
47763 ** rowid iRow is being replaced or deleted. In this case invalidate
47764 ** only those incrblob cursors open on that specific row.
47766 static void invalidateIncrblobCursors(
47767 Btree *pBtree, /* The database file to check */
47768 i64 iRow, /* The rowid that might be changing */
47769 int isClearTable /* True if all rows are being deleted */
47771 BtCursor *p;
47772 BtShared *pBt = pBtree->pBt;
47773 assert( sqlite3BtreeHoldsMutex(pBtree) );
47774 for(p=pBt->pCursor; p; p=p->pNext){
47775 if( p->isIncrblobHandle && (isClearTable || p->info.nKey==iRow) ){
47776 p->eState = CURSOR_INVALID;
47781 #else
47782 /* Stub functions when INCRBLOB is omitted */
47783 #define invalidateOverflowCache(x)
47784 #define invalidateAllOverflowCache(x)
47785 #define invalidateIncrblobCursors(x,y,z)
47786 #endif /* SQLITE_OMIT_INCRBLOB */
47789 ** Set bit pgno of the BtShared.pHasContent bitvec. This is called
47790 ** when a page that previously contained data becomes a free-list leaf
47791 ** page.
47793 ** The BtShared.pHasContent bitvec exists to work around an obscure
47794 ** bug caused by the interaction of two useful IO optimizations surrounding
47795 ** free-list leaf pages:
47797 ** 1) When all data is deleted from a page and the page becomes
47798 ** a free-list leaf page, the page is not written to the database
47799 ** (as free-list leaf pages contain no meaningful data). Sometimes
47800 ** such a page is not even journalled (as it will not be modified,
47801 ** why bother journalling it?).
47803 ** 2) When a free-list leaf page is reused, its content is not read
47804 ** from the database or written to the journal file (why should it
47805 ** be, if it is not at all meaningful?).
47807 ** By themselves, these optimizations work fine and provide a handy
47808 ** performance boost to bulk delete or insert operations. However, if
47809 ** a page is moved to the free-list and then reused within the same
47810 ** transaction, a problem comes up. If the page is not journalled when
47811 ** it is moved to the free-list and it is also not journalled when it
47812 ** is extracted from the free-list and reused, then the original data
47813 ** may be lost. In the event of a rollback, it may not be possible
47814 ** to restore the database to its original configuration.
47816 ** The solution is the BtShared.pHasContent bitvec. Whenever a page is
47817 ** moved to become a free-list leaf page, the corresponding bit is
47818 ** set in the bitvec. Whenever a leaf page is extracted from the free-list,
47819 ** optimization 2 above is omitted if the corresponding bit is already
47820 ** set in BtShared.pHasContent. The contents of the bitvec are cleared
47821 ** at the end of every transaction.
47823 static int btreeSetHasContent(BtShared *pBt, Pgno pgno){
47824 int rc = SQLITE_OK;
47825 if( !pBt->pHasContent ){
47826 assert( pgno<=pBt->nPage );
47827 pBt->pHasContent = sqlite3BitvecCreate(pBt->nPage);
47828 if( !pBt->pHasContent ){
47829 rc = SQLITE_NOMEM;
47832 if( rc==SQLITE_OK && pgno<=sqlite3BitvecSize(pBt->pHasContent) ){
47833 rc = sqlite3BitvecSet(pBt->pHasContent, pgno);
47835 return rc;
47839 ** Query the BtShared.pHasContent vector.
47841 ** This function is called when a free-list leaf page is removed from the
47842 ** free-list for reuse. It returns false if it is safe to retrieve the
47843 ** page from the pager layer with the 'no-content' flag set. True otherwise.
47845 static int btreeGetHasContent(BtShared *pBt, Pgno pgno){
47846 Bitvec *p = pBt->pHasContent;
47847 return (p && (pgno>sqlite3BitvecSize(p) || sqlite3BitvecTest(p, pgno)));
47851 ** Clear (destroy) the BtShared.pHasContent bitvec. This should be
47852 ** invoked at the conclusion of each write-transaction.
47854 static void btreeClearHasContent(BtShared *pBt){
47855 sqlite3BitvecDestroy(pBt->pHasContent);
47856 pBt->pHasContent = 0;
47860 ** Save the current cursor position in the variables BtCursor.nKey
47861 ** and BtCursor.pKey. The cursor's state is set to CURSOR_REQUIRESEEK.
47863 ** The caller must ensure that the cursor is valid (has eState==CURSOR_VALID)
47864 ** prior to calling this routine.
47866 static int saveCursorPosition(BtCursor *pCur){
47867 int rc;
47869 assert( CURSOR_VALID==pCur->eState );
47870 assert( 0==pCur->pKey );
47871 assert( cursorHoldsMutex(pCur) );
47873 rc = sqlite3BtreeKeySize(pCur, &pCur->nKey);
47874 assert( rc==SQLITE_OK ); /* KeySize() cannot fail */
47876 /* If this is an intKey table, then the above call to BtreeKeySize()
47877 ** stores the integer key in pCur->nKey. In this case this value is
47878 ** all that is required. Otherwise, if pCur is not open on an intKey
47879 ** table, then malloc space for and store the pCur->nKey bytes of key
47880 ** data.
47882 if( 0==pCur->apPage[0]->intKey ){
47883 void *pKey = sqlite3Malloc( (int)pCur->nKey );
47884 if( pKey ){
47885 rc = sqlite3BtreeKey(pCur, 0, (int)pCur->nKey, pKey);
47886 if( rc==SQLITE_OK ){
47887 pCur->pKey = pKey;
47888 }else{
47889 sqlite3_free(pKey);
47891 }else{
47892 rc = SQLITE_NOMEM;
47895 assert( !pCur->apPage[0]->intKey || !pCur->pKey );
47897 if( rc==SQLITE_OK ){
47898 int i;
47899 for(i=0; i<=pCur->iPage; i++){
47900 releasePage(pCur->apPage[i]);
47901 pCur->apPage[i] = 0;
47903 pCur->iPage = -1;
47904 pCur->eState = CURSOR_REQUIRESEEK;
47907 invalidateOverflowCache(pCur);
47908 return rc;
47912 ** Save the positions of all cursors (except pExcept) that are open on
47913 ** the table with root-page iRoot. Usually, this is called just before cursor
47914 ** pExcept is used to modify the table (BtreeDelete() or BtreeInsert()).
47916 static int saveAllCursors(BtShared *pBt, Pgno iRoot, BtCursor *pExcept){
47917 BtCursor *p;
47918 assert( sqlite3_mutex_held(pBt->mutex) );
47919 assert( pExcept==0 || pExcept->pBt==pBt );
47920 for(p=pBt->pCursor; p; p=p->pNext){
47921 if( p!=pExcept && (0==iRoot || p->pgnoRoot==iRoot) &&
47922 p->eState==CURSOR_VALID ){
47923 int rc = saveCursorPosition(p);
47924 if( SQLITE_OK!=rc ){
47925 return rc;
47929 return SQLITE_OK;
47933 ** Clear the current cursor position.
47935 SQLITE_PRIVATE void sqlite3BtreeClearCursor(BtCursor *pCur){
47936 assert( cursorHoldsMutex(pCur) );
47937 sqlite3_free(pCur->pKey);
47938 pCur->pKey = 0;
47939 pCur->eState = CURSOR_INVALID;
47943 ** In this version of BtreeMoveto, pKey is a packed index record
47944 ** such as is generated by the OP_MakeRecord opcode. Unpack the
47945 ** record and then call BtreeMovetoUnpacked() to do the work.
47947 static int btreeMoveto(
47948 BtCursor *pCur, /* Cursor open on the btree to be searched */
47949 const void *pKey, /* Packed key if the btree is an index */
47950 i64 nKey, /* Integer key for tables. Size of pKey for indices */
47951 int bias, /* Bias search to the high end */
47952 int *pRes /* Write search results here */
47954 int rc; /* Status code */
47955 UnpackedRecord *pIdxKey; /* Unpacked index key */
47956 char aSpace[150]; /* Temp space for pIdxKey - to avoid a malloc */
47958 if( pKey ){
47959 assert( nKey==(i64)(int)nKey );
47960 pIdxKey = sqlite3VdbeRecordUnpack(pCur->pKeyInfo, (int)nKey, pKey,
47961 aSpace, sizeof(aSpace));
47962 if( pIdxKey==0 ) return SQLITE_NOMEM;
47963 }else{
47964 pIdxKey = 0;
47966 rc = sqlite3BtreeMovetoUnpacked(pCur, pIdxKey, nKey, bias, pRes);
47967 if( pKey ){
47968 sqlite3VdbeDeleteUnpackedRecord(pIdxKey);
47970 return rc;
47974 ** Restore the cursor to the position it was in (or as close to as possible)
47975 ** when saveCursorPosition() was called. Note that this call deletes the
47976 ** saved position info stored by saveCursorPosition(), so there can be
47977 ** at most one effective restoreCursorPosition() call after each
47978 ** saveCursorPosition().
47980 static int btreeRestoreCursorPosition(BtCursor *pCur){
47981 int rc;
47982 assert( cursorHoldsMutex(pCur) );
47983 assert( pCur->eState>=CURSOR_REQUIRESEEK );
47984 if( pCur->eState==CURSOR_FAULT ){
47985 return pCur->skipNext;
47987 pCur->eState = CURSOR_INVALID;
47988 rc = btreeMoveto(pCur, pCur->pKey, pCur->nKey, 0, &pCur->skipNext);
47989 if( rc==SQLITE_OK ){
47990 sqlite3_free(pCur->pKey);
47991 pCur->pKey = 0;
47992 assert( pCur->eState==CURSOR_VALID || pCur->eState==CURSOR_INVALID );
47994 return rc;
47997 #define restoreCursorPosition(p) \
47998 (p->eState>=CURSOR_REQUIRESEEK ? \
47999 btreeRestoreCursorPosition(p) : \
48000 SQLITE_OK)
48003 ** Determine whether or not a cursor has moved from the position it
48004 ** was last placed at. Cursors can move when the row they are pointing
48005 ** at is deleted out from under them.
48007 ** This routine returns an error code if something goes wrong. The
48008 ** integer *pHasMoved is set to one if the cursor has moved and 0 if not.
48010 SQLITE_PRIVATE int sqlite3BtreeCursorHasMoved(BtCursor *pCur, int *pHasMoved){
48011 int rc;
48013 rc = restoreCursorPosition(pCur);
48014 if( rc ){
48015 *pHasMoved = 1;
48016 return rc;
48018 if( pCur->eState!=CURSOR_VALID || pCur->skipNext!=0 ){
48019 *pHasMoved = 1;
48020 }else{
48021 *pHasMoved = 0;
48023 return SQLITE_OK;
48026 #ifndef SQLITE_OMIT_AUTOVACUUM
48028 ** Given a page number of a regular database page, return the page
48029 ** number for the pointer-map page that contains the entry for the
48030 ** input page number.
48032 ** Return 0 (not a valid page) for pgno==1 since there is
48033 ** no pointer map associated with page 1. The integrity_check logic
48034 ** requires that ptrmapPageno(*,1)!=1.
48036 static Pgno ptrmapPageno(BtShared *pBt, Pgno pgno){
48037 int nPagesPerMapPage;
48038 Pgno iPtrMap, ret;
48039 assert( sqlite3_mutex_held(pBt->mutex) );
48040 if( pgno<2 ) return 0;
48041 nPagesPerMapPage = (pBt->usableSize/5)+1;
48042 iPtrMap = (pgno-2)/nPagesPerMapPage;
48043 ret = (iPtrMap*nPagesPerMapPage) + 2;
48044 if( ret==PENDING_BYTE_PAGE(pBt) ){
48045 ret++;
48047 return ret;
48051 ** Write an entry into the pointer map.
48053 ** This routine updates the pointer map entry for page number 'key'
48054 ** so that it maps to type 'eType' and parent page number 'pgno'.
48056 ** If *pRC is initially non-zero (non-SQLITE_OK) then this routine is
48057 ** a no-op. If an error occurs, the appropriate error code is written
48058 ** into *pRC.
48060 static void ptrmapPut(BtShared *pBt, Pgno key, u8 eType, Pgno parent, int *pRC){
48061 DbPage *pDbPage; /* The pointer map page */
48062 u8 *pPtrmap; /* The pointer map data */
48063 Pgno iPtrmap; /* The pointer map page number */
48064 int offset; /* Offset in pointer map page */
48065 int rc; /* Return code from subfunctions */
48067 if( *pRC ) return;
48069 assert( sqlite3_mutex_held(pBt->mutex) );
48070 /* The master-journal page number must never be used as a pointer map page */
48071 assert( 0==PTRMAP_ISPAGE(pBt, PENDING_BYTE_PAGE(pBt)) );
48073 assert( pBt->autoVacuum );
48074 if( key==0 ){
48075 *pRC = SQLITE_CORRUPT_BKPT;
48076 return;
48078 iPtrmap = PTRMAP_PAGENO(pBt, key);
48079 rc = sqlite3PagerGet(pBt->pPager, iPtrmap, &pDbPage);
48080 if( rc!=SQLITE_OK ){
48081 *pRC = rc;
48082 return;
48084 offset = PTRMAP_PTROFFSET(iPtrmap, key);
48085 if( offset<0 ){
48086 *pRC = SQLITE_CORRUPT_BKPT;
48087 goto ptrmap_exit;
48089 pPtrmap = (u8 *)sqlite3PagerGetData(pDbPage);
48091 if( eType!=pPtrmap[offset] || get4byte(&pPtrmap[offset+1])!=parent ){
48092 TRACE(("PTRMAP_UPDATE: %d->(%d,%d)\n", key, eType, parent));
48093 *pRC= rc = sqlite3PagerWrite(pDbPage);
48094 if( rc==SQLITE_OK ){
48095 pPtrmap[offset] = eType;
48096 put4byte(&pPtrmap[offset+1], parent);
48100 ptrmap_exit:
48101 sqlite3PagerUnref(pDbPage);
48105 ** Read an entry from the pointer map.
48107 ** This routine retrieves the pointer map entry for page 'key', writing
48108 ** the type and parent page number to *pEType and *pPgno respectively.
48109 ** An error code is returned if something goes wrong, otherwise SQLITE_OK.
48111 static int ptrmapGet(BtShared *pBt, Pgno key, u8 *pEType, Pgno *pPgno){
48112 DbPage *pDbPage; /* The pointer map page */
48113 int iPtrmap; /* Pointer map page index */
48114 u8 *pPtrmap; /* Pointer map page data */
48115 int offset; /* Offset of entry in pointer map */
48116 int rc;
48118 assert( sqlite3_mutex_held(pBt->mutex) );
48120 iPtrmap = PTRMAP_PAGENO(pBt, key);
48121 rc = sqlite3PagerGet(pBt->pPager, iPtrmap, &pDbPage);
48122 if( rc!=0 ){
48123 return rc;
48125 pPtrmap = (u8 *)sqlite3PagerGetData(pDbPage);
48127 offset = PTRMAP_PTROFFSET(iPtrmap, key);
48128 assert( pEType!=0 );
48129 *pEType = pPtrmap[offset];
48130 if( pPgno ) *pPgno = get4byte(&pPtrmap[offset+1]);
48132 sqlite3PagerUnref(pDbPage);
48133 if( *pEType<1 || *pEType>5 ) return SQLITE_CORRUPT_BKPT;
48134 return SQLITE_OK;
48137 #else /* if defined SQLITE_OMIT_AUTOVACUUM */
48138 #define ptrmapPut(w,x,y,z,rc)
48139 #define ptrmapGet(w,x,y,z) SQLITE_OK
48140 #define ptrmapPutOvflPtr(x, y, rc)
48141 #endif
48144 ** Given a btree page and a cell index (0 means the first cell on
48145 ** the page, 1 means the second cell, and so forth) return a pointer
48146 ** to the cell content.
48148 ** This routine works only for pages that do not contain overflow cells.
48150 #define findCell(P,I) \
48151 ((P)->aData + ((P)->maskPage & get2byte(&(P)->aData[(P)->cellOffset+2*(I)])))
48154 ** This a more complex version of findCell() that works for
48155 ** pages that do contain overflow cells.
48157 static u8 *findOverflowCell(MemPage *pPage, int iCell){
48158 int i;
48159 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
48160 for(i=pPage->nOverflow-1; i>=0; i--){
48161 int k;
48162 struct _OvflCell *pOvfl;
48163 pOvfl = &pPage->aOvfl[i];
48164 k = pOvfl->idx;
48165 if( k<=iCell ){
48166 if( k==iCell ){
48167 return pOvfl->pCell;
48169 iCell--;
48172 return findCell(pPage, iCell);
48176 ** Parse a cell content block and fill in the CellInfo structure. There
48177 ** are two versions of this function. btreeParseCell() takes a
48178 ** cell index as the second argument and btreeParseCellPtr()
48179 ** takes a pointer to the body of the cell as its second argument.
48181 ** Within this file, the parseCell() macro can be called instead of
48182 ** btreeParseCellPtr(). Using some compilers, this will be faster.
48184 static void btreeParseCellPtr(
48185 MemPage *pPage, /* Page containing the cell */
48186 u8 *pCell, /* Pointer to the cell text. */
48187 CellInfo *pInfo /* Fill in this structure */
48189 u16 n; /* Number bytes in cell content header */
48190 u32 nPayload; /* Number of bytes of cell payload */
48192 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
48194 pInfo->pCell = pCell;
48195 assert( pPage->leaf==0 || pPage->leaf==1 );
48196 n = pPage->childPtrSize;
48197 assert( n==4-4*pPage->leaf );
48198 if( pPage->intKey ){
48199 if( pPage->hasData ){
48200 n += getVarint32(&pCell[n], nPayload);
48201 }else{
48202 nPayload = 0;
48204 n += getVarint(&pCell[n], (u64*)&pInfo->nKey);
48205 pInfo->nData = nPayload;
48206 }else{
48207 pInfo->nData = 0;
48208 n += getVarint32(&pCell[n], nPayload);
48209 pInfo->nKey = nPayload;
48211 pInfo->nPayload = nPayload;
48212 pInfo->nHeader = n;
48213 testcase( nPayload==pPage->maxLocal );
48214 testcase( nPayload==pPage->maxLocal+1 );
48215 if( likely(nPayload<=pPage->maxLocal) ){
48216 /* This is the (easy) common case where the entire payload fits
48217 ** on the local page. No overflow is required.
48219 if( (pInfo->nSize = (u16)(n+nPayload))<4 ) pInfo->nSize = 4;
48220 pInfo->nLocal = (u16)nPayload;
48221 pInfo->iOverflow = 0;
48222 }else{
48223 /* If the payload will not fit completely on the local page, we have
48224 ** to decide how much to store locally and how much to spill onto
48225 ** overflow pages. The strategy is to minimize the amount of unused
48226 ** space on overflow pages while keeping the amount of local storage
48227 ** in between minLocal and maxLocal.
48229 ** Warning: changing the way overflow payload is distributed in any
48230 ** way will result in an incompatible file format.
48232 int minLocal; /* Minimum amount of payload held locally */
48233 int maxLocal; /* Maximum amount of payload held locally */
48234 int surplus; /* Overflow payload available for local storage */
48236 minLocal = pPage->minLocal;
48237 maxLocal = pPage->maxLocal;
48238 surplus = minLocal + (nPayload - minLocal)%(pPage->pBt->usableSize - 4);
48239 testcase( surplus==maxLocal );
48240 testcase( surplus==maxLocal+1 );
48241 if( surplus <= maxLocal ){
48242 pInfo->nLocal = (u16)surplus;
48243 }else{
48244 pInfo->nLocal = (u16)minLocal;
48246 pInfo->iOverflow = (u16)(pInfo->nLocal + n);
48247 pInfo->nSize = pInfo->iOverflow + 4;
48250 #define parseCell(pPage, iCell, pInfo) \
48251 btreeParseCellPtr((pPage), findCell((pPage), (iCell)), (pInfo))
48252 static void btreeParseCell(
48253 MemPage *pPage, /* Page containing the cell */
48254 int iCell, /* The cell index. First cell is 0 */
48255 CellInfo *pInfo /* Fill in this structure */
48257 parseCell(pPage, iCell, pInfo);
48261 ** Compute the total number of bytes that a Cell needs in the cell
48262 ** data area of the btree-page. The return number includes the cell
48263 ** data header and the local payload, but not any overflow page or
48264 ** the space used by the cell pointer.
48266 static u16 cellSizePtr(MemPage *pPage, u8 *pCell){
48267 u8 *pIter = &pCell[pPage->childPtrSize];
48268 u32 nSize;
48270 #ifdef SQLITE_DEBUG
48271 /* The value returned by this function should always be the same as
48272 ** the (CellInfo.nSize) value found by doing a full parse of the
48273 ** cell. If SQLITE_DEBUG is defined, an assert() at the bottom of
48274 ** this function verifies that this invariant is not violated. */
48275 CellInfo debuginfo;
48276 btreeParseCellPtr(pPage, pCell, &debuginfo);
48277 #endif
48279 if( pPage->intKey ){
48280 u8 *pEnd;
48281 if( pPage->hasData ){
48282 pIter += getVarint32(pIter, nSize);
48283 }else{
48284 nSize = 0;
48287 /* pIter now points at the 64-bit integer key value, a variable length
48288 ** integer. The following block moves pIter to point at the first byte
48289 ** past the end of the key value. */
48290 pEnd = &pIter[9];
48291 while( (*pIter++)&0x80 && pIter<pEnd );
48292 }else{
48293 pIter += getVarint32(pIter, nSize);
48296 testcase( nSize==pPage->maxLocal );
48297 testcase( nSize==pPage->maxLocal+1 );
48298 if( nSize>pPage->maxLocal ){
48299 int minLocal = pPage->minLocal;
48300 nSize = minLocal + (nSize - minLocal) % (pPage->pBt->usableSize - 4);
48301 testcase( nSize==pPage->maxLocal );
48302 testcase( nSize==pPage->maxLocal+1 );
48303 if( nSize>pPage->maxLocal ){
48304 nSize = minLocal;
48306 nSize += 4;
48308 nSize += (u32)(pIter - pCell);
48310 /* The minimum size of any cell is 4 bytes. */
48311 if( nSize<4 ){
48312 nSize = 4;
48315 assert( nSize==debuginfo.nSize );
48316 return (u16)nSize;
48319 #ifdef SQLITE_DEBUG
48320 /* This variation on cellSizePtr() is used inside of assert() statements
48321 ** only. */
48322 static u16 cellSize(MemPage *pPage, int iCell){
48323 return cellSizePtr(pPage, findCell(pPage, iCell));
48325 #endif
48327 #ifndef SQLITE_OMIT_AUTOVACUUM
48329 ** If the cell pCell, part of page pPage contains a pointer
48330 ** to an overflow page, insert an entry into the pointer-map
48331 ** for the overflow page.
48333 static void ptrmapPutOvflPtr(MemPage *pPage, u8 *pCell, int *pRC){
48334 CellInfo info;
48335 if( *pRC ) return;
48336 assert( pCell!=0 );
48337 btreeParseCellPtr(pPage, pCell, &info);
48338 assert( (info.nData+(pPage->intKey?0:info.nKey))==info.nPayload );
48339 if( info.iOverflow ){
48340 Pgno ovfl = get4byte(&pCell[info.iOverflow]);
48341 ptrmapPut(pPage->pBt, ovfl, PTRMAP_OVERFLOW1, pPage->pgno, pRC);
48344 #endif
48348 ** Defragment the page given. All Cells are moved to the
48349 ** end of the page and all free space is collected into one
48350 ** big FreeBlk that occurs in between the header and cell
48351 ** pointer array and the cell content area.
48353 static int defragmentPage(MemPage *pPage){
48354 int i; /* Loop counter */
48355 int pc; /* Address of a i-th cell */
48356 int hdr; /* Offset to the page header */
48357 int size; /* Size of a cell */
48358 int usableSize; /* Number of usable bytes on a page */
48359 int cellOffset; /* Offset to the cell pointer array */
48360 int cbrk; /* Offset to the cell content area */
48361 int nCell; /* Number of cells on the page */
48362 unsigned char *data; /* The page data */
48363 unsigned char *temp; /* Temp area for cell content */
48364 int iCellFirst; /* First allowable cell index */
48365 int iCellLast; /* Last possible cell index */
48368 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
48369 assert( pPage->pBt!=0 );
48370 assert( pPage->pBt->usableSize <= SQLITE_MAX_PAGE_SIZE );
48371 assert( pPage->nOverflow==0 );
48372 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
48373 temp = sqlite3PagerTempSpace(pPage->pBt->pPager);
48374 data = pPage->aData;
48375 hdr = pPage->hdrOffset;
48376 cellOffset = pPage->cellOffset;
48377 nCell = pPage->nCell;
48378 assert( nCell==get2byte(&data[hdr+3]) );
48379 usableSize = pPage->pBt->usableSize;
48380 cbrk = get2byte(&data[hdr+5]);
48381 memcpy(&temp[cbrk], &data[cbrk], usableSize - cbrk);
48382 cbrk = usableSize;
48383 iCellFirst = cellOffset + 2*nCell;
48384 iCellLast = usableSize - 4;
48385 for(i=0; i<nCell; i++){
48386 u8 *pAddr; /* The i-th cell pointer */
48387 pAddr = &data[cellOffset + i*2];
48388 pc = get2byte(pAddr);
48389 testcase( pc==iCellFirst );
48390 testcase( pc==iCellLast );
48391 #if !defined(SQLITE_ENABLE_OVERSIZE_CELL_CHECK)
48392 /* These conditions have already been verified in btreeInitPage()
48393 ** if SQLITE_ENABLE_OVERSIZE_CELL_CHECK is defined
48395 if( pc<iCellFirst || pc>iCellLast ){
48396 return SQLITE_CORRUPT_BKPT;
48398 #endif
48399 assert( pc>=iCellFirst && pc<=iCellLast );
48400 size = cellSizePtr(pPage, &temp[pc]);
48401 cbrk -= size;
48402 #if defined(SQLITE_ENABLE_OVERSIZE_CELL_CHECK)
48403 if( cbrk<iCellFirst ){
48404 return SQLITE_CORRUPT_BKPT;
48406 #else
48407 if( cbrk<iCellFirst || pc+size>usableSize ){
48408 return SQLITE_CORRUPT_BKPT;
48410 #endif
48411 assert( cbrk+size<=usableSize && cbrk>=iCellFirst );
48412 testcase( cbrk+size==usableSize );
48413 testcase( pc+size==usableSize );
48414 memcpy(&data[cbrk], &temp[pc], size);
48415 put2byte(pAddr, cbrk);
48417 assert( cbrk>=iCellFirst );
48418 put2byte(&data[hdr+5], cbrk);
48419 data[hdr+1] = 0;
48420 data[hdr+2] = 0;
48421 data[hdr+7] = 0;
48422 memset(&data[iCellFirst], 0, cbrk-iCellFirst);
48423 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
48424 if( cbrk-iCellFirst!=pPage->nFree ){
48425 return SQLITE_CORRUPT_BKPT;
48427 return SQLITE_OK;
48431 ** Allocate nByte bytes of space from within the B-Tree page passed
48432 ** as the first argument. Write into *pIdx the index into pPage->aData[]
48433 ** of the first byte of allocated space. Return either SQLITE_OK or
48434 ** an error code (usually SQLITE_CORRUPT).
48436 ** The caller guarantees that there is sufficient space to make the
48437 ** allocation. This routine might need to defragment in order to bring
48438 ** all the space together, however. This routine will avoid using
48439 ** the first two bytes past the cell pointer area since presumably this
48440 ** allocation is being made in order to insert a new cell, so we will
48441 ** also end up needing a new cell pointer.
48443 static int allocateSpace(MemPage *pPage, int nByte, int *pIdx){
48444 const int hdr = pPage->hdrOffset; /* Local cache of pPage->hdrOffset */
48445 u8 * const data = pPage->aData; /* Local cache of pPage->aData */
48446 int nFrag; /* Number of fragmented bytes on pPage */
48447 int top; /* First byte of cell content area */
48448 int gap; /* First byte of gap between cell pointers and cell content */
48449 int rc; /* Integer return code */
48450 int usableSize; /* Usable size of the page */
48452 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
48453 assert( pPage->pBt );
48454 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
48455 assert( nByte>=0 ); /* Minimum cell size is 4 */
48456 assert( pPage->nFree>=nByte );
48457 assert( pPage->nOverflow==0 );
48458 usableSize = pPage->pBt->usableSize;
48459 assert( nByte < usableSize-8 );
48461 nFrag = data[hdr+7];
48462 assert( pPage->cellOffset == hdr + 12 - 4*pPage->leaf );
48463 gap = pPage->cellOffset + 2*pPage->nCell;
48464 top = get2byteNotZero(&data[hdr+5]);
48465 if( gap>top ) return SQLITE_CORRUPT_BKPT;
48466 testcase( gap+2==top );
48467 testcase( gap+1==top );
48468 testcase( gap==top );
48470 if( nFrag>=60 ){
48471 /* Always defragment highly fragmented pages */
48472 rc = defragmentPage(pPage);
48473 if( rc ) return rc;
48474 top = get2byteNotZero(&data[hdr+5]);
48475 }else if( gap+2<=top ){
48476 /* Search the freelist looking for a free slot big enough to satisfy
48477 ** the request. The allocation is made from the first free slot in
48478 ** the list that is large enough to accomadate it.
48480 int pc, addr;
48481 for(addr=hdr+1; (pc = get2byte(&data[addr]))>0; addr=pc){
48482 int size; /* Size of the free slot */
48483 if( pc>usableSize-4 || pc<addr+4 ){
48484 return SQLITE_CORRUPT_BKPT;
48486 size = get2byte(&data[pc+2]);
48487 if( size>=nByte ){
48488 int x = size - nByte;
48489 testcase( x==4 );
48490 testcase( x==3 );
48491 if( x<4 ){
48492 /* Remove the slot from the free-list. Update the number of
48493 ** fragmented bytes within the page. */
48494 memcpy(&data[addr], &data[pc], 2);
48495 data[hdr+7] = (u8)(nFrag + x);
48496 }else if( size+pc > usableSize ){
48497 return SQLITE_CORRUPT_BKPT;
48498 }else{
48499 /* The slot remains on the free-list. Reduce its size to account
48500 ** for the portion used by the new allocation. */
48501 put2byte(&data[pc+2], x);
48503 *pIdx = pc + x;
48504 return SQLITE_OK;
48509 /* Check to make sure there is enough space in the gap to satisfy
48510 ** the allocation. If not, defragment.
48512 testcase( gap+2+nByte==top );
48513 if( gap+2+nByte>top ){
48514 rc = defragmentPage(pPage);
48515 if( rc ) return rc;
48516 top = get2byteNotZero(&data[hdr+5]);
48517 assert( gap+nByte<=top );
48521 /* Allocate memory from the gap in between the cell pointer array
48522 ** and the cell content area. The btreeInitPage() call has already
48523 ** validated the freelist. Given that the freelist is valid, there
48524 ** is no way that the allocation can extend off the end of the page.
48525 ** The assert() below verifies the previous sentence.
48527 top -= nByte;
48528 put2byte(&data[hdr+5], top);
48529 assert( top+nByte <= (int)pPage->pBt->usableSize );
48530 *pIdx = top;
48531 return SQLITE_OK;
48535 ** Return a section of the pPage->aData to the freelist.
48536 ** The first byte of the new free block is pPage->aDisk[start]
48537 ** and the size of the block is "size" bytes.
48539 ** Most of the effort here is involved in coalesing adjacent
48540 ** free blocks into a single big free block.
48542 static int freeSpace(MemPage *pPage, int start, int size){
48543 int addr, pbegin, hdr;
48544 int iLast; /* Largest possible freeblock offset */
48545 unsigned char *data = pPage->aData;
48547 assert( pPage->pBt!=0 );
48548 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
48549 assert( start>=pPage->hdrOffset+6+pPage->childPtrSize );
48550 assert( (start + size) <= (int)pPage->pBt->usableSize );
48551 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
48552 assert( size>=0 ); /* Minimum cell size is 4 */
48554 if( pPage->pBt->secureDelete ){
48555 /* Overwrite deleted information with zeros when the secure_delete
48556 ** option is enabled */
48557 memset(&data[start], 0, size);
48560 /* Add the space back into the linked list of freeblocks. Note that
48561 ** even though the freeblock list was checked by btreeInitPage(),
48562 ** btreeInitPage() did not detect overlapping cells or
48563 ** freeblocks that overlapped cells. Nor does it detect when the
48564 ** cell content area exceeds the value in the page header. If these
48565 ** situations arise, then subsequent insert operations might corrupt
48566 ** the freelist. So we do need to check for corruption while scanning
48567 ** the freelist.
48569 hdr = pPage->hdrOffset;
48570 addr = hdr + 1;
48571 iLast = pPage->pBt->usableSize - 4;
48572 assert( start<=iLast );
48573 while( (pbegin = get2byte(&data[addr]))<start && pbegin>0 ){
48574 if( pbegin<addr+4 ){
48575 return SQLITE_CORRUPT_BKPT;
48577 addr = pbegin;
48579 if( pbegin>iLast ){
48580 return SQLITE_CORRUPT_BKPT;
48582 assert( pbegin>addr || pbegin==0 );
48583 put2byte(&data[addr], start);
48584 put2byte(&data[start], pbegin);
48585 put2byte(&data[start+2], size);
48586 pPage->nFree = pPage->nFree + (u16)size;
48588 /* Coalesce adjacent free blocks */
48589 addr = hdr + 1;
48590 while( (pbegin = get2byte(&data[addr]))>0 ){
48591 int pnext, psize, x;
48592 assert( pbegin>addr );
48593 assert( pbegin <= (int)pPage->pBt->usableSize-4 );
48594 pnext = get2byte(&data[pbegin]);
48595 psize = get2byte(&data[pbegin+2]);
48596 if( pbegin + psize + 3 >= pnext && pnext>0 ){
48597 int frag = pnext - (pbegin+psize);
48598 if( (frag<0) || (frag>(int)data[hdr+7]) ){
48599 return SQLITE_CORRUPT_BKPT;
48601 data[hdr+7] -= (u8)frag;
48602 x = get2byte(&data[pnext]);
48603 put2byte(&data[pbegin], x);
48604 x = pnext + get2byte(&data[pnext+2]) - pbegin;
48605 put2byte(&data[pbegin+2], x);
48606 }else{
48607 addr = pbegin;
48611 /* If the cell content area begins with a freeblock, remove it. */
48612 if( data[hdr+1]==data[hdr+5] && data[hdr+2]==data[hdr+6] ){
48613 int top;
48614 pbegin = get2byte(&data[hdr+1]);
48615 memcpy(&data[hdr+1], &data[pbegin], 2);
48616 top = get2byte(&data[hdr+5]) + get2byte(&data[pbegin+2]);
48617 put2byte(&data[hdr+5], top);
48619 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
48620 return SQLITE_OK;
48624 ** Decode the flags byte (the first byte of the header) for a page
48625 ** and initialize fields of the MemPage structure accordingly.
48627 ** Only the following combinations are supported. Anything different
48628 ** indicates a corrupt database files:
48630 ** PTF_ZERODATA
48631 ** PTF_ZERODATA | PTF_LEAF
48632 ** PTF_LEAFDATA | PTF_INTKEY
48633 ** PTF_LEAFDATA | PTF_INTKEY | PTF_LEAF
48635 static int decodeFlags(MemPage *pPage, int flagByte){
48636 BtShared *pBt; /* A copy of pPage->pBt */
48638 assert( pPage->hdrOffset==(pPage->pgno==1 ? 100 : 0) );
48639 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
48640 pPage->leaf = (u8)(flagByte>>3); assert( PTF_LEAF == 1<<3 );
48641 flagByte &= ~PTF_LEAF;
48642 pPage->childPtrSize = 4-4*pPage->leaf;
48643 pBt = pPage->pBt;
48644 if( flagByte==(PTF_LEAFDATA | PTF_INTKEY) ){
48645 pPage->intKey = 1;
48646 pPage->hasData = pPage->leaf;
48647 pPage->maxLocal = pBt->maxLeaf;
48648 pPage->minLocal = pBt->minLeaf;
48649 }else if( flagByte==PTF_ZERODATA ){
48650 pPage->intKey = 0;
48651 pPage->hasData = 0;
48652 pPage->maxLocal = pBt->maxLocal;
48653 pPage->minLocal = pBt->minLocal;
48654 }else{
48655 return SQLITE_CORRUPT_BKPT;
48657 return SQLITE_OK;
48661 ** Initialize the auxiliary information for a disk block.
48663 ** Return SQLITE_OK on success. If we see that the page does
48664 ** not contain a well-formed database page, then return
48665 ** SQLITE_CORRUPT. Note that a return of SQLITE_OK does not
48666 ** guarantee that the page is well-formed. It only shows that
48667 ** we failed to detect any corruption.
48669 static int btreeInitPage(MemPage *pPage){
48671 assert( pPage->pBt!=0 );
48672 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
48673 assert( pPage->pgno==sqlite3PagerPagenumber(pPage->pDbPage) );
48674 assert( pPage == sqlite3PagerGetExtra(pPage->pDbPage) );
48675 assert( pPage->aData == sqlite3PagerGetData(pPage->pDbPage) );
48677 if( !pPage->isInit ){
48678 u16 pc; /* Address of a freeblock within pPage->aData[] */
48679 u8 hdr; /* Offset to beginning of page header */
48680 u8 *data; /* Equal to pPage->aData */
48681 BtShared *pBt; /* The main btree structure */
48682 int usableSize; /* Amount of usable space on each page */
48683 u16 cellOffset; /* Offset from start of page to first cell pointer */
48684 int nFree; /* Number of unused bytes on the page */
48685 int top; /* First byte of the cell content area */
48686 int iCellFirst; /* First allowable cell or freeblock offset */
48687 int iCellLast; /* Last possible cell or freeblock offset */
48689 pBt = pPage->pBt;
48691 hdr = pPage->hdrOffset;
48692 data = pPage->aData;
48693 if( decodeFlags(pPage, data[hdr]) ) return SQLITE_CORRUPT_BKPT;
48694 assert( pBt->pageSize>=512 && pBt->pageSize<=65536 );
48695 pPage->maskPage = (u16)(pBt->pageSize - 1);
48696 pPage->nOverflow = 0;
48697 usableSize = pBt->usableSize;
48698 pPage->cellOffset = cellOffset = hdr + 12 - 4*pPage->leaf;
48699 top = get2byteNotZero(&data[hdr+5]);
48700 pPage->nCell = get2byte(&data[hdr+3]);
48701 if( pPage->nCell>MX_CELL(pBt) ){
48702 /* To many cells for a single page. The page must be corrupt */
48703 return SQLITE_CORRUPT_BKPT;
48705 testcase( pPage->nCell==MX_CELL(pBt) );
48707 /* A malformed database page might cause us to read past the end
48708 ** of page when parsing a cell.
48710 ** The following block of code checks early to see if a cell extends
48711 ** past the end of a page boundary and causes SQLITE_CORRUPT to be
48712 ** returned if it does.
48714 iCellFirst = cellOffset + 2*pPage->nCell;
48715 iCellLast = usableSize - 4;
48716 #if defined(SQLITE_ENABLE_OVERSIZE_CELL_CHECK)
48718 int i; /* Index into the cell pointer array */
48719 int sz; /* Size of a cell */
48721 if( !pPage->leaf ) iCellLast--;
48722 for(i=0; i<pPage->nCell; i++){
48723 pc = get2byte(&data[cellOffset+i*2]);
48724 testcase( pc==iCellFirst );
48725 testcase( pc==iCellLast );
48726 if( pc<iCellFirst || pc>iCellLast ){
48727 return SQLITE_CORRUPT_BKPT;
48729 sz = cellSizePtr(pPage, &data[pc]);
48730 testcase( pc+sz==usableSize );
48731 if( pc+sz>usableSize ){
48732 return SQLITE_CORRUPT_BKPT;
48735 if( !pPage->leaf ) iCellLast++;
48737 #endif
48739 /* Compute the total free space on the page */
48740 pc = get2byte(&data[hdr+1]);
48741 nFree = data[hdr+7] + top;
48742 while( pc>0 ){
48743 u16 next, size;
48744 if( pc<iCellFirst || pc>iCellLast ){
48745 /* Start of free block is off the page */
48746 return SQLITE_CORRUPT_BKPT;
48748 next = get2byte(&data[pc]);
48749 size = get2byte(&data[pc+2]);
48750 if( (next>0 && next<=pc+size+3) || pc+size>usableSize ){
48751 /* Free blocks must be in ascending order. And the last byte of
48752 ** the free-block must lie on the database page. */
48753 return SQLITE_CORRUPT_BKPT;
48755 nFree = nFree + size;
48756 pc = next;
48759 /* At this point, nFree contains the sum of the offset to the start
48760 ** of the cell-content area plus the number of free bytes within
48761 ** the cell-content area. If this is greater than the usable-size
48762 ** of the page, then the page must be corrupted. This check also
48763 ** serves to verify that the offset to the start of the cell-content
48764 ** area, according to the page header, lies within the page.
48766 if( nFree>usableSize ){
48767 return SQLITE_CORRUPT_BKPT;
48769 pPage->nFree = (u16)(nFree - iCellFirst);
48770 pPage->isInit = 1;
48772 return SQLITE_OK;
48776 ** Set up a raw page so that it looks like a database page holding
48777 ** no entries.
48779 static void zeroPage(MemPage *pPage, int flags){
48780 unsigned char *data = pPage->aData;
48781 BtShared *pBt = pPage->pBt;
48782 u8 hdr = pPage->hdrOffset;
48783 u16 first;
48785 assert( sqlite3PagerPagenumber(pPage->pDbPage)==pPage->pgno );
48786 assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage );
48787 assert( sqlite3PagerGetData(pPage->pDbPage) == data );
48788 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
48789 assert( sqlite3_mutex_held(pBt->mutex) );
48790 if( pBt->secureDelete ){
48791 memset(&data[hdr], 0, pBt->usableSize - hdr);
48793 data[hdr] = (char)flags;
48794 first = hdr + 8 + 4*((flags&PTF_LEAF)==0 ?1:0);
48795 memset(&data[hdr+1], 0, 4);
48796 data[hdr+7] = 0;
48797 put2byte(&data[hdr+5], pBt->usableSize);
48798 pPage->nFree = (u16)(pBt->usableSize - first);
48799 decodeFlags(pPage, flags);
48800 pPage->hdrOffset = hdr;
48801 pPage->cellOffset = first;
48802 pPage->nOverflow = 0;
48803 assert( pBt->pageSize>=512 && pBt->pageSize<=65536 );
48804 pPage->maskPage = (u16)(pBt->pageSize - 1);
48805 pPage->nCell = 0;
48806 pPage->isInit = 1;
48811 ** Convert a DbPage obtained from the pager into a MemPage used by
48812 ** the btree layer.
48814 static MemPage *btreePageFromDbPage(DbPage *pDbPage, Pgno pgno, BtShared *pBt){
48815 MemPage *pPage = (MemPage*)sqlite3PagerGetExtra(pDbPage);
48816 pPage->aData = sqlite3PagerGetData(pDbPage);
48817 pPage->pDbPage = pDbPage;
48818 pPage->pBt = pBt;
48819 pPage->pgno = pgno;
48820 pPage->hdrOffset = pPage->pgno==1 ? 100 : 0;
48821 return pPage;
48825 ** Get a page from the pager. Initialize the MemPage.pBt and
48826 ** MemPage.aData elements if needed.
48828 ** If the noContent flag is set, it means that we do not care about
48829 ** the content of the page at this time. So do not go to the disk
48830 ** to fetch the content. Just fill in the content with zeros for now.
48831 ** If in the future we call sqlite3PagerWrite() on this page, that
48832 ** means we have started to be concerned about content and the disk
48833 ** read should occur at that point.
48835 static int btreeGetPage(
48836 BtShared *pBt, /* The btree */
48837 Pgno pgno, /* Number of the page to fetch */
48838 MemPage **ppPage, /* Return the page in this parameter */
48839 int noContent /* Do not load page content if true */
48841 int rc;
48842 DbPage *pDbPage;
48844 assert( sqlite3_mutex_held(pBt->mutex) );
48845 rc = sqlite3PagerAcquire(pBt->pPager, pgno, (DbPage**)&pDbPage, noContent);
48846 if( rc ) return rc;
48847 *ppPage = btreePageFromDbPage(pDbPage, pgno, pBt);
48848 return SQLITE_OK;
48852 ** Retrieve a page from the pager cache. If the requested page is not
48853 ** already in the pager cache return NULL. Initialize the MemPage.pBt and
48854 ** MemPage.aData elements if needed.
48856 static MemPage *btreePageLookup(BtShared *pBt, Pgno pgno){
48857 DbPage *pDbPage;
48858 assert( sqlite3_mutex_held(pBt->mutex) );
48859 pDbPage = sqlite3PagerLookup(pBt->pPager, pgno);
48860 if( pDbPage ){
48861 return btreePageFromDbPage(pDbPage, pgno, pBt);
48863 return 0;
48867 ** Return the size of the database file in pages. If there is any kind of
48868 ** error, return ((unsigned int)-1).
48870 static Pgno btreePagecount(BtShared *pBt){
48871 return pBt->nPage;
48873 SQLITE_PRIVATE u32 sqlite3BtreeLastPage(Btree *p){
48874 assert( sqlite3BtreeHoldsMutex(p) );
48875 assert( ((p->pBt->nPage)&0x8000000)==0 );
48876 return (int)btreePagecount(p->pBt);
48880 ** Get a page from the pager and initialize it. This routine is just a
48881 ** convenience wrapper around separate calls to btreeGetPage() and
48882 ** btreeInitPage().
48884 ** If an error occurs, then the value *ppPage is set to is undefined. It
48885 ** may remain unchanged, or it may be set to an invalid value.
48887 static int getAndInitPage(
48888 BtShared *pBt, /* The database file */
48889 Pgno pgno, /* Number of the page to get */
48890 MemPage **ppPage /* Write the page pointer here */
48892 int rc;
48893 assert( sqlite3_mutex_held(pBt->mutex) );
48895 if( pgno>btreePagecount(pBt) ){
48896 rc = SQLITE_CORRUPT_BKPT;
48897 }else{
48898 rc = btreeGetPage(pBt, pgno, ppPage, 0);
48899 if( rc==SQLITE_OK ){
48900 rc = btreeInitPage(*ppPage);
48901 if( rc!=SQLITE_OK ){
48902 releasePage(*ppPage);
48907 testcase( pgno==0 );
48908 assert( pgno!=0 || rc==SQLITE_CORRUPT );
48909 return rc;
48913 ** Release a MemPage. This should be called once for each prior
48914 ** call to btreeGetPage.
48916 static void releasePage(MemPage *pPage){
48917 if( pPage ){
48918 assert( pPage->aData );
48919 assert( pPage->pBt );
48920 assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage );
48921 assert( sqlite3PagerGetData(pPage->pDbPage)==pPage->aData );
48922 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
48923 sqlite3PagerUnref(pPage->pDbPage);
48928 ** During a rollback, when the pager reloads information into the cache
48929 ** so that the cache is restored to its original state at the start of
48930 ** the transaction, for each page restored this routine is called.
48932 ** This routine needs to reset the extra data section at the end of the
48933 ** page to agree with the restored data.
48935 static void pageReinit(DbPage *pData){
48936 MemPage *pPage;
48937 pPage = (MemPage *)sqlite3PagerGetExtra(pData);
48938 assert( sqlite3PagerPageRefcount(pData)>0 );
48939 if( pPage->isInit ){
48940 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
48941 pPage->isInit = 0;
48942 if( sqlite3PagerPageRefcount(pData)>1 ){
48943 /* pPage might not be a btree page; it might be an overflow page
48944 ** or ptrmap page or a free page. In those cases, the following
48945 ** call to btreeInitPage() will likely return SQLITE_CORRUPT.
48946 ** But no harm is done by this. And it is very important that
48947 ** btreeInitPage() be called on every btree page so we make
48948 ** the call for every page that comes in for re-initing. */
48949 btreeInitPage(pPage);
48955 ** Invoke the busy handler for a btree.
48957 static int btreeInvokeBusyHandler(void *pArg){
48958 BtShared *pBt = (BtShared*)pArg;
48959 assert( pBt->db );
48960 assert( sqlite3_mutex_held(pBt->db->mutex) );
48961 return sqlite3InvokeBusyHandler(&pBt->db->busyHandler);
48965 ** Open a database file.
48967 ** zFilename is the name of the database file. If zFilename is NULL
48968 ** then an ephemeral database is created. The ephemeral database might
48969 ** be exclusively in memory, or it might use a disk-based memory cache.
48970 ** Either way, the ephemeral database will be automatically deleted
48971 ** when sqlite3BtreeClose() is called.
48973 ** If zFilename is ":memory:" then an in-memory database is created
48974 ** that is automatically destroyed when it is closed.
48976 ** The "flags" parameter is a bitmask that might contain bits
48977 ** BTREE_OMIT_JOURNAL and/or BTREE_NO_READLOCK. The BTREE_NO_READLOCK
48978 ** bit is also set if the SQLITE_NoReadlock flags is set in db->flags.
48979 ** These flags are passed through into sqlite3PagerOpen() and must
48980 ** be the same values as PAGER_OMIT_JOURNAL and PAGER_NO_READLOCK.
48982 ** If the database is already opened in the same database connection
48983 ** and we are in shared cache mode, then the open will fail with an
48984 ** SQLITE_CONSTRAINT error. We cannot allow two or more BtShared
48985 ** objects in the same database connection since doing so will lead
48986 ** to problems with locking.
48988 SQLITE_PRIVATE int sqlite3BtreeOpen(
48989 const char *zFilename, /* Name of the file containing the BTree database */
48990 sqlite3 *db, /* Associated database handle */
48991 Btree **ppBtree, /* Pointer to new Btree object written here */
48992 int flags, /* Options */
48993 int vfsFlags /* Flags passed through to sqlite3_vfs.xOpen() */
48995 sqlite3_vfs *pVfs; /* The VFS to use for this btree */
48996 BtShared *pBt = 0; /* Shared part of btree structure */
48997 Btree *p; /* Handle to return */
48998 sqlite3_mutex *mutexOpen = 0; /* Prevents a race condition. Ticket #3537 */
48999 int rc = SQLITE_OK; /* Result code from this function */
49000 u8 nReserve; /* Byte of unused space on each page */
49001 unsigned char zDbHeader[100]; /* Database header content */
49003 /* True if opening an ephemeral, temporary database */
49004 const int isTempDb = zFilename==0 || zFilename[0]==0;
49006 /* Set the variable isMemdb to true for an in-memory database, or
49007 ** false for a file-based database.
49009 #ifdef SQLITE_OMIT_MEMORYDB
49010 const int isMemdb = 0;
49011 #else
49012 const int isMemdb = (zFilename && strcmp(zFilename, ":memory:")==0)
49013 || (isTempDb && sqlite3TempInMemory(db));
49014 #endif
49016 assert( db!=0 );
49017 assert( sqlite3_mutex_held(db->mutex) );
49018 assert( (flags&0xff)==flags ); /* flags fit in 8 bits */
49020 /* Only a BTREE_SINGLE database can be BTREE_UNORDERED */
49021 assert( (flags & BTREE_UNORDERED)==0 || (flags & BTREE_SINGLE)!=0 );
49023 /* A BTREE_SINGLE database is always a temporary and/or ephemeral */
49024 assert( (flags & BTREE_SINGLE)==0 || isTempDb );
49026 if( db->flags & SQLITE_NoReadlock ){
49027 flags |= BTREE_NO_READLOCK;
49029 if( isMemdb ){
49030 flags |= BTREE_MEMORY;
49032 if( (vfsFlags & SQLITE_OPEN_MAIN_DB)!=0 && (isMemdb || isTempDb) ){
49033 vfsFlags = (vfsFlags & ~SQLITE_OPEN_MAIN_DB) | SQLITE_OPEN_TEMP_DB;
49035 pVfs = db->pVfs;
49036 p = sqlite3MallocZero(sizeof(Btree));
49037 if( !p ){
49038 return SQLITE_NOMEM;
49040 p->inTrans = TRANS_NONE;
49041 p->db = db;
49042 #ifndef SQLITE_OMIT_SHARED_CACHE
49043 p->lock.pBtree = p;
49044 p->lock.iTable = 1;
49045 #endif
49047 #if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
49049 ** If this Btree is a candidate for shared cache, try to find an
49050 ** existing BtShared object that we can share with
49052 if( isMemdb==0 && isTempDb==0 ){
49053 if( vfsFlags & SQLITE_OPEN_SHAREDCACHE ){
49054 int nFullPathname = pVfs->mxPathname+1;
49055 char *zFullPathname = sqlite3Malloc(nFullPathname);
49056 sqlite3_mutex *mutexShared;
49057 p->sharable = 1;
49058 if( !zFullPathname ){
49059 sqlite3_free(p);
49060 return SQLITE_NOMEM;
49062 sqlite3OsFullPathname(pVfs, zFilename, nFullPathname, zFullPathname);
49063 mutexOpen = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_OPEN);
49064 sqlite3_mutex_enter(mutexOpen);
49065 mutexShared = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
49066 sqlite3_mutex_enter(mutexShared);
49067 for(pBt=GLOBAL(BtShared*,sqlite3SharedCacheList); pBt; pBt=pBt->pNext){
49068 assert( pBt->nRef>0 );
49069 if( 0==strcmp(zFullPathname, sqlite3PagerFilename(pBt->pPager))
49070 && sqlite3PagerVfs(pBt->pPager)==pVfs ){
49071 int iDb;
49072 for(iDb=db->nDb-1; iDb>=0; iDb--){
49073 Btree *pExisting = db->aDb[iDb].pBt;
49074 if( pExisting && pExisting->pBt==pBt ){
49075 sqlite3_mutex_leave(mutexShared);
49076 sqlite3_mutex_leave(mutexOpen);
49077 sqlite3_free(zFullPathname);
49078 sqlite3_free(p);
49079 return SQLITE_CONSTRAINT;
49082 p->pBt = pBt;
49083 pBt->nRef++;
49084 break;
49087 sqlite3_mutex_leave(mutexShared);
49088 sqlite3_free(zFullPathname);
49090 #ifdef SQLITE_DEBUG
49091 else{
49092 /* In debug mode, we mark all persistent databases as sharable
49093 ** even when they are not. This exercises the locking code and
49094 ** gives more opportunity for asserts(sqlite3_mutex_held())
49095 ** statements to find locking problems.
49097 p->sharable = 1;
49099 #endif
49101 #endif
49102 if( pBt==0 ){
49104 ** The following asserts make sure that structures used by the btree are
49105 ** the right size. This is to guard against size changes that result
49106 ** when compiling on a different architecture.
49108 assert( sizeof(i64)==8 || sizeof(i64)==4 );
49109 assert( sizeof(u64)==8 || sizeof(u64)==4 );
49110 assert( sizeof(u32)==4 );
49111 assert( sizeof(u16)==2 );
49112 assert( sizeof(Pgno)==4 );
49114 pBt = sqlite3MallocZero( sizeof(*pBt) );
49115 if( pBt==0 ){
49116 rc = SQLITE_NOMEM;
49117 goto btree_open_out;
49119 rc = sqlite3PagerOpen(pVfs, &pBt->pPager, zFilename,
49120 EXTRA_SIZE, flags, vfsFlags, pageReinit);
49121 if( rc==SQLITE_OK ){
49122 rc = sqlite3PagerReadFileheader(pBt->pPager,sizeof(zDbHeader),zDbHeader);
49124 if( rc!=SQLITE_OK ){
49125 goto btree_open_out;
49127 pBt->openFlags = (u8)flags;
49128 pBt->db = db;
49129 sqlite3PagerSetBusyhandler(pBt->pPager, btreeInvokeBusyHandler, pBt);
49130 p->pBt = pBt;
49132 pBt->pCursor = 0;
49133 pBt->pPage1 = 0;
49134 pBt->readOnly = sqlite3PagerIsreadonly(pBt->pPager);
49135 #ifdef SQLITE_SECURE_DELETE
49136 pBt->secureDelete = 1;
49137 #endif
49138 pBt->pageSize = (zDbHeader[16]<<8) | (zDbHeader[17]<<16);
49139 if( pBt->pageSize<512 || pBt->pageSize>SQLITE_MAX_PAGE_SIZE
49140 || ((pBt->pageSize-1)&pBt->pageSize)!=0 ){
49141 pBt->pageSize = 0;
49142 #ifndef SQLITE_OMIT_AUTOVACUUM
49143 /* If the magic name ":memory:" will create an in-memory database, then
49144 ** leave the autoVacuum mode at 0 (do not auto-vacuum), even if
49145 ** SQLITE_DEFAULT_AUTOVACUUM is true. On the other hand, if
49146 ** SQLITE_OMIT_MEMORYDB has been defined, then ":memory:" is just a
49147 ** regular file-name. In this case the auto-vacuum applies as per normal.
49149 if( zFilename && !isMemdb ){
49150 pBt->autoVacuum = (SQLITE_DEFAULT_AUTOVACUUM ? 1 : 0);
49151 pBt->incrVacuum = (SQLITE_DEFAULT_AUTOVACUUM==2 ? 1 : 0);
49153 #endif
49154 nReserve = 0;
49155 }else{
49156 nReserve = zDbHeader[20];
49157 pBt->pageSizeFixed = 1;
49158 #ifndef SQLITE_OMIT_AUTOVACUUM
49159 pBt->autoVacuum = (get4byte(&zDbHeader[36 + 4*4])?1:0);
49160 pBt->incrVacuum = (get4byte(&zDbHeader[36 + 7*4])?1:0);
49161 #endif
49163 rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize, nReserve);
49164 if( rc ) goto btree_open_out;
49165 pBt->usableSize = pBt->pageSize - nReserve;
49166 assert( (pBt->pageSize & 7)==0 ); /* 8-byte alignment of pageSize */
49168 #if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
49169 /* Add the new BtShared object to the linked list sharable BtShareds.
49171 if( p->sharable ){
49172 sqlite3_mutex *mutexShared;
49173 pBt->nRef = 1;
49174 mutexShared = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
49175 if( SQLITE_THREADSAFE && sqlite3GlobalConfig.bCoreMutex ){
49176 pBt->mutex = sqlite3MutexAlloc(SQLITE_MUTEX_FAST);
49177 if( pBt->mutex==0 ){
49178 rc = SQLITE_NOMEM;
49179 db->mallocFailed = 0;
49180 goto btree_open_out;
49183 sqlite3_mutex_enter(mutexShared);
49184 pBt->pNext = GLOBAL(BtShared*,sqlite3SharedCacheList);
49185 GLOBAL(BtShared*,sqlite3SharedCacheList) = pBt;
49186 sqlite3_mutex_leave(mutexShared);
49188 #endif
49191 #if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
49192 /* If the new Btree uses a sharable pBtShared, then link the new
49193 ** Btree into the list of all sharable Btrees for the same connection.
49194 ** The list is kept in ascending order by pBt address.
49196 if( p->sharable ){
49197 int i;
49198 Btree *pSib;
49199 for(i=0; i<db->nDb; i++){
49200 if( (pSib = db->aDb[i].pBt)!=0 && pSib->sharable ){
49201 while( pSib->pPrev ){ pSib = pSib->pPrev; }
49202 if( p->pBt<pSib->pBt ){
49203 p->pNext = pSib;
49204 p->pPrev = 0;
49205 pSib->pPrev = p;
49206 }else{
49207 while( pSib->pNext && pSib->pNext->pBt<p->pBt ){
49208 pSib = pSib->pNext;
49210 p->pNext = pSib->pNext;
49211 p->pPrev = pSib;
49212 if( p->pNext ){
49213 p->pNext->pPrev = p;
49215 pSib->pNext = p;
49217 break;
49221 #endif
49222 *ppBtree = p;
49224 btree_open_out:
49225 if( rc!=SQLITE_OK ){
49226 if( pBt && pBt->pPager ){
49227 sqlite3PagerClose(pBt->pPager);
49229 sqlite3_free(pBt);
49230 sqlite3_free(p);
49231 *ppBtree = 0;
49232 }else{
49233 /* If the B-Tree was successfully opened, set the pager-cache size to the
49234 ** default value. Except, when opening on an existing shared pager-cache,
49235 ** do not change the pager-cache size.
49237 if( sqlite3BtreeSchema(p, 0, 0)==0 ){
49238 sqlite3PagerSetCachesize(p->pBt->pPager, SQLITE_DEFAULT_CACHE_SIZE);
49241 if( mutexOpen ){
49242 assert( sqlite3_mutex_held(mutexOpen) );
49243 sqlite3_mutex_leave(mutexOpen);
49245 return rc;
49249 ** Decrement the BtShared.nRef counter. When it reaches zero,
49250 ** remove the BtShared structure from the sharing list. Return
49251 ** true if the BtShared.nRef counter reaches zero and return
49252 ** false if it is still positive.
49254 static int removeFromSharingList(BtShared *pBt){
49255 #ifndef SQLITE_OMIT_SHARED_CACHE
49256 sqlite3_mutex *pMaster;
49257 BtShared *pList;
49258 int removed = 0;
49260 assert( sqlite3_mutex_notheld(pBt->mutex) );
49261 pMaster = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
49262 sqlite3_mutex_enter(pMaster);
49263 pBt->nRef--;
49264 if( pBt->nRef<=0 ){
49265 if( GLOBAL(BtShared*,sqlite3SharedCacheList)==pBt ){
49266 GLOBAL(BtShared*,sqlite3SharedCacheList) = pBt->pNext;
49267 }else{
49268 pList = GLOBAL(BtShared*,sqlite3SharedCacheList);
49269 while( ALWAYS(pList) && pList->pNext!=pBt ){
49270 pList=pList->pNext;
49272 if( ALWAYS(pList) ){
49273 pList->pNext = pBt->pNext;
49276 if( SQLITE_THREADSAFE ){
49277 sqlite3_mutex_free(pBt->mutex);
49279 removed = 1;
49281 sqlite3_mutex_leave(pMaster);
49282 return removed;
49283 #else
49284 return 1;
49285 #endif
49289 ** Make sure pBt->pTmpSpace points to an allocation of
49290 ** MX_CELL_SIZE(pBt) bytes.
49292 static void allocateTempSpace(BtShared *pBt){
49293 if( !pBt->pTmpSpace ){
49294 pBt->pTmpSpace = sqlite3PageMalloc( pBt->pageSize );
49299 ** Free the pBt->pTmpSpace allocation
49301 static void freeTempSpace(BtShared *pBt){
49302 sqlite3PageFree( pBt->pTmpSpace);
49303 pBt->pTmpSpace = 0;
49307 ** Close an open database and invalidate all cursors.
49309 SQLITE_PRIVATE int sqlite3BtreeClose(Btree *p){
49310 BtShared *pBt = p->pBt;
49311 BtCursor *pCur;
49313 /* Close all cursors opened via this handle. */
49314 assert( sqlite3_mutex_held(p->db->mutex) );
49315 sqlite3BtreeEnter(p);
49316 pCur = pBt->pCursor;
49317 while( pCur ){
49318 BtCursor *pTmp = pCur;
49319 pCur = pCur->pNext;
49320 if( pTmp->pBtree==p ){
49321 sqlite3BtreeCloseCursor(pTmp);
49325 /* Rollback any active transaction and free the handle structure.
49326 ** The call to sqlite3BtreeRollback() drops any table-locks held by
49327 ** this handle.
49329 sqlite3BtreeRollback(p);
49330 sqlite3BtreeLeave(p);
49332 /* If there are still other outstanding references to the shared-btree
49333 ** structure, return now. The remainder of this procedure cleans
49334 ** up the shared-btree.
49336 assert( p->wantToLock==0 && p->locked==0 );
49337 if( !p->sharable || removeFromSharingList(pBt) ){
49338 /* The pBt is no longer on the sharing list, so we can access
49339 ** it without having to hold the mutex.
49341 ** Clean out and delete the BtShared object.
49343 assert( !pBt->pCursor );
49344 sqlite3PagerClose(pBt->pPager);
49345 if( pBt->xFreeSchema && pBt->pSchema ){
49346 pBt->xFreeSchema(pBt->pSchema);
49348 sqlite3DbFree(0, pBt->pSchema);
49349 freeTempSpace(pBt);
49350 sqlite3_free(pBt);
49353 #ifndef SQLITE_OMIT_SHARED_CACHE
49354 assert( p->wantToLock==0 );
49355 assert( p->locked==0 );
49356 if( p->pPrev ) p->pPrev->pNext = p->pNext;
49357 if( p->pNext ) p->pNext->pPrev = p->pPrev;
49358 #endif
49360 sqlite3_free(p);
49361 return SQLITE_OK;
49365 ** Change the limit on the number of pages allowed in the cache.
49367 ** The maximum number of cache pages is set to the absolute
49368 ** value of mxPage. If mxPage is negative, the pager will
49369 ** operate asynchronously - it will not stop to do fsync()s
49370 ** to insure data is written to the disk surface before
49371 ** continuing. Transactions still work if synchronous is off,
49372 ** and the database cannot be corrupted if this program
49373 ** crashes. But if the operating system crashes or there is
49374 ** an abrupt power failure when synchronous is off, the database
49375 ** could be left in an inconsistent and unrecoverable state.
49376 ** Synchronous is on by default so database corruption is not
49377 ** normally a worry.
49379 SQLITE_PRIVATE int sqlite3BtreeSetCacheSize(Btree *p, int mxPage){
49380 BtShared *pBt = p->pBt;
49381 assert( sqlite3_mutex_held(p->db->mutex) );
49382 sqlite3BtreeEnter(p);
49383 sqlite3PagerSetCachesize(pBt->pPager, mxPage);
49384 sqlite3BtreeLeave(p);
49385 return SQLITE_OK;
49389 ** Change the way data is synced to disk in order to increase or decrease
49390 ** how well the database resists damage due to OS crashes and power
49391 ** failures. Level 1 is the same as asynchronous (no syncs() occur and
49392 ** there is a high probability of damage) Level 2 is the default. There
49393 ** is a very low but non-zero probability of damage. Level 3 reduces the
49394 ** probability of damage to near zero but with a write performance reduction.
49396 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
49397 SQLITE_PRIVATE int sqlite3BtreeSetSafetyLevel(
49398 Btree *p, /* The btree to set the safety level on */
49399 int level, /* PRAGMA synchronous. 1=OFF, 2=NORMAL, 3=FULL */
49400 int fullSync, /* PRAGMA fullfsync. */
49401 int ckptFullSync /* PRAGMA checkpoint_fullfync */
49403 BtShared *pBt = p->pBt;
49404 assert( sqlite3_mutex_held(p->db->mutex) );
49405 assert( level>=1 && level<=3 );
49406 sqlite3BtreeEnter(p);
49407 sqlite3PagerSetSafetyLevel(pBt->pPager, level, fullSync, ckptFullSync);
49408 sqlite3BtreeLeave(p);
49409 return SQLITE_OK;
49411 #endif
49414 ** Return TRUE if the given btree is set to safety level 1. In other
49415 ** words, return TRUE if no sync() occurs on the disk files.
49417 SQLITE_PRIVATE int sqlite3BtreeSyncDisabled(Btree *p){
49418 BtShared *pBt = p->pBt;
49419 int rc;
49420 assert( sqlite3_mutex_held(p->db->mutex) );
49421 sqlite3BtreeEnter(p);
49422 assert( pBt && pBt->pPager );
49423 rc = sqlite3PagerNosync(pBt->pPager);
49424 sqlite3BtreeLeave(p);
49425 return rc;
49429 ** Change the default pages size and the number of reserved bytes per page.
49430 ** Or, if the page size has already been fixed, return SQLITE_READONLY
49431 ** without changing anything.
49433 ** The page size must be a power of 2 between 512 and 65536. If the page
49434 ** size supplied does not meet this constraint then the page size is not
49435 ** changed.
49437 ** Page sizes are constrained to be a power of two so that the region
49438 ** of the database file used for locking (beginning at PENDING_BYTE,
49439 ** the first byte past the 1GB boundary, 0x40000000) needs to occur
49440 ** at the beginning of a page.
49442 ** If parameter nReserve is less than zero, then the number of reserved
49443 ** bytes per page is left unchanged.
49445 ** If the iFix!=0 then the pageSizeFixed flag is set so that the page size
49446 ** and autovacuum mode can no longer be changed.
49448 SQLITE_PRIVATE int sqlite3BtreeSetPageSize(Btree *p, int pageSize, int nReserve, int iFix){
49449 int rc = SQLITE_OK;
49450 BtShared *pBt = p->pBt;
49451 assert( nReserve>=-1 && nReserve<=255 );
49452 sqlite3BtreeEnter(p);
49453 if( pBt->pageSizeFixed ){
49454 sqlite3BtreeLeave(p);
49455 return SQLITE_READONLY;
49457 if( nReserve<0 ){
49458 nReserve = pBt->pageSize - pBt->usableSize;
49460 assert( nReserve>=0 && nReserve<=255 );
49461 if( pageSize>=512 && pageSize<=SQLITE_MAX_PAGE_SIZE &&
49462 ((pageSize-1)&pageSize)==0 ){
49463 assert( (pageSize & 7)==0 );
49464 assert( !pBt->pPage1 && !pBt->pCursor );
49465 pBt->pageSize = (u32)pageSize;
49466 freeTempSpace(pBt);
49468 rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize, nReserve);
49469 pBt->usableSize = pBt->pageSize - (u16)nReserve;
49470 if( iFix ) pBt->pageSizeFixed = 1;
49471 sqlite3BtreeLeave(p);
49472 return rc;
49476 ** Return the currently defined page size
49478 SQLITE_PRIVATE int sqlite3BtreeGetPageSize(Btree *p){
49479 return p->pBt->pageSize;
49482 #if !defined(SQLITE_OMIT_PAGER_PRAGMAS) || !defined(SQLITE_OMIT_VACUUM)
49484 ** Return the number of bytes of space at the end of every page that
49485 ** are intentually left unused. This is the "reserved" space that is
49486 ** sometimes used by extensions.
49488 SQLITE_PRIVATE int sqlite3BtreeGetReserve(Btree *p){
49489 int n;
49490 sqlite3BtreeEnter(p);
49491 n = p->pBt->pageSize - p->pBt->usableSize;
49492 sqlite3BtreeLeave(p);
49493 return n;
49497 ** Set the maximum page count for a database if mxPage is positive.
49498 ** No changes are made if mxPage is 0 or negative.
49499 ** Regardless of the value of mxPage, return the maximum page count.
49501 SQLITE_PRIVATE int sqlite3BtreeMaxPageCount(Btree *p, int mxPage){
49502 int n;
49503 sqlite3BtreeEnter(p);
49504 n = sqlite3PagerMaxPageCount(p->pBt->pPager, mxPage);
49505 sqlite3BtreeLeave(p);
49506 return n;
49510 ** Set the secureDelete flag if newFlag is 0 or 1. If newFlag is -1,
49511 ** then make no changes. Always return the value of the secureDelete
49512 ** setting after the change.
49514 SQLITE_PRIVATE int sqlite3BtreeSecureDelete(Btree *p, int newFlag){
49515 int b;
49516 if( p==0 ) return 0;
49517 sqlite3BtreeEnter(p);
49518 if( newFlag>=0 ){
49519 p->pBt->secureDelete = (newFlag!=0) ? 1 : 0;
49521 b = p->pBt->secureDelete;
49522 sqlite3BtreeLeave(p);
49523 return b;
49525 #endif /* !defined(SQLITE_OMIT_PAGER_PRAGMAS) || !defined(SQLITE_OMIT_VACUUM) */
49528 ** Change the 'auto-vacuum' property of the database. If the 'autoVacuum'
49529 ** parameter is non-zero, then auto-vacuum mode is enabled. If zero, it
49530 ** is disabled. The default value for the auto-vacuum property is
49531 ** determined by the SQLITE_DEFAULT_AUTOVACUUM macro.
49533 SQLITE_PRIVATE int sqlite3BtreeSetAutoVacuum(Btree *p, int autoVacuum){
49534 #ifdef SQLITE_OMIT_AUTOVACUUM
49535 return SQLITE_READONLY;
49536 #else
49537 BtShared *pBt = p->pBt;
49538 int rc = SQLITE_OK;
49539 u8 av = (u8)autoVacuum;
49541 sqlite3BtreeEnter(p);
49542 if( pBt->pageSizeFixed && (av ?1:0)!=pBt->autoVacuum ){
49543 rc = SQLITE_READONLY;
49544 }else{
49545 pBt->autoVacuum = av ?1:0;
49546 pBt->incrVacuum = av==2 ?1:0;
49548 sqlite3BtreeLeave(p);
49549 return rc;
49550 #endif
49554 ** Return the value of the 'auto-vacuum' property. If auto-vacuum is
49555 ** enabled 1 is returned. Otherwise 0.
49557 SQLITE_PRIVATE int sqlite3BtreeGetAutoVacuum(Btree *p){
49558 #ifdef SQLITE_OMIT_AUTOVACUUM
49559 return BTREE_AUTOVACUUM_NONE;
49560 #else
49561 int rc;
49562 sqlite3BtreeEnter(p);
49563 rc = (
49564 (!p->pBt->autoVacuum)?BTREE_AUTOVACUUM_NONE:
49565 (!p->pBt->incrVacuum)?BTREE_AUTOVACUUM_FULL:
49566 BTREE_AUTOVACUUM_INCR
49568 sqlite3BtreeLeave(p);
49569 return rc;
49570 #endif
49575 ** Get a reference to pPage1 of the database file. This will
49576 ** also acquire a readlock on that file.
49578 ** SQLITE_OK is returned on success. If the file is not a
49579 ** well-formed database file, then SQLITE_CORRUPT is returned.
49580 ** SQLITE_BUSY is returned if the database is locked. SQLITE_NOMEM
49581 ** is returned if we run out of memory.
49583 static int lockBtree(BtShared *pBt){
49584 int rc; /* Result code from subfunctions */
49585 MemPage *pPage1; /* Page 1 of the database file */
49586 int nPage; /* Number of pages in the database */
49587 int nPageFile = 0; /* Number of pages in the database file */
49588 int nPageHeader; /* Number of pages in the database according to hdr */
49590 assert( sqlite3_mutex_held(pBt->mutex) );
49591 assert( pBt->pPage1==0 );
49592 rc = sqlite3PagerSharedLock(pBt->pPager);
49593 if( rc!=SQLITE_OK ) return rc;
49594 rc = btreeGetPage(pBt, 1, &pPage1, 0);
49595 if( rc!=SQLITE_OK ) return rc;
49597 /* Do some checking to help insure the file we opened really is
49598 ** a valid database file.
49600 nPage = nPageHeader = get4byte(28+(u8*)pPage1->aData);
49601 sqlite3PagerPagecount(pBt->pPager, &nPageFile);
49602 if( nPage==0 || memcmp(24+(u8*)pPage1->aData, 92+(u8*)pPage1->aData,4)!=0 ){
49603 nPage = nPageFile;
49605 if( nPage>0 ){
49606 u32 pageSize;
49607 u32 usableSize;
49608 u8 *page1 = pPage1->aData;
49609 rc = SQLITE_NOTADB;
49610 if( memcmp(page1, zMagicHeader, 16)!=0 ){
49611 goto page1_init_failed;
49614 #ifdef SQLITE_OMIT_WAL
49615 if( page1[18]>1 ){
49616 pBt->readOnly = 1;
49618 if( page1[19]>1 ){
49619 goto page1_init_failed;
49621 #else
49622 if( page1[18]>2 ){
49623 pBt->readOnly = 1;
49625 if( page1[19]>2 ){
49626 goto page1_init_failed;
49629 /* If the write version is set to 2, this database should be accessed
49630 ** in WAL mode. If the log is not already open, open it now. Then
49631 ** return SQLITE_OK and return without populating BtShared.pPage1.
49632 ** The caller detects this and calls this function again. This is
49633 ** required as the version of page 1 currently in the page1 buffer
49634 ** may not be the latest version - there may be a newer one in the log
49635 ** file.
49637 if( page1[19]==2 && pBt->doNotUseWAL==0 ){
49638 int isOpen = 0;
49639 rc = sqlite3PagerOpenWal(pBt->pPager, &isOpen);
49640 if( rc!=SQLITE_OK ){
49641 goto page1_init_failed;
49642 }else if( isOpen==0 ){
49643 releasePage(pPage1);
49644 return SQLITE_OK;
49646 rc = SQLITE_NOTADB;
49648 #endif
49650 /* The maximum embedded fraction must be exactly 25%. And the minimum
49651 ** embedded fraction must be 12.5% for both leaf-data and non-leaf-data.
49652 ** The original design allowed these amounts to vary, but as of
49653 ** version 3.6.0, we require them to be fixed.
49655 if( memcmp(&page1[21], "\100\040\040",3)!=0 ){
49656 goto page1_init_failed;
49658 pageSize = (page1[16]<<8) | (page1[17]<<16);
49659 if( ((pageSize-1)&pageSize)!=0
49660 || pageSize>SQLITE_MAX_PAGE_SIZE
49661 || pageSize<=256
49663 goto page1_init_failed;
49665 assert( (pageSize & 7)==0 );
49666 usableSize = pageSize - page1[20];
49667 if( (u32)pageSize!=pBt->pageSize ){
49668 /* After reading the first page of the database assuming a page size
49669 ** of BtShared.pageSize, we have discovered that the page-size is
49670 ** actually pageSize. Unlock the database, leave pBt->pPage1 at
49671 ** zero and return SQLITE_OK. The caller will call this function
49672 ** again with the correct page-size.
49674 releasePage(pPage1);
49675 pBt->usableSize = usableSize;
49676 pBt->pageSize = pageSize;
49677 freeTempSpace(pBt);
49678 rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize,
49679 pageSize-usableSize);
49680 return rc;
49682 if( (pBt->db->flags & SQLITE_RecoveryMode)==0 && nPage>nPageFile ){
49683 rc = SQLITE_CORRUPT_BKPT;
49684 goto page1_init_failed;
49686 if( usableSize<480 ){
49687 goto page1_init_failed;
49689 pBt->pageSize = pageSize;
49690 pBt->usableSize = usableSize;
49691 #ifndef SQLITE_OMIT_AUTOVACUUM
49692 pBt->autoVacuum = (get4byte(&page1[36 + 4*4])?1:0);
49693 pBt->incrVacuum = (get4byte(&page1[36 + 7*4])?1:0);
49694 #endif
49697 /* maxLocal is the maximum amount of payload to store locally for
49698 ** a cell. Make sure it is small enough so that at least minFanout
49699 ** cells can will fit on one page. We assume a 10-byte page header.
49700 ** Besides the payload, the cell must store:
49701 ** 2-byte pointer to the cell
49702 ** 4-byte child pointer
49703 ** 9-byte nKey value
49704 ** 4-byte nData value
49705 ** 4-byte overflow page pointer
49706 ** So a cell consists of a 2-byte pointer, a header which is as much as
49707 ** 17 bytes long, 0 to N bytes of payload, and an optional 4 byte overflow
49708 ** page pointer.
49710 pBt->maxLocal = (u16)((pBt->usableSize-12)*64/255 - 23);
49711 pBt->minLocal = (u16)((pBt->usableSize-12)*32/255 - 23);
49712 pBt->maxLeaf = (u16)(pBt->usableSize - 35);
49713 pBt->minLeaf = (u16)((pBt->usableSize-12)*32/255 - 23);
49714 assert( pBt->maxLeaf + 23 <= MX_CELL_SIZE(pBt) );
49715 pBt->pPage1 = pPage1;
49716 pBt->nPage = nPage;
49717 return SQLITE_OK;
49719 page1_init_failed:
49720 releasePage(pPage1);
49721 pBt->pPage1 = 0;
49722 return rc;
49726 ** If there are no outstanding cursors and we are not in the middle
49727 ** of a transaction but there is a read lock on the database, then
49728 ** this routine unrefs the first page of the database file which
49729 ** has the effect of releasing the read lock.
49731 ** If there is a transaction in progress, this routine is a no-op.
49733 static void unlockBtreeIfUnused(BtShared *pBt){
49734 assert( sqlite3_mutex_held(pBt->mutex) );
49735 assert( pBt->pCursor==0 || pBt->inTransaction>TRANS_NONE );
49736 if( pBt->inTransaction==TRANS_NONE && pBt->pPage1!=0 ){
49737 assert( pBt->pPage1->aData );
49738 assert( sqlite3PagerRefcount(pBt->pPager)==1 );
49739 assert( pBt->pPage1->aData );
49740 releasePage(pBt->pPage1);
49741 pBt->pPage1 = 0;
49746 ** If pBt points to an empty file then convert that empty file
49747 ** into a new empty database by initializing the first page of
49748 ** the database.
49750 static int newDatabase(BtShared *pBt){
49751 MemPage *pP1;
49752 unsigned char *data;
49753 int rc;
49755 assert( sqlite3_mutex_held(pBt->mutex) );
49756 if( pBt->nPage>0 ){
49757 return SQLITE_OK;
49759 pP1 = pBt->pPage1;
49760 assert( pP1!=0 );
49761 data = pP1->aData;
49762 rc = sqlite3PagerWrite(pP1->pDbPage);
49763 if( rc ) return rc;
49764 memcpy(data, zMagicHeader, sizeof(zMagicHeader));
49765 assert( sizeof(zMagicHeader)==16 );
49766 data[16] = (u8)((pBt->pageSize>>8)&0xff);
49767 data[17] = (u8)((pBt->pageSize>>16)&0xff);
49768 data[18] = 1;
49769 data[19] = 1;
49770 assert( pBt->usableSize<=pBt->pageSize && pBt->usableSize+255>=pBt->pageSize);
49771 data[20] = (u8)(pBt->pageSize - pBt->usableSize);
49772 data[21] = 64;
49773 data[22] = 32;
49774 data[23] = 32;
49775 memset(&data[24], 0, 100-24);
49776 zeroPage(pP1, PTF_INTKEY|PTF_LEAF|PTF_LEAFDATA );
49777 pBt->pageSizeFixed = 1;
49778 #ifndef SQLITE_OMIT_AUTOVACUUM
49779 assert( pBt->autoVacuum==1 || pBt->autoVacuum==0 );
49780 assert( pBt->incrVacuum==1 || pBt->incrVacuum==0 );
49781 put4byte(&data[36 + 4*4], pBt->autoVacuum);
49782 put4byte(&data[36 + 7*4], pBt->incrVacuum);
49783 #endif
49784 pBt->nPage = 1;
49785 data[31] = 1;
49786 return SQLITE_OK;
49790 ** Attempt to start a new transaction. A write-transaction
49791 ** is started if the second argument is nonzero, otherwise a read-
49792 ** transaction. If the second argument is 2 or more and exclusive
49793 ** transaction is started, meaning that no other process is allowed
49794 ** to access the database. A preexisting transaction may not be
49795 ** upgraded to exclusive by calling this routine a second time - the
49796 ** exclusivity flag only works for a new transaction.
49798 ** A write-transaction must be started before attempting any
49799 ** changes to the database. None of the following routines
49800 ** will work unless a transaction is started first:
49802 ** sqlite3BtreeCreateTable()
49803 ** sqlite3BtreeCreateIndex()
49804 ** sqlite3BtreeClearTable()
49805 ** sqlite3BtreeDropTable()
49806 ** sqlite3BtreeInsert()
49807 ** sqlite3BtreeDelete()
49808 ** sqlite3BtreeUpdateMeta()
49810 ** If an initial attempt to acquire the lock fails because of lock contention
49811 ** and the database was previously unlocked, then invoke the busy handler
49812 ** if there is one. But if there was previously a read-lock, do not
49813 ** invoke the busy handler - just return SQLITE_BUSY. SQLITE_BUSY is
49814 ** returned when there is already a read-lock in order to avoid a deadlock.
49816 ** Suppose there are two processes A and B. A has a read lock and B has
49817 ** a reserved lock. B tries to promote to exclusive but is blocked because
49818 ** of A's read lock. A tries to promote to reserved but is blocked by B.
49819 ** One or the other of the two processes must give way or there can be
49820 ** no progress. By returning SQLITE_BUSY and not invoking the busy callback
49821 ** when A already has a read lock, we encourage A to give up and let B
49822 ** proceed.
49824 SQLITE_PRIVATE int sqlite3BtreeBeginTrans(Btree *p, int wrflag){
49825 sqlite3 *pBlock = 0;
49826 BtShared *pBt = p->pBt;
49827 int rc = SQLITE_OK;
49829 sqlite3BtreeEnter(p);
49830 btreeIntegrity(p);
49832 /* If the btree is already in a write-transaction, or it
49833 ** is already in a read-transaction and a read-transaction
49834 ** is requested, this is a no-op.
49836 if( p->inTrans==TRANS_WRITE || (p->inTrans==TRANS_READ && !wrflag) ){
49837 goto trans_begun;
49840 /* Write transactions are not possible on a read-only database */
49841 if( pBt->readOnly && wrflag ){
49842 rc = SQLITE_READONLY;
49843 goto trans_begun;
49846 #ifndef SQLITE_OMIT_SHARED_CACHE
49847 /* If another database handle has already opened a write transaction
49848 ** on this shared-btree structure and a second write transaction is
49849 ** requested, return SQLITE_LOCKED.
49851 if( (wrflag && pBt->inTransaction==TRANS_WRITE) || pBt->isPending ){
49852 pBlock = pBt->pWriter->db;
49853 }else if( wrflag>1 ){
49854 BtLock *pIter;
49855 for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
49856 if( pIter->pBtree!=p ){
49857 pBlock = pIter->pBtree->db;
49858 break;
49862 if( pBlock ){
49863 sqlite3ConnectionBlocked(p->db, pBlock);
49864 rc = SQLITE_LOCKED_SHAREDCACHE;
49865 goto trans_begun;
49867 #endif
49869 /* Any read-only or read-write transaction implies a read-lock on
49870 ** page 1. So if some other shared-cache client already has a write-lock
49871 ** on page 1, the transaction cannot be opened. */
49872 rc = querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK);
49873 if( SQLITE_OK!=rc ) goto trans_begun;
49875 pBt->initiallyEmpty = (u8)(pBt->nPage==0);
49876 do {
49877 /* Call lockBtree() until either pBt->pPage1 is populated or
49878 ** lockBtree() returns something other than SQLITE_OK. lockBtree()
49879 ** may return SQLITE_OK but leave pBt->pPage1 set to 0 if after
49880 ** reading page 1 it discovers that the page-size of the database
49881 ** file is not pBt->pageSize. In this case lockBtree() will update
49882 ** pBt->pageSize to the page-size of the file on disk.
49884 while( pBt->pPage1==0 && SQLITE_OK==(rc = lockBtree(pBt)) );
49886 if( rc==SQLITE_OK && wrflag ){
49887 if( pBt->readOnly ){
49888 rc = SQLITE_READONLY;
49889 }else{
49890 rc = sqlite3PagerBegin(pBt->pPager,wrflag>1,sqlite3TempInMemory(p->db));
49891 if( rc==SQLITE_OK ){
49892 rc = newDatabase(pBt);
49897 if( rc!=SQLITE_OK ){
49898 unlockBtreeIfUnused(pBt);
49900 }while( (rc&0xFF)==SQLITE_BUSY && pBt->inTransaction==TRANS_NONE &&
49901 btreeInvokeBusyHandler(pBt) );
49903 if( rc==SQLITE_OK ){
49904 if( p->inTrans==TRANS_NONE ){
49905 pBt->nTransaction++;
49906 #ifndef SQLITE_OMIT_SHARED_CACHE
49907 if( p->sharable ){
49908 assert( p->lock.pBtree==p && p->lock.iTable==1 );
49909 p->lock.eLock = READ_LOCK;
49910 p->lock.pNext = pBt->pLock;
49911 pBt->pLock = &p->lock;
49913 #endif
49915 p->inTrans = (wrflag?TRANS_WRITE:TRANS_READ);
49916 if( p->inTrans>pBt->inTransaction ){
49917 pBt->inTransaction = p->inTrans;
49919 if( wrflag ){
49920 MemPage *pPage1 = pBt->pPage1;
49921 #ifndef SQLITE_OMIT_SHARED_CACHE
49922 assert( !pBt->pWriter );
49923 pBt->pWriter = p;
49924 pBt->isExclusive = (u8)(wrflag>1);
49925 #endif
49927 /* If the db-size header field is incorrect (as it may be if an old
49928 ** client has been writing the database file), update it now. Doing
49929 ** this sooner rather than later means the database size can safely
49930 ** re-read the database size from page 1 if a savepoint or transaction
49931 ** rollback occurs within the transaction.
49933 if( pBt->nPage!=get4byte(&pPage1->aData[28]) ){
49934 rc = sqlite3PagerWrite(pPage1->pDbPage);
49935 if( rc==SQLITE_OK ){
49936 put4byte(&pPage1->aData[28], pBt->nPage);
49943 trans_begun:
49944 if( rc==SQLITE_OK && wrflag ){
49945 /* This call makes sure that the pager has the correct number of
49946 ** open savepoints. If the second parameter is greater than 0 and
49947 ** the sub-journal is not already open, then it will be opened here.
49949 rc = sqlite3PagerOpenSavepoint(pBt->pPager, p->db->nSavepoint);
49952 btreeIntegrity(p);
49953 sqlite3BtreeLeave(p);
49954 return rc;
49957 #ifndef SQLITE_OMIT_AUTOVACUUM
49960 ** Set the pointer-map entries for all children of page pPage. Also, if
49961 ** pPage contains cells that point to overflow pages, set the pointer
49962 ** map entries for the overflow pages as well.
49964 static int setChildPtrmaps(MemPage *pPage){
49965 int i; /* Counter variable */
49966 int nCell; /* Number of cells in page pPage */
49967 int rc; /* Return code */
49968 BtShared *pBt = pPage->pBt;
49969 u8 isInitOrig = pPage->isInit;
49970 Pgno pgno = pPage->pgno;
49972 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
49973 rc = btreeInitPage(pPage);
49974 if( rc!=SQLITE_OK ){
49975 goto set_child_ptrmaps_out;
49977 nCell = pPage->nCell;
49979 for(i=0; i<nCell; i++){
49980 u8 *pCell = findCell(pPage, i);
49982 ptrmapPutOvflPtr(pPage, pCell, &rc);
49984 if( !pPage->leaf ){
49985 Pgno childPgno = get4byte(pCell);
49986 ptrmapPut(pBt, childPgno, PTRMAP_BTREE, pgno, &rc);
49990 if( !pPage->leaf ){
49991 Pgno childPgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
49992 ptrmapPut(pBt, childPgno, PTRMAP_BTREE, pgno, &rc);
49995 set_child_ptrmaps_out:
49996 pPage->isInit = isInitOrig;
49997 return rc;
50001 ** Somewhere on pPage is a pointer to page iFrom. Modify this pointer so
50002 ** that it points to iTo. Parameter eType describes the type of pointer to
50003 ** be modified, as follows:
50005 ** PTRMAP_BTREE: pPage is a btree-page. The pointer points at a child
50006 ** page of pPage.
50008 ** PTRMAP_OVERFLOW1: pPage is a btree-page. The pointer points at an overflow
50009 ** page pointed to by one of the cells on pPage.
50011 ** PTRMAP_OVERFLOW2: pPage is an overflow-page. The pointer points at the next
50012 ** overflow page in the list.
50014 static int modifyPagePointer(MemPage *pPage, Pgno iFrom, Pgno iTo, u8 eType){
50015 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
50016 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
50017 if( eType==PTRMAP_OVERFLOW2 ){
50018 /* The pointer is always the first 4 bytes of the page in this case. */
50019 if( get4byte(pPage->aData)!=iFrom ){
50020 return SQLITE_CORRUPT_BKPT;
50022 put4byte(pPage->aData, iTo);
50023 }else{
50024 u8 isInitOrig = pPage->isInit;
50025 int i;
50026 int nCell;
50028 btreeInitPage(pPage);
50029 nCell = pPage->nCell;
50031 for(i=0; i<nCell; i++){
50032 u8 *pCell = findCell(pPage, i);
50033 if( eType==PTRMAP_OVERFLOW1 ){
50034 CellInfo info;
50035 btreeParseCellPtr(pPage, pCell, &info);
50036 if( info.iOverflow ){
50037 if( iFrom==get4byte(&pCell[info.iOverflow]) ){
50038 put4byte(&pCell[info.iOverflow], iTo);
50039 break;
50042 }else{
50043 if( get4byte(pCell)==iFrom ){
50044 put4byte(pCell, iTo);
50045 break;
50050 if( i==nCell ){
50051 if( eType!=PTRMAP_BTREE ||
50052 get4byte(&pPage->aData[pPage->hdrOffset+8])!=iFrom ){
50053 return SQLITE_CORRUPT_BKPT;
50055 put4byte(&pPage->aData[pPage->hdrOffset+8], iTo);
50058 pPage->isInit = isInitOrig;
50060 return SQLITE_OK;
50065 ** Move the open database page pDbPage to location iFreePage in the
50066 ** database. The pDbPage reference remains valid.
50068 ** The isCommit flag indicates that there is no need to remember that
50069 ** the journal needs to be sync()ed before database page pDbPage->pgno
50070 ** can be written to. The caller has already promised not to write to that
50071 ** page.
50073 static int relocatePage(
50074 BtShared *pBt, /* Btree */
50075 MemPage *pDbPage, /* Open page to move */
50076 u8 eType, /* Pointer map 'type' entry for pDbPage */
50077 Pgno iPtrPage, /* Pointer map 'page-no' entry for pDbPage */
50078 Pgno iFreePage, /* The location to move pDbPage to */
50079 int isCommit /* isCommit flag passed to sqlite3PagerMovepage */
50081 MemPage *pPtrPage; /* The page that contains a pointer to pDbPage */
50082 Pgno iDbPage = pDbPage->pgno;
50083 Pager *pPager = pBt->pPager;
50084 int rc;
50086 assert( eType==PTRMAP_OVERFLOW2 || eType==PTRMAP_OVERFLOW1 ||
50087 eType==PTRMAP_BTREE || eType==PTRMAP_ROOTPAGE );
50088 assert( sqlite3_mutex_held(pBt->mutex) );
50089 assert( pDbPage->pBt==pBt );
50091 /* Move page iDbPage from its current location to page number iFreePage */
50092 TRACE(("AUTOVACUUM: Moving %d to free page %d (ptr page %d type %d)\n",
50093 iDbPage, iFreePage, iPtrPage, eType));
50094 rc = sqlite3PagerMovepage(pPager, pDbPage->pDbPage, iFreePage, isCommit);
50095 if( rc!=SQLITE_OK ){
50096 return rc;
50098 pDbPage->pgno = iFreePage;
50100 /* If pDbPage was a btree-page, then it may have child pages and/or cells
50101 ** that point to overflow pages. The pointer map entries for all these
50102 ** pages need to be changed.
50104 ** If pDbPage is an overflow page, then the first 4 bytes may store a
50105 ** pointer to a subsequent overflow page. If this is the case, then
50106 ** the pointer map needs to be updated for the subsequent overflow page.
50108 if( eType==PTRMAP_BTREE || eType==PTRMAP_ROOTPAGE ){
50109 rc = setChildPtrmaps(pDbPage);
50110 if( rc!=SQLITE_OK ){
50111 return rc;
50113 }else{
50114 Pgno nextOvfl = get4byte(pDbPage->aData);
50115 if( nextOvfl!=0 ){
50116 ptrmapPut(pBt, nextOvfl, PTRMAP_OVERFLOW2, iFreePage, &rc);
50117 if( rc!=SQLITE_OK ){
50118 return rc;
50123 /* Fix the database pointer on page iPtrPage that pointed at iDbPage so
50124 ** that it points at iFreePage. Also fix the pointer map entry for
50125 ** iPtrPage.
50127 if( eType!=PTRMAP_ROOTPAGE ){
50128 rc = btreeGetPage(pBt, iPtrPage, &pPtrPage, 0);
50129 if( rc!=SQLITE_OK ){
50130 return rc;
50132 rc = sqlite3PagerWrite(pPtrPage->pDbPage);
50133 if( rc!=SQLITE_OK ){
50134 releasePage(pPtrPage);
50135 return rc;
50137 rc = modifyPagePointer(pPtrPage, iDbPage, iFreePage, eType);
50138 releasePage(pPtrPage);
50139 if( rc==SQLITE_OK ){
50140 ptrmapPut(pBt, iFreePage, eType, iPtrPage, &rc);
50143 return rc;
50146 /* Forward declaration required by incrVacuumStep(). */
50147 static int allocateBtreePage(BtShared *, MemPage **, Pgno *, Pgno, u8);
50150 ** Perform a single step of an incremental-vacuum. If successful,
50151 ** return SQLITE_OK. If there is no work to do (and therefore no
50152 ** point in calling this function again), return SQLITE_DONE.
50154 ** More specificly, this function attempts to re-organize the
50155 ** database so that the last page of the file currently in use
50156 ** is no longer in use.
50158 ** If the nFin parameter is non-zero, this function assumes
50159 ** that the caller will keep calling incrVacuumStep() until
50160 ** it returns SQLITE_DONE or an error, and that nFin is the
50161 ** number of pages the database file will contain after this
50162 ** process is complete. If nFin is zero, it is assumed that
50163 ** incrVacuumStep() will be called a finite amount of times
50164 ** which may or may not empty the freelist. A full autovacuum
50165 ** has nFin>0. A "PRAGMA incremental_vacuum" has nFin==0.
50167 static int incrVacuumStep(BtShared *pBt, Pgno nFin, Pgno iLastPg){
50168 Pgno nFreeList; /* Number of pages still on the free-list */
50169 int rc;
50171 assert( sqlite3_mutex_held(pBt->mutex) );
50172 assert( iLastPg>nFin );
50174 if( !PTRMAP_ISPAGE(pBt, iLastPg) && iLastPg!=PENDING_BYTE_PAGE(pBt) ){
50175 u8 eType;
50176 Pgno iPtrPage;
50178 nFreeList = get4byte(&pBt->pPage1->aData[36]);
50179 if( nFreeList==0 ){
50180 return SQLITE_DONE;
50183 rc = ptrmapGet(pBt, iLastPg, &eType, &iPtrPage);
50184 if( rc!=SQLITE_OK ){
50185 return rc;
50187 if( eType==PTRMAP_ROOTPAGE ){
50188 return SQLITE_CORRUPT_BKPT;
50191 if( eType==PTRMAP_FREEPAGE ){
50192 if( nFin==0 ){
50193 /* Remove the page from the files free-list. This is not required
50194 ** if nFin is non-zero. In that case, the free-list will be
50195 ** truncated to zero after this function returns, so it doesn't
50196 ** matter if it still contains some garbage entries.
50198 Pgno iFreePg;
50199 MemPage *pFreePg;
50200 rc = allocateBtreePage(pBt, &pFreePg, &iFreePg, iLastPg, 1);
50201 if( rc!=SQLITE_OK ){
50202 return rc;
50204 assert( iFreePg==iLastPg );
50205 releasePage(pFreePg);
50207 } else {
50208 Pgno iFreePg; /* Index of free page to move pLastPg to */
50209 MemPage *pLastPg;
50211 rc = btreeGetPage(pBt, iLastPg, &pLastPg, 0);
50212 if( rc!=SQLITE_OK ){
50213 return rc;
50216 /* If nFin is zero, this loop runs exactly once and page pLastPg
50217 ** is swapped with the first free page pulled off the free list.
50219 ** On the other hand, if nFin is greater than zero, then keep
50220 ** looping until a free-page located within the first nFin pages
50221 ** of the file is found.
50223 do {
50224 MemPage *pFreePg;
50225 rc = allocateBtreePage(pBt, &pFreePg, &iFreePg, 0, 0);
50226 if( rc!=SQLITE_OK ){
50227 releasePage(pLastPg);
50228 return rc;
50230 releasePage(pFreePg);
50231 }while( nFin!=0 && iFreePg>nFin );
50232 assert( iFreePg<iLastPg );
50234 rc = sqlite3PagerWrite(pLastPg->pDbPage);
50235 if( rc==SQLITE_OK ){
50236 rc = relocatePage(pBt, pLastPg, eType, iPtrPage, iFreePg, nFin!=0);
50238 releasePage(pLastPg);
50239 if( rc!=SQLITE_OK ){
50240 return rc;
50245 if( nFin==0 ){
50246 iLastPg--;
50247 while( iLastPg==PENDING_BYTE_PAGE(pBt)||PTRMAP_ISPAGE(pBt, iLastPg) ){
50248 if( PTRMAP_ISPAGE(pBt, iLastPg) ){
50249 MemPage *pPg;
50250 rc = btreeGetPage(pBt, iLastPg, &pPg, 0);
50251 if( rc!=SQLITE_OK ){
50252 return rc;
50254 rc = sqlite3PagerWrite(pPg->pDbPage);
50255 releasePage(pPg);
50256 if( rc!=SQLITE_OK ){
50257 return rc;
50260 iLastPg--;
50262 sqlite3PagerTruncateImage(pBt->pPager, iLastPg);
50263 pBt->nPage = iLastPg;
50265 return SQLITE_OK;
50269 ** A write-transaction must be opened before calling this function.
50270 ** It performs a single unit of work towards an incremental vacuum.
50272 ** If the incremental vacuum is finished after this function has run,
50273 ** SQLITE_DONE is returned. If it is not finished, but no error occurred,
50274 ** SQLITE_OK is returned. Otherwise an SQLite error code.
50276 SQLITE_PRIVATE int sqlite3BtreeIncrVacuum(Btree *p){
50277 int rc;
50278 BtShared *pBt = p->pBt;
50280 sqlite3BtreeEnter(p);
50281 assert( pBt->inTransaction==TRANS_WRITE && p->inTrans==TRANS_WRITE );
50282 if( !pBt->autoVacuum ){
50283 rc = SQLITE_DONE;
50284 }else{
50285 invalidateAllOverflowCache(pBt);
50286 rc = incrVacuumStep(pBt, 0, btreePagecount(pBt));
50287 if( rc==SQLITE_OK ){
50288 rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
50289 put4byte(&pBt->pPage1->aData[28], pBt->nPage);
50292 sqlite3BtreeLeave(p);
50293 return rc;
50297 ** This routine is called prior to sqlite3PagerCommit when a transaction
50298 ** is commited for an auto-vacuum database.
50300 ** If SQLITE_OK is returned, then *pnTrunc is set to the number of pages
50301 ** the database file should be truncated to during the commit process.
50302 ** i.e. the database has been reorganized so that only the first *pnTrunc
50303 ** pages are in use.
50305 static int autoVacuumCommit(BtShared *pBt){
50306 int rc = SQLITE_OK;
50307 Pager *pPager = pBt->pPager;
50308 VVA_ONLY( int nRef = sqlite3PagerRefcount(pPager) );
50310 assert( sqlite3_mutex_held(pBt->mutex) );
50311 invalidateAllOverflowCache(pBt);
50312 assert(pBt->autoVacuum);
50313 if( !pBt->incrVacuum ){
50314 Pgno nFin; /* Number of pages in database after autovacuuming */
50315 Pgno nFree; /* Number of pages on the freelist initially */
50316 Pgno nPtrmap; /* Number of PtrMap pages to be freed */
50317 Pgno iFree; /* The next page to be freed */
50318 int nEntry; /* Number of entries on one ptrmap page */
50319 Pgno nOrig; /* Database size before freeing */
50321 nOrig = btreePagecount(pBt);
50322 if( PTRMAP_ISPAGE(pBt, nOrig) || nOrig==PENDING_BYTE_PAGE(pBt) ){
50323 /* It is not possible to create a database for which the final page
50324 ** is either a pointer-map page or the pending-byte page. If one
50325 ** is encountered, this indicates corruption.
50327 return SQLITE_CORRUPT_BKPT;
50330 nFree = get4byte(&pBt->pPage1->aData[36]);
50331 nEntry = pBt->usableSize/5;
50332 nPtrmap = (nFree-nOrig+PTRMAP_PAGENO(pBt, nOrig)+nEntry)/nEntry;
50333 nFin = nOrig - nFree - nPtrmap;
50334 if( nOrig>PENDING_BYTE_PAGE(pBt) && nFin<PENDING_BYTE_PAGE(pBt) ){
50335 nFin--;
50337 while( PTRMAP_ISPAGE(pBt, nFin) || nFin==PENDING_BYTE_PAGE(pBt) ){
50338 nFin--;
50340 if( nFin>nOrig ) return SQLITE_CORRUPT_BKPT;
50342 for(iFree=nOrig; iFree>nFin && rc==SQLITE_OK; iFree--){
50343 rc = incrVacuumStep(pBt, nFin, iFree);
50345 if( (rc==SQLITE_DONE || rc==SQLITE_OK) && nFree>0 ){
50346 rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
50347 put4byte(&pBt->pPage1->aData[32], 0);
50348 put4byte(&pBt->pPage1->aData[36], 0);
50349 put4byte(&pBt->pPage1->aData[28], nFin);
50350 sqlite3PagerTruncateImage(pBt->pPager, nFin);
50351 pBt->nPage = nFin;
50353 if( rc!=SQLITE_OK ){
50354 sqlite3PagerRollback(pPager);
50358 assert( nRef==sqlite3PagerRefcount(pPager) );
50359 return rc;
50362 #else /* ifndef SQLITE_OMIT_AUTOVACUUM */
50363 # define setChildPtrmaps(x) SQLITE_OK
50364 #endif
50367 ** This routine does the first phase of a two-phase commit. This routine
50368 ** causes a rollback journal to be created (if it does not already exist)
50369 ** and populated with enough information so that if a power loss occurs
50370 ** the database can be restored to its original state by playing back
50371 ** the journal. Then the contents of the journal are flushed out to
50372 ** the disk. After the journal is safely on oxide, the changes to the
50373 ** database are written into the database file and flushed to oxide.
50374 ** At the end of this call, the rollback journal still exists on the
50375 ** disk and we are still holding all locks, so the transaction has not
50376 ** committed. See sqlite3BtreeCommitPhaseTwo() for the second phase of the
50377 ** commit process.
50379 ** This call is a no-op if no write-transaction is currently active on pBt.
50381 ** Otherwise, sync the database file for the btree pBt. zMaster points to
50382 ** the name of a master journal file that should be written into the
50383 ** individual journal file, or is NULL, indicating no master journal file
50384 ** (single database transaction).
50386 ** When this is called, the master journal should already have been
50387 ** created, populated with this journal pointer and synced to disk.
50389 ** Once this is routine has returned, the only thing required to commit
50390 ** the write-transaction for this database file is to delete the journal.
50392 SQLITE_PRIVATE int sqlite3BtreeCommitPhaseOne(Btree *p, const char *zMaster){
50393 int rc = SQLITE_OK;
50394 if( p->inTrans==TRANS_WRITE ){
50395 BtShared *pBt = p->pBt;
50396 sqlite3BtreeEnter(p);
50397 #ifndef SQLITE_OMIT_AUTOVACUUM
50398 if( pBt->autoVacuum ){
50399 rc = autoVacuumCommit(pBt);
50400 if( rc!=SQLITE_OK ){
50401 sqlite3BtreeLeave(p);
50402 return rc;
50405 #endif
50406 rc = sqlite3PagerCommitPhaseOne(pBt->pPager, zMaster, 0);
50407 sqlite3BtreeLeave(p);
50409 return rc;
50413 ** This function is called from both BtreeCommitPhaseTwo() and BtreeRollback()
50414 ** at the conclusion of a transaction.
50416 static void btreeEndTransaction(Btree *p){
50417 BtShared *pBt = p->pBt;
50418 assert( sqlite3BtreeHoldsMutex(p) );
50420 btreeClearHasContent(pBt);
50421 if( p->inTrans>TRANS_NONE && p->db->activeVdbeCnt>1 ){
50422 /* If there are other active statements that belong to this database
50423 ** handle, downgrade to a read-only transaction. The other statements
50424 ** may still be reading from the database. */
50425 downgradeAllSharedCacheTableLocks(p);
50426 p->inTrans = TRANS_READ;
50427 }else{
50428 /* If the handle had any kind of transaction open, decrement the
50429 ** transaction count of the shared btree. If the transaction count
50430 ** reaches 0, set the shared state to TRANS_NONE. The unlockBtreeIfUnused()
50431 ** call below will unlock the pager. */
50432 if( p->inTrans!=TRANS_NONE ){
50433 clearAllSharedCacheTableLocks(p);
50434 pBt->nTransaction--;
50435 if( 0==pBt->nTransaction ){
50436 pBt->inTransaction = TRANS_NONE;
50440 /* Set the current transaction state to TRANS_NONE and unlock the
50441 ** pager if this call closed the only read or write transaction. */
50442 p->inTrans = TRANS_NONE;
50443 unlockBtreeIfUnused(pBt);
50446 btreeIntegrity(p);
50450 ** Commit the transaction currently in progress.
50452 ** This routine implements the second phase of a 2-phase commit. The
50453 ** sqlite3BtreeCommitPhaseOne() routine does the first phase and should
50454 ** be invoked prior to calling this routine. The sqlite3BtreeCommitPhaseOne()
50455 ** routine did all the work of writing information out to disk and flushing the
50456 ** contents so that they are written onto the disk platter. All this
50457 ** routine has to do is delete or truncate or zero the header in the
50458 ** the rollback journal (which causes the transaction to commit) and
50459 ** drop locks.
50461 ** Normally, if an error occurs while the pager layer is attempting to
50462 ** finalize the underlying journal file, this function returns an error and
50463 ** the upper layer will attempt a rollback. However, if the second argument
50464 ** is non-zero then this b-tree transaction is part of a multi-file
50465 ** transaction. In this case, the transaction has already been committed
50466 ** (by deleting a master journal file) and the caller will ignore this
50467 ** functions return code. So, even if an error occurs in the pager layer,
50468 ** reset the b-tree objects internal state to indicate that the write
50469 ** transaction has been closed. This is quite safe, as the pager will have
50470 ** transitioned to the error state.
50472 ** This will release the write lock on the database file. If there
50473 ** are no active cursors, it also releases the read lock.
50475 SQLITE_PRIVATE int sqlite3BtreeCommitPhaseTwo(Btree *p, int bCleanup){
50477 if( p->inTrans==TRANS_NONE ) return SQLITE_OK;
50478 sqlite3BtreeEnter(p);
50479 btreeIntegrity(p);
50481 /* If the handle has a write-transaction open, commit the shared-btrees
50482 ** transaction and set the shared state to TRANS_READ.
50484 if( p->inTrans==TRANS_WRITE ){
50485 int rc;
50486 BtShared *pBt = p->pBt;
50487 assert( pBt->inTransaction==TRANS_WRITE );
50488 assert( pBt->nTransaction>0 );
50489 rc = sqlite3PagerCommitPhaseTwo(pBt->pPager);
50490 if( rc!=SQLITE_OK && bCleanup==0 ){
50491 sqlite3BtreeLeave(p);
50492 return rc;
50494 pBt->inTransaction = TRANS_READ;
50497 btreeEndTransaction(p);
50498 sqlite3BtreeLeave(p);
50499 return SQLITE_OK;
50503 ** Do both phases of a commit.
50505 SQLITE_PRIVATE int sqlite3BtreeCommit(Btree *p){
50506 int rc;
50507 sqlite3BtreeEnter(p);
50508 rc = sqlite3BtreeCommitPhaseOne(p, 0);
50509 if( rc==SQLITE_OK ){
50510 rc = sqlite3BtreeCommitPhaseTwo(p, 0);
50512 sqlite3BtreeLeave(p);
50513 return rc;
50516 #ifndef NDEBUG
50518 ** Return the number of write-cursors open on this handle. This is for use
50519 ** in assert() expressions, so it is only compiled if NDEBUG is not
50520 ** defined.
50522 ** For the purposes of this routine, a write-cursor is any cursor that
50523 ** is capable of writing to the databse. That means the cursor was
50524 ** originally opened for writing and the cursor has not be disabled
50525 ** by having its state changed to CURSOR_FAULT.
50527 static int countWriteCursors(BtShared *pBt){
50528 BtCursor *pCur;
50529 int r = 0;
50530 for(pCur=pBt->pCursor; pCur; pCur=pCur->pNext){
50531 if( pCur->wrFlag && pCur->eState!=CURSOR_FAULT ) r++;
50533 return r;
50535 #endif
50538 ** This routine sets the state to CURSOR_FAULT and the error
50539 ** code to errCode for every cursor on BtShared that pBtree
50540 ** references.
50542 ** Every cursor is tripped, including cursors that belong
50543 ** to other database connections that happen to be sharing
50544 ** the cache with pBtree.
50546 ** This routine gets called when a rollback occurs.
50547 ** All cursors using the same cache must be tripped
50548 ** to prevent them from trying to use the btree after
50549 ** the rollback. The rollback may have deleted tables
50550 ** or moved root pages, so it is not sufficient to
50551 ** save the state of the cursor. The cursor must be
50552 ** invalidated.
50554 SQLITE_PRIVATE void sqlite3BtreeTripAllCursors(Btree *pBtree, int errCode){
50555 BtCursor *p;
50556 sqlite3BtreeEnter(pBtree);
50557 for(p=pBtree->pBt->pCursor; p; p=p->pNext){
50558 int i;
50559 sqlite3BtreeClearCursor(p);
50560 p->eState = CURSOR_FAULT;
50561 p->skipNext = errCode;
50562 for(i=0; i<=p->iPage; i++){
50563 releasePage(p->apPage[i]);
50564 p->apPage[i] = 0;
50567 sqlite3BtreeLeave(pBtree);
50571 ** Rollback the transaction in progress. All cursors will be
50572 ** invalided by this operation. Any attempt to use a cursor
50573 ** that was open at the beginning of this operation will result
50574 ** in an error.
50576 ** This will release the write lock on the database file. If there
50577 ** are no active cursors, it also releases the read lock.
50579 SQLITE_PRIVATE int sqlite3BtreeRollback(Btree *p){
50580 int rc;
50581 BtShared *pBt = p->pBt;
50582 MemPage *pPage1;
50584 sqlite3BtreeEnter(p);
50585 rc = saveAllCursors(pBt, 0, 0);
50586 #ifndef SQLITE_OMIT_SHARED_CACHE
50587 if( rc!=SQLITE_OK ){
50588 /* This is a horrible situation. An IO or malloc() error occurred whilst
50589 ** trying to save cursor positions. If this is an automatic rollback (as
50590 ** the result of a constraint, malloc() failure or IO error) then
50591 ** the cache may be internally inconsistent (not contain valid trees) so
50592 ** we cannot simply return the error to the caller. Instead, abort
50593 ** all queries that may be using any of the cursors that failed to save.
50595 sqlite3BtreeTripAllCursors(p, rc);
50597 #endif
50598 btreeIntegrity(p);
50600 if( p->inTrans==TRANS_WRITE ){
50601 int rc2;
50603 assert( TRANS_WRITE==pBt->inTransaction );
50604 rc2 = sqlite3PagerRollback(pBt->pPager);
50605 if( rc2!=SQLITE_OK ){
50606 rc = rc2;
50609 /* The rollback may have destroyed the pPage1->aData value. So
50610 ** call btreeGetPage() on page 1 again to make
50611 ** sure pPage1->aData is set correctly. */
50612 if( btreeGetPage(pBt, 1, &pPage1, 0)==SQLITE_OK ){
50613 int nPage = get4byte(28+(u8*)pPage1->aData);
50614 testcase( nPage==0 );
50615 if( nPage==0 ) sqlite3PagerPagecount(pBt->pPager, &nPage);
50616 testcase( pBt->nPage!=nPage );
50617 pBt->nPage = nPage;
50618 releasePage(pPage1);
50620 assert( countWriteCursors(pBt)==0 );
50621 pBt->inTransaction = TRANS_READ;
50624 btreeEndTransaction(p);
50625 sqlite3BtreeLeave(p);
50626 return rc;
50630 ** Start a statement subtransaction. The subtransaction can can be rolled
50631 ** back independently of the main transaction. You must start a transaction
50632 ** before starting a subtransaction. The subtransaction is ended automatically
50633 ** if the main transaction commits or rolls back.
50635 ** Statement subtransactions are used around individual SQL statements
50636 ** that are contained within a BEGIN...COMMIT block. If a constraint
50637 ** error occurs within the statement, the effect of that one statement
50638 ** can be rolled back without having to rollback the entire transaction.
50640 ** A statement sub-transaction is implemented as an anonymous savepoint. The
50641 ** value passed as the second parameter is the total number of savepoints,
50642 ** including the new anonymous savepoint, open on the B-Tree. i.e. if there
50643 ** are no active savepoints and no other statement-transactions open,
50644 ** iStatement is 1. This anonymous savepoint can be released or rolled back
50645 ** using the sqlite3BtreeSavepoint() function.
50647 SQLITE_PRIVATE int sqlite3BtreeBeginStmt(Btree *p, int iStatement){
50648 int rc;
50649 BtShared *pBt = p->pBt;
50650 sqlite3BtreeEnter(p);
50651 assert( p->inTrans==TRANS_WRITE );
50652 assert( pBt->readOnly==0 );
50653 assert( iStatement>0 );
50654 assert( iStatement>p->db->nSavepoint );
50655 assert( pBt->inTransaction==TRANS_WRITE );
50656 /* At the pager level, a statement transaction is a savepoint with
50657 ** an index greater than all savepoints created explicitly using
50658 ** SQL statements. It is illegal to open, release or rollback any
50659 ** such savepoints while the statement transaction savepoint is active.
50661 rc = sqlite3PagerOpenSavepoint(pBt->pPager, iStatement);
50662 sqlite3BtreeLeave(p);
50663 return rc;
50667 ** The second argument to this function, op, is always SAVEPOINT_ROLLBACK
50668 ** or SAVEPOINT_RELEASE. This function either releases or rolls back the
50669 ** savepoint identified by parameter iSavepoint, depending on the value
50670 ** of op.
50672 ** Normally, iSavepoint is greater than or equal to zero. However, if op is
50673 ** SAVEPOINT_ROLLBACK, then iSavepoint may also be -1. In this case the
50674 ** contents of the entire transaction are rolled back. This is different
50675 ** from a normal transaction rollback, as no locks are released and the
50676 ** transaction remains open.
50678 SQLITE_PRIVATE int sqlite3BtreeSavepoint(Btree *p, int op, int iSavepoint){
50679 int rc = SQLITE_OK;
50680 if( p && p->inTrans==TRANS_WRITE ){
50681 BtShared *pBt = p->pBt;
50682 assert( op==SAVEPOINT_RELEASE || op==SAVEPOINT_ROLLBACK );
50683 assert( iSavepoint>=0 || (iSavepoint==-1 && op==SAVEPOINT_ROLLBACK) );
50684 sqlite3BtreeEnter(p);
50685 rc = sqlite3PagerSavepoint(pBt->pPager, op, iSavepoint);
50686 if( rc==SQLITE_OK ){
50687 if( iSavepoint<0 && pBt->initiallyEmpty ) pBt->nPage = 0;
50688 rc = newDatabase(pBt);
50689 pBt->nPage = get4byte(28 + pBt->pPage1->aData);
50691 /* The database size was written into the offset 28 of the header
50692 ** when the transaction started, so we know that the value at offset
50693 ** 28 is nonzero. */
50694 assert( pBt->nPage>0 );
50696 sqlite3BtreeLeave(p);
50698 return rc;
50702 ** Create a new cursor for the BTree whose root is on the page
50703 ** iTable. If a read-only cursor is requested, it is assumed that
50704 ** the caller already has at least a read-only transaction open
50705 ** on the database already. If a write-cursor is requested, then
50706 ** the caller is assumed to have an open write transaction.
50708 ** If wrFlag==0, then the cursor can only be used for reading.
50709 ** If wrFlag==1, then the cursor can be used for reading or for
50710 ** writing if other conditions for writing are also met. These
50711 ** are the conditions that must be met in order for writing to
50712 ** be allowed:
50714 ** 1: The cursor must have been opened with wrFlag==1
50716 ** 2: Other database connections that share the same pager cache
50717 ** but which are not in the READ_UNCOMMITTED state may not have
50718 ** cursors open with wrFlag==0 on the same table. Otherwise
50719 ** the changes made by this write cursor would be visible to
50720 ** the read cursors in the other database connection.
50722 ** 3: The database must be writable (not on read-only media)
50724 ** 4: There must be an active transaction.
50726 ** No checking is done to make sure that page iTable really is the
50727 ** root page of a b-tree. If it is not, then the cursor acquired
50728 ** will not work correctly.
50730 ** It is assumed that the sqlite3BtreeCursorZero() has been called
50731 ** on pCur to initialize the memory space prior to invoking this routine.
50733 static int btreeCursor(
50734 Btree *p, /* The btree */
50735 int iTable, /* Root page of table to open */
50736 int wrFlag, /* 1 to write. 0 read-only */
50737 struct KeyInfo *pKeyInfo, /* First arg to comparison function */
50738 BtCursor *pCur /* Space for new cursor */
50740 BtShared *pBt = p->pBt; /* Shared b-tree handle */
50742 assert( sqlite3BtreeHoldsMutex(p) );
50743 assert( wrFlag==0 || wrFlag==1 );
50745 /* The following assert statements verify that if this is a sharable
50746 ** b-tree database, the connection is holding the required table locks,
50747 ** and that no other connection has any open cursor that conflicts with
50748 ** this lock. */
50749 assert( hasSharedCacheTableLock(p, iTable, pKeyInfo!=0, wrFlag+1) );
50750 assert( wrFlag==0 || !hasReadConflicts(p, iTable) );
50752 /* Assert that the caller has opened the required transaction. */
50753 assert( p->inTrans>TRANS_NONE );
50754 assert( wrFlag==0 || p->inTrans==TRANS_WRITE );
50755 assert( pBt->pPage1 && pBt->pPage1->aData );
50757 if( NEVER(wrFlag && pBt->readOnly) ){
50758 return SQLITE_READONLY;
50760 if( iTable==1 && btreePagecount(pBt)==0 ){
50761 return SQLITE_EMPTY;
50764 /* Now that no other errors can occur, finish filling in the BtCursor
50765 ** variables and link the cursor into the BtShared list. */
50766 pCur->pgnoRoot = (Pgno)iTable;
50767 pCur->iPage = -1;
50768 pCur->pKeyInfo = pKeyInfo;
50769 pCur->pBtree = p;
50770 pCur->pBt = pBt;
50771 pCur->wrFlag = (u8)wrFlag;
50772 pCur->pNext = pBt->pCursor;
50773 if( pCur->pNext ){
50774 pCur->pNext->pPrev = pCur;
50776 pBt->pCursor = pCur;
50777 pCur->eState = CURSOR_INVALID;
50778 pCur->cachedRowid = 0;
50779 return SQLITE_OK;
50781 SQLITE_PRIVATE int sqlite3BtreeCursor(
50782 Btree *p, /* The btree */
50783 int iTable, /* Root page of table to open */
50784 int wrFlag, /* 1 to write. 0 read-only */
50785 struct KeyInfo *pKeyInfo, /* First arg to xCompare() */
50786 BtCursor *pCur /* Write new cursor here */
50788 int rc;
50789 sqlite3BtreeEnter(p);
50790 rc = btreeCursor(p, iTable, wrFlag, pKeyInfo, pCur);
50791 sqlite3BtreeLeave(p);
50792 return rc;
50796 ** Return the size of a BtCursor object in bytes.
50798 ** This interfaces is needed so that users of cursors can preallocate
50799 ** sufficient storage to hold a cursor. The BtCursor object is opaque
50800 ** to users so they cannot do the sizeof() themselves - they must call
50801 ** this routine.
50803 SQLITE_PRIVATE int sqlite3BtreeCursorSize(void){
50804 return ROUND8(sizeof(BtCursor));
50808 ** Initialize memory that will be converted into a BtCursor object.
50810 ** The simple approach here would be to memset() the entire object
50811 ** to zero. But it turns out that the apPage[] and aiIdx[] arrays
50812 ** do not need to be zeroed and they are large, so we can save a lot
50813 ** of run-time by skipping the initialization of those elements.
50815 SQLITE_PRIVATE void sqlite3BtreeCursorZero(BtCursor *p){
50816 memset(p, 0, offsetof(BtCursor, iPage));
50820 ** Set the cached rowid value of every cursor in the same database file
50821 ** as pCur and having the same root page number as pCur. The value is
50822 ** set to iRowid.
50824 ** Only positive rowid values are considered valid for this cache.
50825 ** The cache is initialized to zero, indicating an invalid cache.
50826 ** A btree will work fine with zero or negative rowids. We just cannot
50827 ** cache zero or negative rowids, which means tables that use zero or
50828 ** negative rowids might run a little slower. But in practice, zero
50829 ** or negative rowids are very uncommon so this should not be a problem.
50831 SQLITE_PRIVATE void sqlite3BtreeSetCachedRowid(BtCursor *pCur, sqlite3_int64 iRowid){
50832 BtCursor *p;
50833 for(p=pCur->pBt->pCursor; p; p=p->pNext){
50834 if( p->pgnoRoot==pCur->pgnoRoot ) p->cachedRowid = iRowid;
50836 assert( pCur->cachedRowid==iRowid );
50840 ** Return the cached rowid for the given cursor. A negative or zero
50841 ** return value indicates that the rowid cache is invalid and should be
50842 ** ignored. If the rowid cache has never before been set, then a
50843 ** zero is returned.
50845 SQLITE_PRIVATE sqlite3_int64 sqlite3BtreeGetCachedRowid(BtCursor *pCur){
50846 return pCur->cachedRowid;
50850 ** Close a cursor. The read lock on the database file is released
50851 ** when the last cursor is closed.
50853 SQLITE_PRIVATE int sqlite3BtreeCloseCursor(BtCursor *pCur){
50854 Btree *pBtree = pCur->pBtree;
50855 if( pBtree ){
50856 int i;
50857 BtShared *pBt = pCur->pBt;
50858 sqlite3BtreeEnter(pBtree);
50859 sqlite3BtreeClearCursor(pCur);
50860 if( pCur->pPrev ){
50861 pCur->pPrev->pNext = pCur->pNext;
50862 }else{
50863 pBt->pCursor = pCur->pNext;
50865 if( pCur->pNext ){
50866 pCur->pNext->pPrev = pCur->pPrev;
50868 for(i=0; i<=pCur->iPage; i++){
50869 releasePage(pCur->apPage[i]);
50871 unlockBtreeIfUnused(pBt);
50872 invalidateOverflowCache(pCur);
50873 /* sqlite3_free(pCur); */
50874 sqlite3BtreeLeave(pBtree);
50876 return SQLITE_OK;
50880 ** Make sure the BtCursor* given in the argument has a valid
50881 ** BtCursor.info structure. If it is not already valid, call
50882 ** btreeParseCell() to fill it in.
50884 ** BtCursor.info is a cache of the information in the current cell.
50885 ** Using this cache reduces the number of calls to btreeParseCell().
50887 ** 2007-06-25: There is a bug in some versions of MSVC that cause the
50888 ** compiler to crash when getCellInfo() is implemented as a macro.
50889 ** But there is a measureable speed advantage to using the macro on gcc
50890 ** (when less compiler optimizations like -Os or -O0 are used and the
50891 ** compiler is not doing agressive inlining.) So we use a real function
50892 ** for MSVC and a macro for everything else. Ticket #2457.
50894 #ifndef NDEBUG
50895 static void assertCellInfo(BtCursor *pCur){
50896 CellInfo info;
50897 int iPage = pCur->iPage;
50898 memset(&info, 0, sizeof(info));
50899 btreeParseCell(pCur->apPage[iPage], pCur->aiIdx[iPage], &info);
50900 assert( memcmp(&info, &pCur->info, sizeof(info))==0 );
50902 #else
50903 #define assertCellInfo(x)
50904 #endif
50905 #ifdef _MSC_VER
50906 /* Use a real function in MSVC to work around bugs in that compiler. */
50907 static void getCellInfo(BtCursor *pCur){
50908 if( pCur->info.nSize==0 ){
50909 int iPage = pCur->iPage;
50910 btreeParseCell(pCur->apPage[iPage],pCur->aiIdx[iPage],&pCur->info);
50911 pCur->validNKey = 1;
50912 }else{
50913 assertCellInfo(pCur);
50916 #else /* if not _MSC_VER */
50917 /* Use a macro in all other compilers so that the function is inlined */
50918 #define getCellInfo(pCur) \
50919 if( pCur->info.nSize==0 ){ \
50920 int iPage = pCur->iPage; \
50921 btreeParseCell(pCur->apPage[iPage],pCur->aiIdx[iPage],&pCur->info); \
50922 pCur->validNKey = 1; \
50923 }else{ \
50924 assertCellInfo(pCur); \
50926 #endif /* _MSC_VER */
50928 #ifndef NDEBUG /* The next routine used only within assert() statements */
50930 ** Return true if the given BtCursor is valid. A valid cursor is one
50931 ** that is currently pointing to a row in a (non-empty) table.
50932 ** This is a verification routine is used only within assert() statements.
50934 SQLITE_PRIVATE int sqlite3BtreeCursorIsValid(BtCursor *pCur){
50935 return pCur && pCur->eState==CURSOR_VALID;
50937 #endif /* NDEBUG */
50940 ** Set *pSize to the size of the buffer needed to hold the value of
50941 ** the key for the current entry. If the cursor is not pointing
50942 ** to a valid entry, *pSize is set to 0.
50944 ** For a table with the INTKEY flag set, this routine returns the key
50945 ** itself, not the number of bytes in the key.
50947 ** The caller must position the cursor prior to invoking this routine.
50949 ** This routine cannot fail. It always returns SQLITE_OK.
50951 SQLITE_PRIVATE int sqlite3BtreeKeySize(BtCursor *pCur, i64 *pSize){
50952 assert( cursorHoldsMutex(pCur) );
50953 assert( pCur->eState==CURSOR_INVALID || pCur->eState==CURSOR_VALID );
50954 if( pCur->eState!=CURSOR_VALID ){
50955 *pSize = 0;
50956 }else{
50957 getCellInfo(pCur);
50958 *pSize = pCur->info.nKey;
50960 return SQLITE_OK;
50964 ** Set *pSize to the number of bytes of data in the entry the
50965 ** cursor currently points to.
50967 ** The caller must guarantee that the cursor is pointing to a non-NULL
50968 ** valid entry. In other words, the calling procedure must guarantee
50969 ** that the cursor has Cursor.eState==CURSOR_VALID.
50971 ** Failure is not possible. This function always returns SQLITE_OK.
50972 ** It might just as well be a procedure (returning void) but we continue
50973 ** to return an integer result code for historical reasons.
50975 SQLITE_PRIVATE int sqlite3BtreeDataSize(BtCursor *pCur, u32 *pSize){
50976 assert( cursorHoldsMutex(pCur) );
50977 assert( pCur->eState==CURSOR_VALID );
50978 getCellInfo(pCur);
50979 *pSize = pCur->info.nData;
50980 return SQLITE_OK;
50984 ** Given the page number of an overflow page in the database (parameter
50985 ** ovfl), this function finds the page number of the next page in the
50986 ** linked list of overflow pages. If possible, it uses the auto-vacuum
50987 ** pointer-map data instead of reading the content of page ovfl to do so.
50989 ** If an error occurs an SQLite error code is returned. Otherwise:
50991 ** The page number of the next overflow page in the linked list is
50992 ** written to *pPgnoNext. If page ovfl is the last page in its linked
50993 ** list, *pPgnoNext is set to zero.
50995 ** If ppPage is not NULL, and a reference to the MemPage object corresponding
50996 ** to page number pOvfl was obtained, then *ppPage is set to point to that
50997 ** reference. It is the responsibility of the caller to call releasePage()
50998 ** on *ppPage to free the reference. In no reference was obtained (because
50999 ** the pointer-map was used to obtain the value for *pPgnoNext), then
51000 ** *ppPage is set to zero.
51002 static int getOverflowPage(
51003 BtShared *pBt, /* The database file */
51004 Pgno ovfl, /* Current overflow page number */
51005 MemPage **ppPage, /* OUT: MemPage handle (may be NULL) */
51006 Pgno *pPgnoNext /* OUT: Next overflow page number */
51008 Pgno next = 0;
51009 MemPage *pPage = 0;
51010 int rc = SQLITE_OK;
51012 assert( sqlite3_mutex_held(pBt->mutex) );
51013 assert(pPgnoNext);
51015 #ifndef SQLITE_OMIT_AUTOVACUUM
51016 /* Try to find the next page in the overflow list using the
51017 ** autovacuum pointer-map pages. Guess that the next page in
51018 ** the overflow list is page number (ovfl+1). If that guess turns
51019 ** out to be wrong, fall back to loading the data of page
51020 ** number ovfl to determine the next page number.
51022 if( pBt->autoVacuum ){
51023 Pgno pgno;
51024 Pgno iGuess = ovfl+1;
51025 u8 eType;
51027 while( PTRMAP_ISPAGE(pBt, iGuess) || iGuess==PENDING_BYTE_PAGE(pBt) ){
51028 iGuess++;
51031 if( iGuess<=btreePagecount(pBt) ){
51032 rc = ptrmapGet(pBt, iGuess, &eType, &pgno);
51033 if( rc==SQLITE_OK && eType==PTRMAP_OVERFLOW2 && pgno==ovfl ){
51034 next = iGuess;
51035 rc = SQLITE_DONE;
51039 #endif
51041 assert( next==0 || rc==SQLITE_DONE );
51042 if( rc==SQLITE_OK ){
51043 rc = btreeGetPage(pBt, ovfl, &pPage, 0);
51044 assert( rc==SQLITE_OK || pPage==0 );
51045 if( rc==SQLITE_OK ){
51046 next = get4byte(pPage->aData);
51050 *pPgnoNext = next;
51051 if( ppPage ){
51052 *ppPage = pPage;
51053 }else{
51054 releasePage(pPage);
51056 return (rc==SQLITE_DONE ? SQLITE_OK : rc);
51060 ** Copy data from a buffer to a page, or from a page to a buffer.
51062 ** pPayload is a pointer to data stored on database page pDbPage.
51063 ** If argument eOp is false, then nByte bytes of data are copied
51064 ** from pPayload to the buffer pointed at by pBuf. If eOp is true,
51065 ** then sqlite3PagerWrite() is called on pDbPage and nByte bytes
51066 ** of data are copied from the buffer pBuf to pPayload.
51068 ** SQLITE_OK is returned on success, otherwise an error code.
51070 static int copyPayload(
51071 void *pPayload, /* Pointer to page data */
51072 void *pBuf, /* Pointer to buffer */
51073 int nByte, /* Number of bytes to copy */
51074 int eOp, /* 0 -> copy from page, 1 -> copy to page */
51075 DbPage *pDbPage /* Page containing pPayload */
51077 if( eOp ){
51078 /* Copy data from buffer to page (a write operation) */
51079 int rc = sqlite3PagerWrite(pDbPage);
51080 if( rc!=SQLITE_OK ){
51081 return rc;
51083 memcpy(pPayload, pBuf, nByte);
51084 }else{
51085 /* Copy data from page to buffer (a read operation) */
51086 memcpy(pBuf, pPayload, nByte);
51088 return SQLITE_OK;
51092 ** This function is used to read or overwrite payload information
51093 ** for the entry that the pCur cursor is pointing to. If the eOp
51094 ** parameter is 0, this is a read operation (data copied into
51095 ** buffer pBuf). If it is non-zero, a write (data copied from
51096 ** buffer pBuf).
51098 ** A total of "amt" bytes are read or written beginning at "offset".
51099 ** Data is read to or from the buffer pBuf.
51101 ** The content being read or written might appear on the main page
51102 ** or be scattered out on multiple overflow pages.
51104 ** If the BtCursor.isIncrblobHandle flag is set, and the current
51105 ** cursor entry uses one or more overflow pages, this function
51106 ** allocates space for and lazily popluates the overflow page-list
51107 ** cache array (BtCursor.aOverflow). Subsequent calls use this
51108 ** cache to make seeking to the supplied offset more efficient.
51110 ** Once an overflow page-list cache has been allocated, it may be
51111 ** invalidated if some other cursor writes to the same table, or if
51112 ** the cursor is moved to a different row. Additionally, in auto-vacuum
51113 ** mode, the following events may invalidate an overflow page-list cache.
51115 ** * An incremental vacuum,
51116 ** * A commit in auto_vacuum="full" mode,
51117 ** * Creating a table (may require moving an overflow page).
51119 static int accessPayload(
51120 BtCursor *pCur, /* Cursor pointing to entry to read from */
51121 u32 offset, /* Begin reading this far into payload */
51122 u32 amt, /* Read this many bytes */
51123 unsigned char *pBuf, /* Write the bytes into this buffer */
51124 int eOp /* zero to read. non-zero to write. */
51126 unsigned char *aPayload;
51127 int rc = SQLITE_OK;
51128 u32 nKey;
51129 int iIdx = 0;
51130 MemPage *pPage = pCur->apPage[pCur->iPage]; /* Btree page of current entry */
51131 BtShared *pBt = pCur->pBt; /* Btree this cursor belongs to */
51133 assert( pPage );
51134 assert( pCur->eState==CURSOR_VALID );
51135 assert( pCur->aiIdx[pCur->iPage]<pPage->nCell );
51136 assert( cursorHoldsMutex(pCur) );
51138 getCellInfo(pCur);
51139 aPayload = pCur->info.pCell + pCur->info.nHeader;
51140 nKey = (pPage->intKey ? 0 : (int)pCur->info.nKey);
51142 if( NEVER(offset+amt > nKey+pCur->info.nData)
51143 || &aPayload[pCur->info.nLocal] > &pPage->aData[pBt->usableSize]
51145 /* Trying to read or write past the end of the data is an error */
51146 return SQLITE_CORRUPT_BKPT;
51149 /* Check if data must be read/written to/from the btree page itself. */
51150 if( offset<pCur->info.nLocal ){
51151 int a = amt;
51152 if( a+offset>pCur->info.nLocal ){
51153 a = pCur->info.nLocal - offset;
51155 rc = copyPayload(&aPayload[offset], pBuf, a, eOp, pPage->pDbPage);
51156 offset = 0;
51157 pBuf += a;
51158 amt -= a;
51159 }else{
51160 offset -= pCur->info.nLocal;
51163 if( rc==SQLITE_OK && amt>0 ){
51164 const u32 ovflSize = pBt->usableSize - 4; /* Bytes content per ovfl page */
51165 Pgno nextPage;
51167 nextPage = get4byte(&aPayload[pCur->info.nLocal]);
51169 #ifndef SQLITE_OMIT_INCRBLOB
51170 /* If the isIncrblobHandle flag is set and the BtCursor.aOverflow[]
51171 ** has not been allocated, allocate it now. The array is sized at
51172 ** one entry for each overflow page in the overflow chain. The
51173 ** page number of the first overflow page is stored in aOverflow[0],
51174 ** etc. A value of 0 in the aOverflow[] array means "not yet known"
51175 ** (the cache is lazily populated).
51177 if( pCur->isIncrblobHandle && !pCur->aOverflow ){
51178 int nOvfl = (pCur->info.nPayload-pCur->info.nLocal+ovflSize-1)/ovflSize;
51179 pCur->aOverflow = (Pgno *)sqlite3MallocZero(sizeof(Pgno)*nOvfl);
51180 /* nOvfl is always positive. If it were zero, fetchPayload would have
51181 ** been used instead of this routine. */
51182 if( ALWAYS(nOvfl) && !pCur->aOverflow ){
51183 rc = SQLITE_NOMEM;
51187 /* If the overflow page-list cache has been allocated and the
51188 ** entry for the first required overflow page is valid, skip
51189 ** directly to it.
51191 if( pCur->aOverflow && pCur->aOverflow[offset/ovflSize] ){
51192 iIdx = (offset/ovflSize);
51193 nextPage = pCur->aOverflow[iIdx];
51194 offset = (offset%ovflSize);
51196 #endif
51198 for( ; rc==SQLITE_OK && amt>0 && nextPage; iIdx++){
51200 #ifndef SQLITE_OMIT_INCRBLOB
51201 /* If required, populate the overflow page-list cache. */
51202 if( pCur->aOverflow ){
51203 assert(!pCur->aOverflow[iIdx] || pCur->aOverflow[iIdx]==nextPage);
51204 pCur->aOverflow[iIdx] = nextPage;
51206 #endif
51208 if( offset>=ovflSize ){
51209 /* The only reason to read this page is to obtain the page
51210 ** number for the next page in the overflow chain. The page
51211 ** data is not required. So first try to lookup the overflow
51212 ** page-list cache, if any, then fall back to the getOverflowPage()
51213 ** function.
51215 #ifndef SQLITE_OMIT_INCRBLOB
51216 if( pCur->aOverflow && pCur->aOverflow[iIdx+1] ){
51217 nextPage = pCur->aOverflow[iIdx+1];
51218 } else
51219 #endif
51220 rc = getOverflowPage(pBt, nextPage, 0, &nextPage);
51221 offset -= ovflSize;
51222 }else{
51223 /* Need to read this page properly. It contains some of the
51224 ** range of data that is being read (eOp==0) or written (eOp!=0).
51226 DbPage *pDbPage;
51227 int a = amt;
51228 rc = sqlite3PagerGet(pBt->pPager, nextPage, &pDbPage);
51229 if( rc==SQLITE_OK ){
51230 aPayload = sqlite3PagerGetData(pDbPage);
51231 nextPage = get4byte(aPayload);
51232 if( a + offset > ovflSize ){
51233 a = ovflSize - offset;
51235 rc = copyPayload(&aPayload[offset+4], pBuf, a, eOp, pDbPage);
51236 sqlite3PagerUnref(pDbPage);
51237 offset = 0;
51238 amt -= a;
51239 pBuf += a;
51245 if( rc==SQLITE_OK && amt>0 ){
51246 return SQLITE_CORRUPT_BKPT;
51248 return rc;
51252 ** Read part of the key associated with cursor pCur. Exactly
51253 ** "amt" bytes will be transfered into pBuf[]. The transfer
51254 ** begins at "offset".
51256 ** The caller must ensure that pCur is pointing to a valid row
51257 ** in the table.
51259 ** Return SQLITE_OK on success or an error code if anything goes
51260 ** wrong. An error is returned if "offset+amt" is larger than
51261 ** the available payload.
51263 SQLITE_PRIVATE int sqlite3BtreeKey(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){
51264 assert( cursorHoldsMutex(pCur) );
51265 assert( pCur->eState==CURSOR_VALID );
51266 assert( pCur->iPage>=0 && pCur->apPage[pCur->iPage] );
51267 assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );
51268 return accessPayload(pCur, offset, amt, (unsigned char*)pBuf, 0);
51272 ** Read part of the data associated with cursor pCur. Exactly
51273 ** "amt" bytes will be transfered into pBuf[]. The transfer
51274 ** begins at "offset".
51276 ** Return SQLITE_OK on success or an error code if anything goes
51277 ** wrong. An error is returned if "offset+amt" is larger than
51278 ** the available payload.
51280 SQLITE_PRIVATE int sqlite3BtreeData(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){
51281 int rc;
51283 #ifndef SQLITE_OMIT_INCRBLOB
51284 if ( pCur->eState==CURSOR_INVALID ){
51285 return SQLITE_ABORT;
51287 #endif
51289 assert( cursorHoldsMutex(pCur) );
51290 rc = restoreCursorPosition(pCur);
51291 if( rc==SQLITE_OK ){
51292 assert( pCur->eState==CURSOR_VALID );
51293 assert( pCur->iPage>=0 && pCur->apPage[pCur->iPage] );
51294 assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );
51295 rc = accessPayload(pCur, offset, amt, pBuf, 0);
51297 return rc;
51301 ** Return a pointer to payload information from the entry that the
51302 ** pCur cursor is pointing to. The pointer is to the beginning of
51303 ** the key if skipKey==0 and it points to the beginning of data if
51304 ** skipKey==1. The number of bytes of available key/data is written
51305 ** into *pAmt. If *pAmt==0, then the value returned will not be
51306 ** a valid pointer.
51308 ** This routine is an optimization. It is common for the entire key
51309 ** and data to fit on the local page and for there to be no overflow
51310 ** pages. When that is so, this routine can be used to access the
51311 ** key and data without making a copy. If the key and/or data spills
51312 ** onto overflow pages, then accessPayload() must be used to reassemble
51313 ** the key/data and copy it into a preallocated buffer.
51315 ** The pointer returned by this routine looks directly into the cached
51316 ** page of the database. The data might change or move the next time
51317 ** any btree routine is called.
51319 static const unsigned char *fetchPayload(
51320 BtCursor *pCur, /* Cursor pointing to entry to read from */
51321 int *pAmt, /* Write the number of available bytes here */
51322 int skipKey /* read beginning at data if this is true */
51324 unsigned char *aPayload;
51325 MemPage *pPage;
51326 u32 nKey;
51327 u32 nLocal;
51329 assert( pCur!=0 && pCur->iPage>=0 && pCur->apPage[pCur->iPage]);
51330 assert( pCur->eState==CURSOR_VALID );
51331 assert( cursorHoldsMutex(pCur) );
51332 pPage = pCur->apPage[pCur->iPage];
51333 assert( pCur->aiIdx[pCur->iPage]<pPage->nCell );
51334 if( NEVER(pCur->info.nSize==0) ){
51335 btreeParseCell(pCur->apPage[pCur->iPage], pCur->aiIdx[pCur->iPage],
51336 &pCur->info);
51338 aPayload = pCur->info.pCell;
51339 aPayload += pCur->info.nHeader;
51340 if( pPage->intKey ){
51341 nKey = 0;
51342 }else{
51343 nKey = (int)pCur->info.nKey;
51345 if( skipKey ){
51346 aPayload += nKey;
51347 nLocal = pCur->info.nLocal - nKey;
51348 }else{
51349 nLocal = pCur->info.nLocal;
51350 assert( nLocal<=nKey );
51352 *pAmt = nLocal;
51353 return aPayload;
51358 ** For the entry that cursor pCur is point to, return as
51359 ** many bytes of the key or data as are available on the local
51360 ** b-tree page. Write the number of available bytes into *pAmt.
51362 ** The pointer returned is ephemeral. The key/data may move
51363 ** or be destroyed on the next call to any Btree routine,
51364 ** including calls from other threads against the same cache.
51365 ** Hence, a mutex on the BtShared should be held prior to calling
51366 ** this routine.
51368 ** These routines is used to get quick access to key and data
51369 ** in the common case where no overflow pages are used.
51371 SQLITE_PRIVATE const void *sqlite3BtreeKeyFetch(BtCursor *pCur, int *pAmt){
51372 const void *p = 0;
51373 assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
51374 assert( cursorHoldsMutex(pCur) );
51375 if( ALWAYS(pCur->eState==CURSOR_VALID) ){
51376 p = (const void*)fetchPayload(pCur, pAmt, 0);
51378 return p;
51380 SQLITE_PRIVATE const void *sqlite3BtreeDataFetch(BtCursor *pCur, int *pAmt){
51381 const void *p = 0;
51382 assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
51383 assert( cursorHoldsMutex(pCur) );
51384 if( ALWAYS(pCur->eState==CURSOR_VALID) ){
51385 p = (const void*)fetchPayload(pCur, pAmt, 1);
51387 return p;
51392 ** Move the cursor down to a new child page. The newPgno argument is the
51393 ** page number of the child page to move to.
51395 ** This function returns SQLITE_CORRUPT if the page-header flags field of
51396 ** the new child page does not match the flags field of the parent (i.e.
51397 ** if an intkey page appears to be the parent of a non-intkey page, or
51398 ** vice-versa).
51400 static int moveToChild(BtCursor *pCur, u32 newPgno){
51401 int rc;
51402 int i = pCur->iPage;
51403 MemPage *pNewPage;
51404 BtShared *pBt = pCur->pBt;
51406 assert( cursorHoldsMutex(pCur) );
51407 assert( pCur->eState==CURSOR_VALID );
51408 assert( pCur->iPage<BTCURSOR_MAX_DEPTH );
51409 if( pCur->iPage>=(BTCURSOR_MAX_DEPTH-1) ){
51410 return SQLITE_CORRUPT_BKPT;
51412 rc = getAndInitPage(pBt, newPgno, &pNewPage);
51413 if( rc ) return rc;
51414 pCur->apPage[i+1] = pNewPage;
51415 pCur->aiIdx[i+1] = 0;
51416 pCur->iPage++;
51418 pCur->info.nSize = 0;
51419 pCur->validNKey = 0;
51420 if( pNewPage->nCell<1 || pNewPage->intKey!=pCur->apPage[i]->intKey ){
51421 return SQLITE_CORRUPT_BKPT;
51423 return SQLITE_OK;
51426 #ifndef NDEBUG
51428 ** Page pParent is an internal (non-leaf) tree page. This function
51429 ** asserts that page number iChild is the left-child if the iIdx'th
51430 ** cell in page pParent. Or, if iIdx is equal to the total number of
51431 ** cells in pParent, that page number iChild is the right-child of
51432 ** the page.
51434 static void assertParentIndex(MemPage *pParent, int iIdx, Pgno iChild){
51435 assert( iIdx<=pParent->nCell );
51436 if( iIdx==pParent->nCell ){
51437 assert( get4byte(&pParent->aData[pParent->hdrOffset+8])==iChild );
51438 }else{
51439 assert( get4byte(findCell(pParent, iIdx))==iChild );
51442 #else
51443 # define assertParentIndex(x,y,z)
51444 #endif
51447 ** Move the cursor up to the parent page.
51449 ** pCur->idx is set to the cell index that contains the pointer
51450 ** to the page we are coming from. If we are coming from the
51451 ** right-most child page then pCur->idx is set to one more than
51452 ** the largest cell index.
51454 static void moveToParent(BtCursor *pCur){
51455 assert( cursorHoldsMutex(pCur) );
51456 assert( pCur->eState==CURSOR_VALID );
51457 assert( pCur->iPage>0 );
51458 assert( pCur->apPage[pCur->iPage] );
51459 assertParentIndex(
51460 pCur->apPage[pCur->iPage-1],
51461 pCur->aiIdx[pCur->iPage-1],
51462 pCur->apPage[pCur->iPage]->pgno
51464 releasePage(pCur->apPage[pCur->iPage]);
51465 pCur->iPage--;
51466 pCur->info.nSize = 0;
51467 pCur->validNKey = 0;
51471 ** Move the cursor to point to the root page of its b-tree structure.
51473 ** If the table has a virtual root page, then the cursor is moved to point
51474 ** to the virtual root page instead of the actual root page. A table has a
51475 ** virtual root page when the actual root page contains no cells and a
51476 ** single child page. This can only happen with the table rooted at page 1.
51478 ** If the b-tree structure is empty, the cursor state is set to
51479 ** CURSOR_INVALID. Otherwise, the cursor is set to point to the first
51480 ** cell located on the root (or virtual root) page and the cursor state
51481 ** is set to CURSOR_VALID.
51483 ** If this function returns successfully, it may be assumed that the
51484 ** page-header flags indicate that the [virtual] root-page is the expected
51485 ** kind of b-tree page (i.e. if when opening the cursor the caller did not
51486 ** specify a KeyInfo structure the flags byte is set to 0x05 or 0x0D,
51487 ** indicating a table b-tree, or if the caller did specify a KeyInfo
51488 ** structure the flags byte is set to 0x02 or 0x0A, indicating an index
51489 ** b-tree).
51491 static int moveToRoot(BtCursor *pCur){
51492 MemPage *pRoot;
51493 int rc = SQLITE_OK;
51494 Btree *p = pCur->pBtree;
51495 BtShared *pBt = p->pBt;
51497 assert( cursorHoldsMutex(pCur) );
51498 assert( CURSOR_INVALID < CURSOR_REQUIRESEEK );
51499 assert( CURSOR_VALID < CURSOR_REQUIRESEEK );
51500 assert( CURSOR_FAULT > CURSOR_REQUIRESEEK );
51501 if( pCur->eState>=CURSOR_REQUIRESEEK ){
51502 if( pCur->eState==CURSOR_FAULT ){
51503 assert( pCur->skipNext!=SQLITE_OK );
51504 return pCur->skipNext;
51506 sqlite3BtreeClearCursor(pCur);
51509 if( pCur->iPage>=0 ){
51510 int i;
51511 for(i=1; i<=pCur->iPage; i++){
51512 releasePage(pCur->apPage[i]);
51514 pCur->iPage = 0;
51515 }else{
51516 rc = getAndInitPage(pBt, pCur->pgnoRoot, &pCur->apPage[0]);
51517 if( rc!=SQLITE_OK ){
51518 pCur->eState = CURSOR_INVALID;
51519 return rc;
51521 pCur->iPage = 0;
51523 /* If pCur->pKeyInfo is not NULL, then the caller that opened this cursor
51524 ** expected to open it on an index b-tree. Otherwise, if pKeyInfo is
51525 ** NULL, the caller expects a table b-tree. If this is not the case,
51526 ** return an SQLITE_CORRUPT error. */
51527 assert( pCur->apPage[0]->intKey==1 || pCur->apPage[0]->intKey==0 );
51528 if( (pCur->pKeyInfo==0)!=pCur->apPage[0]->intKey ){
51529 return SQLITE_CORRUPT_BKPT;
51533 /* Assert that the root page is of the correct type. This must be the
51534 ** case as the call to this function that loaded the root-page (either
51535 ** this call or a previous invocation) would have detected corruption
51536 ** if the assumption were not true, and it is not possible for the flags
51537 ** byte to have been modified while this cursor is holding a reference
51538 ** to the page. */
51539 pRoot = pCur->apPage[0];
51540 assert( pRoot->pgno==pCur->pgnoRoot );
51541 assert( pRoot->isInit && (pCur->pKeyInfo==0)==pRoot->intKey );
51543 pCur->aiIdx[0] = 0;
51544 pCur->info.nSize = 0;
51545 pCur->atLast = 0;
51546 pCur->validNKey = 0;
51548 if( pRoot->nCell==0 && !pRoot->leaf ){
51549 Pgno subpage;
51550 if( pRoot->pgno!=1 ) return SQLITE_CORRUPT_BKPT;
51551 subpage = get4byte(&pRoot->aData[pRoot->hdrOffset+8]);
51552 pCur->eState = CURSOR_VALID;
51553 rc = moveToChild(pCur, subpage);
51554 }else{
51555 pCur->eState = ((pRoot->nCell>0)?CURSOR_VALID:CURSOR_INVALID);
51557 return rc;
51561 ** Move the cursor down to the left-most leaf entry beneath the
51562 ** entry to which it is currently pointing.
51564 ** The left-most leaf is the one with the smallest key - the first
51565 ** in ascending order.
51567 static int moveToLeftmost(BtCursor *pCur){
51568 Pgno pgno;
51569 int rc = SQLITE_OK;
51570 MemPage *pPage;
51572 assert( cursorHoldsMutex(pCur) );
51573 assert( pCur->eState==CURSOR_VALID );
51574 while( rc==SQLITE_OK && !(pPage = pCur->apPage[pCur->iPage])->leaf ){
51575 assert( pCur->aiIdx[pCur->iPage]<pPage->nCell );
51576 pgno = get4byte(findCell(pPage, pCur->aiIdx[pCur->iPage]));
51577 rc = moveToChild(pCur, pgno);
51579 return rc;
51583 ** Move the cursor down to the right-most leaf entry beneath the
51584 ** page to which it is currently pointing. Notice the difference
51585 ** between moveToLeftmost() and moveToRightmost(). moveToLeftmost()
51586 ** finds the left-most entry beneath the *entry* whereas moveToRightmost()
51587 ** finds the right-most entry beneath the *page*.
51589 ** The right-most entry is the one with the largest key - the last
51590 ** key in ascending order.
51592 static int moveToRightmost(BtCursor *pCur){
51593 Pgno pgno;
51594 int rc = SQLITE_OK;
51595 MemPage *pPage = 0;
51597 assert( cursorHoldsMutex(pCur) );
51598 assert( pCur->eState==CURSOR_VALID );
51599 while( rc==SQLITE_OK && !(pPage = pCur->apPage[pCur->iPage])->leaf ){
51600 pgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
51601 pCur->aiIdx[pCur->iPage] = pPage->nCell;
51602 rc = moveToChild(pCur, pgno);
51604 if( rc==SQLITE_OK ){
51605 pCur->aiIdx[pCur->iPage] = pPage->nCell-1;
51606 pCur->info.nSize = 0;
51607 pCur->validNKey = 0;
51609 return rc;
51612 /* Move the cursor to the first entry in the table. Return SQLITE_OK
51613 ** on success. Set *pRes to 0 if the cursor actually points to something
51614 ** or set *pRes to 1 if the table is empty.
51616 SQLITE_PRIVATE int sqlite3BtreeFirst(BtCursor *pCur, int *pRes){
51617 int rc;
51619 assert( cursorHoldsMutex(pCur) );
51620 assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
51621 rc = moveToRoot(pCur);
51622 if( rc==SQLITE_OK ){
51623 if( pCur->eState==CURSOR_INVALID ){
51624 assert( pCur->apPage[pCur->iPage]->nCell==0 );
51625 *pRes = 1;
51626 }else{
51627 assert( pCur->apPage[pCur->iPage]->nCell>0 );
51628 *pRes = 0;
51629 rc = moveToLeftmost(pCur);
51632 return rc;
51635 /* Move the cursor to the last entry in the table. Return SQLITE_OK
51636 ** on success. Set *pRes to 0 if the cursor actually points to something
51637 ** or set *pRes to 1 if the table is empty.
51639 SQLITE_PRIVATE int sqlite3BtreeLast(BtCursor *pCur, int *pRes){
51640 int rc;
51642 assert( cursorHoldsMutex(pCur) );
51643 assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
51645 /* If the cursor already points to the last entry, this is a no-op. */
51646 if( CURSOR_VALID==pCur->eState && pCur->atLast ){
51647 #ifdef SQLITE_DEBUG
51648 /* This block serves to assert() that the cursor really does point
51649 ** to the last entry in the b-tree. */
51650 int ii;
51651 for(ii=0; ii<pCur->iPage; ii++){
51652 assert( pCur->aiIdx[ii]==pCur->apPage[ii]->nCell );
51654 assert( pCur->aiIdx[pCur->iPage]==pCur->apPage[pCur->iPage]->nCell-1 );
51655 assert( pCur->apPage[pCur->iPage]->leaf );
51656 #endif
51657 return SQLITE_OK;
51660 rc = moveToRoot(pCur);
51661 if( rc==SQLITE_OK ){
51662 if( CURSOR_INVALID==pCur->eState ){
51663 assert( pCur->apPage[pCur->iPage]->nCell==0 );
51664 *pRes = 1;
51665 }else{
51666 assert( pCur->eState==CURSOR_VALID );
51667 *pRes = 0;
51668 rc = moveToRightmost(pCur);
51669 pCur->atLast = rc==SQLITE_OK ?1:0;
51672 return rc;
51675 /* Move the cursor so that it points to an entry near the key
51676 ** specified by pIdxKey or intKey. Return a success code.
51678 ** For INTKEY tables, the intKey parameter is used. pIdxKey
51679 ** must be NULL. For index tables, pIdxKey is used and intKey
51680 ** is ignored.
51682 ** If an exact match is not found, then the cursor is always
51683 ** left pointing at a leaf page which would hold the entry if it
51684 ** were present. The cursor might point to an entry that comes
51685 ** before or after the key.
51687 ** An integer is written into *pRes which is the result of
51688 ** comparing the key with the entry to which the cursor is
51689 ** pointing. The meaning of the integer written into
51690 ** *pRes is as follows:
51692 ** *pRes<0 The cursor is left pointing at an entry that
51693 ** is smaller than intKey/pIdxKey or if the table is empty
51694 ** and the cursor is therefore left point to nothing.
51696 ** *pRes==0 The cursor is left pointing at an entry that
51697 ** exactly matches intKey/pIdxKey.
51699 ** *pRes>0 The cursor is left pointing at an entry that
51700 ** is larger than intKey/pIdxKey.
51703 SQLITE_PRIVATE int sqlite3BtreeMovetoUnpacked(
51704 BtCursor *pCur, /* The cursor to be moved */
51705 UnpackedRecord *pIdxKey, /* Unpacked index key */
51706 i64 intKey, /* The table key */
51707 int biasRight, /* If true, bias the search to the high end */
51708 int *pRes /* Write search results here */
51710 int rc;
51712 assert( cursorHoldsMutex(pCur) );
51713 assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
51714 assert( pRes );
51715 assert( (pIdxKey==0)==(pCur->pKeyInfo==0) );
51717 /* If the cursor is already positioned at the point we are trying
51718 ** to move to, then just return without doing any work */
51719 if( pCur->eState==CURSOR_VALID && pCur->validNKey
51720 && pCur->apPage[0]->intKey
51722 if( pCur->info.nKey==intKey ){
51723 *pRes = 0;
51724 return SQLITE_OK;
51726 if( pCur->atLast && pCur->info.nKey<intKey ){
51727 *pRes = -1;
51728 return SQLITE_OK;
51732 rc = moveToRoot(pCur);
51733 if( rc ){
51734 return rc;
51736 assert( pCur->apPage[pCur->iPage] );
51737 assert( pCur->apPage[pCur->iPage]->isInit );
51738 assert( pCur->apPage[pCur->iPage]->nCell>0 || pCur->eState==CURSOR_INVALID );
51739 if( pCur->eState==CURSOR_INVALID ){
51740 *pRes = -1;
51741 assert( pCur->apPage[pCur->iPage]->nCell==0 );
51742 return SQLITE_OK;
51744 assert( pCur->apPage[0]->intKey || pIdxKey );
51745 for(;;){
51746 int lwr, upr;
51747 Pgno chldPg;
51748 MemPage *pPage = pCur->apPage[pCur->iPage];
51749 int c;
51751 /* pPage->nCell must be greater than zero. If this is the root-page
51752 ** the cursor would have been INVALID above and this for(;;) loop
51753 ** not run. If this is not the root-page, then the moveToChild() routine
51754 ** would have already detected db corruption. Similarly, pPage must
51755 ** be the right kind (index or table) of b-tree page. Otherwise
51756 ** a moveToChild() or moveToRoot() call would have detected corruption. */
51757 assert( pPage->nCell>0 );
51758 assert( pPage->intKey==(pIdxKey==0) );
51759 lwr = 0;
51760 upr = pPage->nCell-1;
51761 if( biasRight ){
51762 pCur->aiIdx[pCur->iPage] = (u16)upr;
51763 }else{
51764 pCur->aiIdx[pCur->iPage] = (u16)((upr+lwr)/2);
51766 for(;;){
51767 int idx = pCur->aiIdx[pCur->iPage]; /* Index of current cell in pPage */
51768 u8 *pCell; /* Pointer to current cell in pPage */
51770 pCur->info.nSize = 0;
51771 pCell = findCell(pPage, idx) + pPage->childPtrSize;
51772 if( pPage->intKey ){
51773 i64 nCellKey;
51774 if( pPage->hasData ){
51775 u32 dummy;
51776 pCell += getVarint32(pCell, dummy);
51778 getVarint(pCell, (u64*)&nCellKey);
51779 if( nCellKey==intKey ){
51780 c = 0;
51781 }else if( nCellKey<intKey ){
51782 c = -1;
51783 }else{
51784 assert( nCellKey>intKey );
51785 c = +1;
51787 pCur->validNKey = 1;
51788 pCur->info.nKey = nCellKey;
51789 }else{
51790 /* The maximum supported page-size is 65536 bytes. This means that
51791 ** the maximum number of record bytes stored on an index B-Tree
51792 ** page is less than 16384 bytes and may be stored as a 2-byte
51793 ** varint. This information is used to attempt to avoid parsing
51794 ** the entire cell by checking for the cases where the record is
51795 ** stored entirely within the b-tree page by inspecting the first
51796 ** 2 bytes of the cell.
51798 int nCell = pCell[0];
51799 if( !(nCell & 0x80) && nCell<=pPage->maxLocal ){
51800 /* This branch runs if the record-size field of the cell is a
51801 ** single byte varint and the record fits entirely on the main
51802 ** b-tree page. */
51803 c = sqlite3VdbeRecordCompare(nCell, (void*)&pCell[1], pIdxKey);
51804 }else if( !(pCell[1] & 0x80)
51805 && (nCell = ((nCell&0x7f)<<7) + pCell[1])<=pPage->maxLocal
51807 /* The record-size field is a 2 byte varint and the record
51808 ** fits entirely on the main b-tree page. */
51809 c = sqlite3VdbeRecordCompare(nCell, (void*)&pCell[2], pIdxKey);
51810 }else{
51811 /* The record flows over onto one or more overflow pages. In
51812 ** this case the whole cell needs to be parsed, a buffer allocated
51813 ** and accessPayload() used to retrieve the record into the
51814 ** buffer before VdbeRecordCompare() can be called. */
51815 void *pCellKey;
51816 u8 * const pCellBody = pCell - pPage->childPtrSize;
51817 btreeParseCellPtr(pPage, pCellBody, &pCur->info);
51818 nCell = (int)pCur->info.nKey;
51819 pCellKey = sqlite3Malloc( nCell );
51820 if( pCellKey==0 ){
51821 rc = SQLITE_NOMEM;
51822 goto moveto_finish;
51824 rc = accessPayload(pCur, 0, nCell, (unsigned char*)pCellKey, 0);
51825 if( rc ){
51826 sqlite3_free(pCellKey);
51827 goto moveto_finish;
51829 c = sqlite3VdbeRecordCompare(nCell, pCellKey, pIdxKey);
51830 sqlite3_free(pCellKey);
51833 if( c==0 ){
51834 if( pPage->intKey && !pPage->leaf ){
51835 lwr = idx;
51836 upr = lwr - 1;
51837 break;
51838 }else{
51839 *pRes = 0;
51840 rc = SQLITE_OK;
51841 goto moveto_finish;
51844 if( c<0 ){
51845 lwr = idx+1;
51846 }else{
51847 upr = idx-1;
51849 if( lwr>upr ){
51850 break;
51852 pCur->aiIdx[pCur->iPage] = (u16)((lwr+upr)/2);
51854 assert( lwr==upr+1 );
51855 assert( pPage->isInit );
51856 if( pPage->leaf ){
51857 chldPg = 0;
51858 }else if( lwr>=pPage->nCell ){
51859 chldPg = get4byte(&pPage->aData[pPage->hdrOffset+8]);
51860 }else{
51861 chldPg = get4byte(findCell(pPage, lwr));
51863 if( chldPg==0 ){
51864 assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );
51865 *pRes = c;
51866 rc = SQLITE_OK;
51867 goto moveto_finish;
51869 pCur->aiIdx[pCur->iPage] = (u16)lwr;
51870 pCur->info.nSize = 0;
51871 pCur->validNKey = 0;
51872 rc = moveToChild(pCur, chldPg);
51873 if( rc ) goto moveto_finish;
51875 moveto_finish:
51876 return rc;
51881 ** Return TRUE if the cursor is not pointing at an entry of the table.
51883 ** TRUE will be returned after a call to sqlite3BtreeNext() moves
51884 ** past the last entry in the table or sqlite3BtreePrev() moves past
51885 ** the first entry. TRUE is also returned if the table is empty.
51887 SQLITE_PRIVATE int sqlite3BtreeEof(BtCursor *pCur){
51888 /* TODO: What if the cursor is in CURSOR_REQUIRESEEK but all table entries
51889 ** have been deleted? This API will need to change to return an error code
51890 ** as well as the boolean result value.
51892 return (CURSOR_VALID!=pCur->eState);
51896 ** Advance the cursor to the next entry in the database. If
51897 ** successful then set *pRes=0. If the cursor
51898 ** was already pointing to the last entry in the database before
51899 ** this routine was called, then set *pRes=1.
51901 SQLITE_PRIVATE int sqlite3BtreeNext(BtCursor *pCur, int *pRes){
51902 int rc;
51903 int idx;
51904 MemPage *pPage;
51906 assert( cursorHoldsMutex(pCur) );
51907 rc = restoreCursorPosition(pCur);
51908 if( rc!=SQLITE_OK ){
51909 return rc;
51911 assert( pRes!=0 );
51912 if( CURSOR_INVALID==pCur->eState ){
51913 *pRes = 1;
51914 return SQLITE_OK;
51916 if( pCur->skipNext>0 ){
51917 pCur->skipNext = 0;
51918 *pRes = 0;
51919 return SQLITE_OK;
51921 pCur->skipNext = 0;
51923 pPage = pCur->apPage[pCur->iPage];
51924 idx = ++pCur->aiIdx[pCur->iPage];
51925 assert( pPage->isInit );
51926 assert( idx<=pPage->nCell );
51928 pCur->info.nSize = 0;
51929 pCur->validNKey = 0;
51930 if( idx>=pPage->nCell ){
51931 if( !pPage->leaf ){
51932 rc = moveToChild(pCur, get4byte(&pPage->aData[pPage->hdrOffset+8]));
51933 if( rc ) return rc;
51934 rc = moveToLeftmost(pCur);
51935 *pRes = 0;
51936 return rc;
51939 if( pCur->iPage==0 ){
51940 *pRes = 1;
51941 pCur->eState = CURSOR_INVALID;
51942 return SQLITE_OK;
51944 moveToParent(pCur);
51945 pPage = pCur->apPage[pCur->iPage];
51946 }while( pCur->aiIdx[pCur->iPage]>=pPage->nCell );
51947 *pRes = 0;
51948 if( pPage->intKey ){
51949 rc = sqlite3BtreeNext(pCur, pRes);
51950 }else{
51951 rc = SQLITE_OK;
51953 return rc;
51955 *pRes = 0;
51956 if( pPage->leaf ){
51957 return SQLITE_OK;
51959 rc = moveToLeftmost(pCur);
51960 return rc;
51965 ** Step the cursor to the back to the previous entry in the database. If
51966 ** successful then set *pRes=0. If the cursor
51967 ** was already pointing to the first entry in the database before
51968 ** this routine was called, then set *pRes=1.
51970 SQLITE_PRIVATE int sqlite3BtreePrevious(BtCursor *pCur, int *pRes){
51971 int rc;
51972 MemPage *pPage;
51974 assert( cursorHoldsMutex(pCur) );
51975 rc = restoreCursorPosition(pCur);
51976 if( rc!=SQLITE_OK ){
51977 return rc;
51979 pCur->atLast = 0;
51980 if( CURSOR_INVALID==pCur->eState ){
51981 *pRes = 1;
51982 return SQLITE_OK;
51984 if( pCur->skipNext<0 ){
51985 pCur->skipNext = 0;
51986 *pRes = 0;
51987 return SQLITE_OK;
51989 pCur->skipNext = 0;
51991 pPage = pCur->apPage[pCur->iPage];
51992 assert( pPage->isInit );
51993 if( !pPage->leaf ){
51994 int idx = pCur->aiIdx[pCur->iPage];
51995 rc = moveToChild(pCur, get4byte(findCell(pPage, idx)));
51996 if( rc ){
51997 return rc;
51999 rc = moveToRightmost(pCur);
52000 }else{
52001 while( pCur->aiIdx[pCur->iPage]==0 ){
52002 if( pCur->iPage==0 ){
52003 pCur->eState = CURSOR_INVALID;
52004 *pRes = 1;
52005 return SQLITE_OK;
52007 moveToParent(pCur);
52009 pCur->info.nSize = 0;
52010 pCur->validNKey = 0;
52012 pCur->aiIdx[pCur->iPage]--;
52013 pPage = pCur->apPage[pCur->iPage];
52014 if( pPage->intKey && !pPage->leaf ){
52015 rc = sqlite3BtreePrevious(pCur, pRes);
52016 }else{
52017 rc = SQLITE_OK;
52020 *pRes = 0;
52021 return rc;
52025 ** Allocate a new page from the database file.
52027 ** The new page is marked as dirty. (In other words, sqlite3PagerWrite()
52028 ** has already been called on the new page.) The new page has also
52029 ** been referenced and the calling routine is responsible for calling
52030 ** sqlite3PagerUnref() on the new page when it is done.
52032 ** SQLITE_OK is returned on success. Any other return value indicates
52033 ** an error. *ppPage and *pPgno are undefined in the event of an error.
52034 ** Do not invoke sqlite3PagerUnref() on *ppPage if an error is returned.
52036 ** If the "nearby" parameter is not 0, then a (feeble) effort is made to
52037 ** locate a page close to the page number "nearby". This can be used in an
52038 ** attempt to keep related pages close to each other in the database file,
52039 ** which in turn can make database access faster.
52041 ** If the "exact" parameter is not 0, and the page-number nearby exists
52042 ** anywhere on the free-list, then it is guarenteed to be returned. This
52043 ** is only used by auto-vacuum databases when allocating a new table.
52045 static int allocateBtreePage(
52046 BtShared *pBt,
52047 MemPage **ppPage,
52048 Pgno *pPgno,
52049 Pgno nearby,
52050 u8 exact
52052 MemPage *pPage1;
52053 int rc;
52054 u32 n; /* Number of pages on the freelist */
52055 u32 k; /* Number of leaves on the trunk of the freelist */
52056 MemPage *pTrunk = 0;
52057 MemPage *pPrevTrunk = 0;
52058 Pgno mxPage; /* Total size of the database file */
52060 assert( sqlite3_mutex_held(pBt->mutex) );
52061 pPage1 = pBt->pPage1;
52062 mxPage = btreePagecount(pBt);
52063 n = get4byte(&pPage1->aData[36]);
52064 testcase( n==mxPage-1 );
52065 if( n>=mxPage ){
52066 return SQLITE_CORRUPT_BKPT;
52068 if( n>0 ){
52069 /* There are pages on the freelist. Reuse one of those pages. */
52070 Pgno iTrunk;
52071 u8 searchList = 0; /* If the free-list must be searched for 'nearby' */
52073 /* If the 'exact' parameter was true and a query of the pointer-map
52074 ** shows that the page 'nearby' is somewhere on the free-list, then
52075 ** the entire-list will be searched for that page.
52077 #ifndef SQLITE_OMIT_AUTOVACUUM
52078 if( exact && nearby<=mxPage ){
52079 u8 eType;
52080 assert( nearby>0 );
52081 assert( pBt->autoVacuum );
52082 rc = ptrmapGet(pBt, nearby, &eType, 0);
52083 if( rc ) return rc;
52084 if( eType==PTRMAP_FREEPAGE ){
52085 searchList = 1;
52087 *pPgno = nearby;
52089 #endif
52091 /* Decrement the free-list count by 1. Set iTrunk to the index of the
52092 ** first free-list trunk page. iPrevTrunk is initially 1.
52094 rc = sqlite3PagerWrite(pPage1->pDbPage);
52095 if( rc ) return rc;
52096 put4byte(&pPage1->aData[36], n-1);
52098 /* The code within this loop is run only once if the 'searchList' variable
52099 ** is not true. Otherwise, it runs once for each trunk-page on the
52100 ** free-list until the page 'nearby' is located.
52102 do {
52103 pPrevTrunk = pTrunk;
52104 if( pPrevTrunk ){
52105 iTrunk = get4byte(&pPrevTrunk->aData[0]);
52106 }else{
52107 iTrunk = get4byte(&pPage1->aData[32]);
52109 testcase( iTrunk==mxPage );
52110 if( iTrunk>mxPage ){
52111 rc = SQLITE_CORRUPT_BKPT;
52112 }else{
52113 rc = btreeGetPage(pBt, iTrunk, &pTrunk, 0);
52115 if( rc ){
52116 pTrunk = 0;
52117 goto end_allocate_page;
52120 k = get4byte(&pTrunk->aData[4]); /* # of leaves on this trunk page */
52121 if( k==0 && !searchList ){
52122 /* The trunk has no leaves and the list is not being searched.
52123 ** So extract the trunk page itself and use it as the newly
52124 ** allocated page */
52125 assert( pPrevTrunk==0 );
52126 rc = sqlite3PagerWrite(pTrunk->pDbPage);
52127 if( rc ){
52128 goto end_allocate_page;
52130 *pPgno = iTrunk;
52131 memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4);
52132 *ppPage = pTrunk;
52133 pTrunk = 0;
52134 TRACE(("ALLOCATE: %d trunk - %d free pages left\n", *pPgno, n-1));
52135 }else if( k>(u32)(pBt->usableSize/4 - 2) ){
52136 /* Value of k is out of range. Database corruption */
52137 rc = SQLITE_CORRUPT_BKPT;
52138 goto end_allocate_page;
52139 #ifndef SQLITE_OMIT_AUTOVACUUM
52140 }else if( searchList && nearby==iTrunk ){
52141 /* The list is being searched and this trunk page is the page
52142 ** to allocate, regardless of whether it has leaves.
52144 assert( *pPgno==iTrunk );
52145 *ppPage = pTrunk;
52146 searchList = 0;
52147 rc = sqlite3PagerWrite(pTrunk->pDbPage);
52148 if( rc ){
52149 goto end_allocate_page;
52151 if( k==0 ){
52152 if( !pPrevTrunk ){
52153 memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4);
52154 }else{
52155 rc = sqlite3PagerWrite(pPrevTrunk->pDbPage);
52156 if( rc!=SQLITE_OK ){
52157 goto end_allocate_page;
52159 memcpy(&pPrevTrunk->aData[0], &pTrunk->aData[0], 4);
52161 }else{
52162 /* The trunk page is required by the caller but it contains
52163 ** pointers to free-list leaves. The first leaf becomes a trunk
52164 ** page in this case.
52166 MemPage *pNewTrunk;
52167 Pgno iNewTrunk = get4byte(&pTrunk->aData[8]);
52168 if( iNewTrunk>mxPage ){
52169 rc = SQLITE_CORRUPT_BKPT;
52170 goto end_allocate_page;
52172 testcase( iNewTrunk==mxPage );
52173 rc = btreeGetPage(pBt, iNewTrunk, &pNewTrunk, 0);
52174 if( rc!=SQLITE_OK ){
52175 goto end_allocate_page;
52177 rc = sqlite3PagerWrite(pNewTrunk->pDbPage);
52178 if( rc!=SQLITE_OK ){
52179 releasePage(pNewTrunk);
52180 goto end_allocate_page;
52182 memcpy(&pNewTrunk->aData[0], &pTrunk->aData[0], 4);
52183 put4byte(&pNewTrunk->aData[4], k-1);
52184 memcpy(&pNewTrunk->aData[8], &pTrunk->aData[12], (k-1)*4);
52185 releasePage(pNewTrunk);
52186 if( !pPrevTrunk ){
52187 assert( sqlite3PagerIswriteable(pPage1->pDbPage) );
52188 put4byte(&pPage1->aData[32], iNewTrunk);
52189 }else{
52190 rc = sqlite3PagerWrite(pPrevTrunk->pDbPage);
52191 if( rc ){
52192 goto end_allocate_page;
52194 put4byte(&pPrevTrunk->aData[0], iNewTrunk);
52197 pTrunk = 0;
52198 TRACE(("ALLOCATE: %d trunk - %d free pages left\n", *pPgno, n-1));
52199 #endif
52200 }else if( k>0 ){
52201 /* Extract a leaf from the trunk */
52202 u32 closest;
52203 Pgno iPage;
52204 unsigned char *aData = pTrunk->aData;
52205 if( nearby>0 ){
52206 u32 i;
52207 int dist;
52208 closest = 0;
52209 dist = sqlite3AbsInt32(get4byte(&aData[8]) - nearby);
52210 for(i=1; i<k; i++){
52211 int d2 = sqlite3AbsInt32(get4byte(&aData[8+i*4]) - nearby);
52212 if( d2<dist ){
52213 closest = i;
52214 dist = d2;
52217 }else{
52218 closest = 0;
52221 iPage = get4byte(&aData[8+closest*4]);
52222 testcase( iPage==mxPage );
52223 if( iPage>mxPage ){
52224 rc = SQLITE_CORRUPT_BKPT;
52225 goto end_allocate_page;
52227 testcase( iPage==mxPage );
52228 if( !searchList || iPage==nearby ){
52229 int noContent;
52230 *pPgno = iPage;
52231 TRACE(("ALLOCATE: %d was leaf %d of %d on trunk %d"
52232 ": %d more free pages\n",
52233 *pPgno, closest+1, k, pTrunk->pgno, n-1));
52234 rc = sqlite3PagerWrite(pTrunk->pDbPage);
52235 if( rc ) goto end_allocate_page;
52236 if( closest<k-1 ){
52237 memcpy(&aData[8+closest*4], &aData[4+k*4], 4);
52239 put4byte(&aData[4], k-1);
52240 noContent = !btreeGetHasContent(pBt, *pPgno);
52241 rc = btreeGetPage(pBt, *pPgno, ppPage, noContent);
52242 if( rc==SQLITE_OK ){
52243 rc = sqlite3PagerWrite((*ppPage)->pDbPage);
52244 if( rc!=SQLITE_OK ){
52245 releasePage(*ppPage);
52248 searchList = 0;
52251 releasePage(pPrevTrunk);
52252 pPrevTrunk = 0;
52253 }while( searchList );
52254 }else{
52255 /* There are no pages on the freelist, so create a new page at the
52256 ** end of the file */
52257 rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
52258 if( rc ) return rc;
52259 pBt->nPage++;
52260 if( pBt->nPage==PENDING_BYTE_PAGE(pBt) ) pBt->nPage++;
52262 #ifndef SQLITE_OMIT_AUTOVACUUM
52263 if( pBt->autoVacuum && PTRMAP_ISPAGE(pBt, pBt->nPage) ){
52264 /* If *pPgno refers to a pointer-map page, allocate two new pages
52265 ** at the end of the file instead of one. The first allocated page
52266 ** becomes a new pointer-map page, the second is used by the caller.
52268 MemPage *pPg = 0;
52269 TRACE(("ALLOCATE: %d from end of file (pointer-map page)\n", pBt->nPage));
52270 assert( pBt->nPage!=PENDING_BYTE_PAGE(pBt) );
52271 rc = btreeGetPage(pBt, pBt->nPage, &pPg, 1);
52272 if( rc==SQLITE_OK ){
52273 rc = sqlite3PagerWrite(pPg->pDbPage);
52274 releasePage(pPg);
52276 if( rc ) return rc;
52277 pBt->nPage++;
52278 if( pBt->nPage==PENDING_BYTE_PAGE(pBt) ){ pBt->nPage++; }
52280 #endif
52281 put4byte(28 + (u8*)pBt->pPage1->aData, pBt->nPage);
52282 *pPgno = pBt->nPage;
52284 assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );
52285 rc = btreeGetPage(pBt, *pPgno, ppPage, 1);
52286 if( rc ) return rc;
52287 rc = sqlite3PagerWrite((*ppPage)->pDbPage);
52288 if( rc!=SQLITE_OK ){
52289 releasePage(*ppPage);
52291 TRACE(("ALLOCATE: %d from end of file\n", *pPgno));
52294 assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );
52296 end_allocate_page:
52297 releasePage(pTrunk);
52298 releasePage(pPrevTrunk);
52299 if( rc==SQLITE_OK ){
52300 if( sqlite3PagerPageRefcount((*ppPage)->pDbPage)>1 ){
52301 releasePage(*ppPage);
52302 return SQLITE_CORRUPT_BKPT;
52304 (*ppPage)->isInit = 0;
52305 }else{
52306 *ppPage = 0;
52308 assert( rc!=SQLITE_OK || sqlite3PagerIswriteable((*ppPage)->pDbPage) );
52309 return rc;
52313 ** This function is used to add page iPage to the database file free-list.
52314 ** It is assumed that the page is not already a part of the free-list.
52316 ** The value passed as the second argument to this function is optional.
52317 ** If the caller happens to have a pointer to the MemPage object
52318 ** corresponding to page iPage handy, it may pass it as the second value.
52319 ** Otherwise, it may pass NULL.
52321 ** If a pointer to a MemPage object is passed as the second argument,
52322 ** its reference count is not altered by this function.
52324 static int freePage2(BtShared *pBt, MemPage *pMemPage, Pgno iPage){
52325 MemPage *pTrunk = 0; /* Free-list trunk page */
52326 Pgno iTrunk = 0; /* Page number of free-list trunk page */
52327 MemPage *pPage1 = pBt->pPage1; /* Local reference to page 1 */
52328 MemPage *pPage; /* Page being freed. May be NULL. */
52329 int rc; /* Return Code */
52330 int nFree; /* Initial number of pages on free-list */
52332 assert( sqlite3_mutex_held(pBt->mutex) );
52333 assert( iPage>1 );
52334 assert( !pMemPage || pMemPage->pgno==iPage );
52336 if( pMemPage ){
52337 pPage = pMemPage;
52338 sqlite3PagerRef(pPage->pDbPage);
52339 }else{
52340 pPage = btreePageLookup(pBt, iPage);
52343 /* Increment the free page count on pPage1 */
52344 rc = sqlite3PagerWrite(pPage1->pDbPage);
52345 if( rc ) goto freepage_out;
52346 nFree = get4byte(&pPage1->aData[36]);
52347 put4byte(&pPage1->aData[36], nFree+1);
52349 if( pBt->secureDelete ){
52350 /* If the secure_delete option is enabled, then
52351 ** always fully overwrite deleted information with zeros.
52353 if( (!pPage && ((rc = btreeGetPage(pBt, iPage, &pPage, 0))!=0) )
52354 || ((rc = sqlite3PagerWrite(pPage->pDbPage))!=0)
52356 goto freepage_out;
52358 memset(pPage->aData, 0, pPage->pBt->pageSize);
52361 /* If the database supports auto-vacuum, write an entry in the pointer-map
52362 ** to indicate that the page is free.
52364 if( ISAUTOVACUUM ){
52365 ptrmapPut(pBt, iPage, PTRMAP_FREEPAGE, 0, &rc);
52366 if( rc ) goto freepage_out;
52369 /* Now manipulate the actual database free-list structure. There are two
52370 ** possibilities. If the free-list is currently empty, or if the first
52371 ** trunk page in the free-list is full, then this page will become a
52372 ** new free-list trunk page. Otherwise, it will become a leaf of the
52373 ** first trunk page in the current free-list. This block tests if it
52374 ** is possible to add the page as a new free-list leaf.
52376 if( nFree!=0 ){
52377 u32 nLeaf; /* Initial number of leaf cells on trunk page */
52379 iTrunk = get4byte(&pPage1->aData[32]);
52380 rc = btreeGetPage(pBt, iTrunk, &pTrunk, 0);
52381 if( rc!=SQLITE_OK ){
52382 goto freepage_out;
52385 nLeaf = get4byte(&pTrunk->aData[4]);
52386 assert( pBt->usableSize>32 );
52387 if( nLeaf > (u32)pBt->usableSize/4 - 2 ){
52388 rc = SQLITE_CORRUPT_BKPT;
52389 goto freepage_out;
52391 if( nLeaf < (u32)pBt->usableSize/4 - 8 ){
52392 /* In this case there is room on the trunk page to insert the page
52393 ** being freed as a new leaf.
52395 ** Note that the trunk page is not really full until it contains
52396 ** usableSize/4 - 2 entries, not usableSize/4 - 8 entries as we have
52397 ** coded. But due to a coding error in versions of SQLite prior to
52398 ** 3.6.0, databases with freelist trunk pages holding more than
52399 ** usableSize/4 - 8 entries will be reported as corrupt. In order
52400 ** to maintain backwards compatibility with older versions of SQLite,
52401 ** we will continue to restrict the number of entries to usableSize/4 - 8
52402 ** for now. At some point in the future (once everyone has upgraded
52403 ** to 3.6.0 or later) we should consider fixing the conditional above
52404 ** to read "usableSize/4-2" instead of "usableSize/4-8".
52406 rc = sqlite3PagerWrite(pTrunk->pDbPage);
52407 if( rc==SQLITE_OK ){
52408 put4byte(&pTrunk->aData[4], nLeaf+1);
52409 put4byte(&pTrunk->aData[8+nLeaf*4], iPage);
52410 if( pPage && !pBt->secureDelete ){
52411 sqlite3PagerDontWrite(pPage->pDbPage);
52413 rc = btreeSetHasContent(pBt, iPage);
52415 TRACE(("FREE-PAGE: %d leaf on trunk page %d\n",pPage->pgno,pTrunk->pgno));
52416 goto freepage_out;
52420 /* If control flows to this point, then it was not possible to add the
52421 ** the page being freed as a leaf page of the first trunk in the free-list.
52422 ** Possibly because the free-list is empty, or possibly because the
52423 ** first trunk in the free-list is full. Either way, the page being freed
52424 ** will become the new first trunk page in the free-list.
52426 if( pPage==0 && SQLITE_OK!=(rc = btreeGetPage(pBt, iPage, &pPage, 0)) ){
52427 goto freepage_out;
52429 rc = sqlite3PagerWrite(pPage->pDbPage);
52430 if( rc!=SQLITE_OK ){
52431 goto freepage_out;
52433 put4byte(pPage->aData, iTrunk);
52434 put4byte(&pPage->aData[4], 0);
52435 put4byte(&pPage1->aData[32], iPage);
52436 TRACE(("FREE-PAGE: %d new trunk page replacing %d\n", pPage->pgno, iTrunk));
52438 freepage_out:
52439 if( pPage ){
52440 pPage->isInit = 0;
52442 releasePage(pPage);
52443 releasePage(pTrunk);
52444 return rc;
52446 static void freePage(MemPage *pPage, int *pRC){
52447 if( (*pRC)==SQLITE_OK ){
52448 *pRC = freePage2(pPage->pBt, pPage, pPage->pgno);
52453 ** Free any overflow pages associated with the given Cell.
52455 static int clearCell(MemPage *pPage, unsigned char *pCell){
52456 BtShared *pBt = pPage->pBt;
52457 CellInfo info;
52458 Pgno ovflPgno;
52459 int rc;
52460 int nOvfl;
52461 u32 ovflPageSize;
52463 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
52464 btreeParseCellPtr(pPage, pCell, &info);
52465 if( info.iOverflow==0 ){
52466 return SQLITE_OK; /* No overflow pages. Return without doing anything */
52468 ovflPgno = get4byte(&pCell[info.iOverflow]);
52469 assert( pBt->usableSize > 4 );
52470 ovflPageSize = pBt->usableSize - 4;
52471 nOvfl = (info.nPayload - info.nLocal + ovflPageSize - 1)/ovflPageSize;
52472 assert( ovflPgno==0 || nOvfl>0 );
52473 while( nOvfl-- ){
52474 Pgno iNext = 0;
52475 MemPage *pOvfl = 0;
52476 if( ovflPgno<2 || ovflPgno>btreePagecount(pBt) ){
52477 /* 0 is not a legal page number and page 1 cannot be an
52478 ** overflow page. Therefore if ovflPgno<2 or past the end of the
52479 ** file the database must be corrupt. */
52480 return SQLITE_CORRUPT_BKPT;
52482 if( nOvfl ){
52483 rc = getOverflowPage(pBt, ovflPgno, &pOvfl, &iNext);
52484 if( rc ) return rc;
52487 if( ( pOvfl || ((pOvfl = btreePageLookup(pBt, ovflPgno))!=0) )
52488 && sqlite3PagerPageRefcount(pOvfl->pDbPage)!=1
52490 /* There is no reason any cursor should have an outstanding reference
52491 ** to an overflow page belonging to a cell that is being deleted/updated.
52492 ** So if there exists more than one reference to this page, then it
52493 ** must not really be an overflow page and the database must be corrupt.
52494 ** It is helpful to detect this before calling freePage2(), as
52495 ** freePage2() may zero the page contents if secure-delete mode is
52496 ** enabled. If this 'overflow' page happens to be a page that the
52497 ** caller is iterating through or using in some other way, this
52498 ** can be problematic.
52500 rc = SQLITE_CORRUPT_BKPT;
52501 }else{
52502 rc = freePage2(pBt, pOvfl, ovflPgno);
52505 if( pOvfl ){
52506 sqlite3PagerUnref(pOvfl->pDbPage);
52508 if( rc ) return rc;
52509 ovflPgno = iNext;
52511 return SQLITE_OK;
52515 ** Create the byte sequence used to represent a cell on page pPage
52516 ** and write that byte sequence into pCell[]. Overflow pages are
52517 ** allocated and filled in as necessary. The calling procedure
52518 ** is responsible for making sure sufficient space has been allocated
52519 ** for pCell[].
52521 ** Note that pCell does not necessary need to point to the pPage->aData
52522 ** area. pCell might point to some temporary storage. The cell will
52523 ** be constructed in this temporary area then copied into pPage->aData
52524 ** later.
52526 static int fillInCell(
52527 MemPage *pPage, /* The page that contains the cell */
52528 unsigned char *pCell, /* Complete text of the cell */
52529 const void *pKey, i64 nKey, /* The key */
52530 const void *pData,int nData, /* The data */
52531 int nZero, /* Extra zero bytes to append to pData */
52532 int *pnSize /* Write cell size here */
52534 int nPayload;
52535 const u8 *pSrc;
52536 int nSrc, n, rc;
52537 int spaceLeft;
52538 MemPage *pOvfl = 0;
52539 MemPage *pToRelease = 0;
52540 unsigned char *pPrior;
52541 unsigned char *pPayload;
52542 BtShared *pBt = pPage->pBt;
52543 Pgno pgnoOvfl = 0;
52544 int nHeader;
52545 CellInfo info;
52547 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
52549 /* pPage is not necessarily writeable since pCell might be auxiliary
52550 ** buffer space that is separate from the pPage buffer area */
52551 assert( pCell<pPage->aData || pCell>=&pPage->aData[pBt->pageSize]
52552 || sqlite3PagerIswriteable(pPage->pDbPage) );
52554 /* Fill in the header. */
52555 nHeader = 0;
52556 if( !pPage->leaf ){
52557 nHeader += 4;
52559 if( pPage->hasData ){
52560 nHeader += putVarint(&pCell[nHeader], nData+nZero);
52561 }else{
52562 nData = nZero = 0;
52564 nHeader += putVarint(&pCell[nHeader], *(u64*)&nKey);
52565 btreeParseCellPtr(pPage, pCell, &info);
52566 assert( info.nHeader==nHeader );
52567 assert( info.nKey==nKey );
52568 assert( info.nData==(u32)(nData+nZero) );
52570 /* Fill in the payload */
52571 nPayload = nData + nZero;
52572 if( pPage->intKey ){
52573 pSrc = pData;
52574 nSrc = nData;
52575 nData = 0;
52576 }else{
52577 if( NEVER(nKey>0x7fffffff || pKey==0) ){
52578 return SQLITE_CORRUPT_BKPT;
52580 nPayload += (int)nKey;
52581 pSrc = pKey;
52582 nSrc = (int)nKey;
52584 *pnSize = info.nSize;
52585 spaceLeft = info.nLocal;
52586 pPayload = &pCell[nHeader];
52587 pPrior = &pCell[info.iOverflow];
52589 while( nPayload>0 ){
52590 if( spaceLeft==0 ){
52591 #ifndef SQLITE_OMIT_AUTOVACUUM
52592 Pgno pgnoPtrmap = pgnoOvfl; /* Overflow page pointer-map entry page */
52593 if( pBt->autoVacuum ){
52595 pgnoOvfl++;
52596 } while(
52597 PTRMAP_ISPAGE(pBt, pgnoOvfl) || pgnoOvfl==PENDING_BYTE_PAGE(pBt)
52600 #endif
52601 rc = allocateBtreePage(pBt, &pOvfl, &pgnoOvfl, pgnoOvfl, 0);
52602 #ifndef SQLITE_OMIT_AUTOVACUUM
52603 /* If the database supports auto-vacuum, and the second or subsequent
52604 ** overflow page is being allocated, add an entry to the pointer-map
52605 ** for that page now.
52607 ** If this is the first overflow page, then write a partial entry
52608 ** to the pointer-map. If we write nothing to this pointer-map slot,
52609 ** then the optimistic overflow chain processing in clearCell()
52610 ** may misinterpret the uninitialised values and delete the
52611 ** wrong pages from the database.
52613 if( pBt->autoVacuum && rc==SQLITE_OK ){
52614 u8 eType = (pgnoPtrmap?PTRMAP_OVERFLOW2:PTRMAP_OVERFLOW1);
52615 ptrmapPut(pBt, pgnoOvfl, eType, pgnoPtrmap, &rc);
52616 if( rc ){
52617 releasePage(pOvfl);
52620 #endif
52621 if( rc ){
52622 releasePage(pToRelease);
52623 return rc;
52626 /* If pToRelease is not zero than pPrior points into the data area
52627 ** of pToRelease. Make sure pToRelease is still writeable. */
52628 assert( pToRelease==0 || sqlite3PagerIswriteable(pToRelease->pDbPage) );
52630 /* If pPrior is part of the data area of pPage, then make sure pPage
52631 ** is still writeable */
52632 assert( pPrior<pPage->aData || pPrior>=&pPage->aData[pBt->pageSize]
52633 || sqlite3PagerIswriteable(pPage->pDbPage) );
52635 put4byte(pPrior, pgnoOvfl);
52636 releasePage(pToRelease);
52637 pToRelease = pOvfl;
52638 pPrior = pOvfl->aData;
52639 put4byte(pPrior, 0);
52640 pPayload = &pOvfl->aData[4];
52641 spaceLeft = pBt->usableSize - 4;
52643 n = nPayload;
52644 if( n>spaceLeft ) n = spaceLeft;
52646 /* If pToRelease is not zero than pPayload points into the data area
52647 ** of pToRelease. Make sure pToRelease is still writeable. */
52648 assert( pToRelease==0 || sqlite3PagerIswriteable(pToRelease->pDbPage) );
52650 /* If pPayload is part of the data area of pPage, then make sure pPage
52651 ** is still writeable */
52652 assert( pPayload<pPage->aData || pPayload>=&pPage->aData[pBt->pageSize]
52653 || sqlite3PagerIswriteable(pPage->pDbPage) );
52655 if( nSrc>0 ){
52656 if( n>nSrc ) n = nSrc;
52657 assert( pSrc );
52658 memcpy(pPayload, pSrc, n);
52659 }else{
52660 memset(pPayload, 0, n);
52662 nPayload -= n;
52663 pPayload += n;
52664 pSrc += n;
52665 nSrc -= n;
52666 spaceLeft -= n;
52667 if( nSrc==0 ){
52668 nSrc = nData;
52669 pSrc = pData;
52672 releasePage(pToRelease);
52673 return SQLITE_OK;
52677 ** Remove the i-th cell from pPage. This routine effects pPage only.
52678 ** The cell content is not freed or deallocated. It is assumed that
52679 ** the cell content has been copied someplace else. This routine just
52680 ** removes the reference to the cell from pPage.
52682 ** "sz" must be the number of bytes in the cell.
52684 static void dropCell(MemPage *pPage, int idx, int sz, int *pRC){
52685 int i; /* Loop counter */
52686 u32 pc; /* Offset to cell content of cell being deleted */
52687 u8 *data; /* pPage->aData */
52688 u8 *ptr; /* Used to move bytes around within data[] */
52689 int rc; /* The return code */
52690 int hdr; /* Beginning of the header. 0 most pages. 100 page 1 */
52692 if( *pRC ) return;
52694 assert( idx>=0 && idx<pPage->nCell );
52695 assert( sz==cellSize(pPage, idx) );
52696 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
52697 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
52698 data = pPage->aData;
52699 ptr = &data[pPage->cellOffset + 2*idx];
52700 pc = get2byte(ptr);
52701 hdr = pPage->hdrOffset;
52702 testcase( pc==get2byte(&data[hdr+5]) );
52703 testcase( pc+sz==pPage->pBt->usableSize );
52704 if( pc < (u32)get2byte(&data[hdr+5]) || pc+sz > pPage->pBt->usableSize ){
52705 *pRC = SQLITE_CORRUPT_BKPT;
52706 return;
52708 rc = freeSpace(pPage, pc, sz);
52709 if( rc ){
52710 *pRC = rc;
52711 return;
52713 for(i=idx+1; i<pPage->nCell; i++, ptr+=2){
52714 ptr[0] = ptr[2];
52715 ptr[1] = ptr[3];
52717 pPage->nCell--;
52718 put2byte(&data[hdr+3], pPage->nCell);
52719 pPage->nFree += 2;
52723 ** Insert a new cell on pPage at cell index "i". pCell points to the
52724 ** content of the cell.
52726 ** If the cell content will fit on the page, then put it there. If it
52727 ** will not fit, then make a copy of the cell content into pTemp if
52728 ** pTemp is not null. Regardless of pTemp, allocate a new entry
52729 ** in pPage->aOvfl[] and make it point to the cell content (either
52730 ** in pTemp or the original pCell) and also record its index.
52731 ** Allocating a new entry in pPage->aCell[] implies that
52732 ** pPage->nOverflow is incremented.
52734 ** If nSkip is non-zero, then do not copy the first nSkip bytes of the
52735 ** cell. The caller will overwrite them after this function returns. If
52736 ** nSkip is non-zero, then pCell may not point to an invalid memory location
52737 ** (but pCell+nSkip is always valid).
52739 static void insertCell(
52740 MemPage *pPage, /* Page into which we are copying */
52741 int i, /* New cell becomes the i-th cell of the page */
52742 u8 *pCell, /* Content of the new cell */
52743 int sz, /* Bytes of content in pCell */
52744 u8 *pTemp, /* Temp storage space for pCell, if needed */
52745 Pgno iChild, /* If non-zero, replace first 4 bytes with this value */
52746 int *pRC /* Read and write return code from here */
52748 int idx = 0; /* Where to write new cell content in data[] */
52749 int j; /* Loop counter */
52750 int end; /* First byte past the last cell pointer in data[] */
52751 int ins; /* Index in data[] where new cell pointer is inserted */
52752 int cellOffset; /* Address of first cell pointer in data[] */
52753 u8 *data; /* The content of the whole page */
52754 u8 *ptr; /* Used for moving information around in data[] */
52756 int nSkip = (iChild ? 4 : 0);
52758 if( *pRC ) return;
52760 assert( i>=0 && i<=pPage->nCell+pPage->nOverflow );
52761 assert( pPage->nCell<=MX_CELL(pPage->pBt) && MX_CELL(pPage->pBt)<=10921 );
52762 assert( pPage->nOverflow<=ArraySize(pPage->aOvfl) );
52763 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
52764 /* The cell should normally be sized correctly. However, when moving a
52765 ** malformed cell from a leaf page to an interior page, if the cell size
52766 ** wanted to be less than 4 but got rounded up to 4 on the leaf, then size
52767 ** might be less than 8 (leaf-size + pointer) on the interior node. Hence
52768 ** the term after the || in the following assert(). */
52769 assert( sz==cellSizePtr(pPage, pCell) || (sz==8 && iChild>0) );
52770 if( pPage->nOverflow || sz+2>pPage->nFree ){
52771 if( pTemp ){
52772 memcpy(pTemp+nSkip, pCell+nSkip, sz-nSkip);
52773 pCell = pTemp;
52775 if( iChild ){
52776 put4byte(pCell, iChild);
52778 j = pPage->nOverflow++;
52779 assert( j<(int)(sizeof(pPage->aOvfl)/sizeof(pPage->aOvfl[0])) );
52780 pPage->aOvfl[j].pCell = pCell;
52781 pPage->aOvfl[j].idx = (u16)i;
52782 }else{
52783 int rc = sqlite3PagerWrite(pPage->pDbPage);
52784 if( rc!=SQLITE_OK ){
52785 *pRC = rc;
52786 return;
52788 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
52789 data = pPage->aData;
52790 cellOffset = pPage->cellOffset;
52791 end = cellOffset + 2*pPage->nCell;
52792 ins = cellOffset + 2*i;
52793 rc = allocateSpace(pPage, sz, &idx);
52794 if( rc ){ *pRC = rc; return; }
52795 /* The allocateSpace() routine guarantees the following two properties
52796 ** if it returns success */
52797 assert( idx >= end+2 );
52798 assert( idx+sz <= (int)pPage->pBt->usableSize );
52799 pPage->nCell++;
52800 pPage->nFree -= (u16)(2 + sz);
52801 memcpy(&data[idx+nSkip], pCell+nSkip, sz-nSkip);
52802 if( iChild ){
52803 put4byte(&data[idx], iChild);
52805 for(j=end, ptr=&data[j]; j>ins; j-=2, ptr-=2){
52806 ptr[0] = ptr[-2];
52807 ptr[1] = ptr[-1];
52809 put2byte(&data[ins], idx);
52810 put2byte(&data[pPage->hdrOffset+3], pPage->nCell);
52811 #ifndef SQLITE_OMIT_AUTOVACUUM
52812 if( pPage->pBt->autoVacuum ){
52813 /* The cell may contain a pointer to an overflow page. If so, write
52814 ** the entry for the overflow page into the pointer map.
52816 ptrmapPutOvflPtr(pPage, pCell, pRC);
52818 #endif
52823 ** Add a list of cells to a page. The page should be initially empty.
52824 ** The cells are guaranteed to fit on the page.
52826 static void assemblePage(
52827 MemPage *pPage, /* The page to be assemblied */
52828 int nCell, /* The number of cells to add to this page */
52829 u8 **apCell, /* Pointers to cell bodies */
52830 u16 *aSize /* Sizes of the cells */
52832 int i; /* Loop counter */
52833 u8 *pCellptr; /* Address of next cell pointer */
52834 int cellbody; /* Address of next cell body */
52835 u8 * const data = pPage->aData; /* Pointer to data for pPage */
52836 const int hdr = pPage->hdrOffset; /* Offset of header on pPage */
52837 const int nUsable = pPage->pBt->usableSize; /* Usable size of page */
52839 assert( pPage->nOverflow==0 );
52840 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
52841 assert( nCell>=0 && nCell<=(int)MX_CELL(pPage->pBt)
52842 && (int)MX_CELL(pPage->pBt)<=10921);
52843 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
52845 /* Check that the page has just been zeroed by zeroPage() */
52846 assert( pPage->nCell==0 );
52847 assert( get2byteNotZero(&data[hdr+5])==nUsable );
52849 pCellptr = &data[pPage->cellOffset + nCell*2];
52850 cellbody = nUsable;
52851 for(i=nCell-1; i>=0; i--){
52852 pCellptr -= 2;
52853 cellbody -= aSize[i];
52854 put2byte(pCellptr, cellbody);
52855 memcpy(&data[cellbody], apCell[i], aSize[i]);
52857 put2byte(&data[hdr+3], nCell);
52858 put2byte(&data[hdr+5], cellbody);
52859 pPage->nFree -= (nCell*2 + nUsable - cellbody);
52860 pPage->nCell = (u16)nCell;
52864 ** The following parameters determine how many adjacent pages get involved
52865 ** in a balancing operation. NN is the number of neighbors on either side
52866 ** of the page that participate in the balancing operation. NB is the
52867 ** total number of pages that participate, including the target page and
52868 ** NN neighbors on either side.
52870 ** The minimum value of NN is 1 (of course). Increasing NN above 1
52871 ** (to 2 or 3) gives a modest improvement in SELECT and DELETE performance
52872 ** in exchange for a larger degradation in INSERT and UPDATE performance.
52873 ** The value of NN appears to give the best results overall.
52875 #define NN 1 /* Number of neighbors on either side of pPage */
52876 #define NB (NN*2+1) /* Total pages involved in the balance */
52879 #ifndef SQLITE_OMIT_QUICKBALANCE
52881 ** This version of balance() handles the common special case where
52882 ** a new entry is being inserted on the extreme right-end of the
52883 ** tree, in other words, when the new entry will become the largest
52884 ** entry in the tree.
52886 ** Instead of trying to balance the 3 right-most leaf pages, just add
52887 ** a new page to the right-hand side and put the one new entry in
52888 ** that page. This leaves the right side of the tree somewhat
52889 ** unbalanced. But odds are that we will be inserting new entries
52890 ** at the end soon afterwards so the nearly empty page will quickly
52891 ** fill up. On average.
52893 ** pPage is the leaf page which is the right-most page in the tree.
52894 ** pParent is its parent. pPage must have a single overflow entry
52895 ** which is also the right-most entry on the page.
52897 ** The pSpace buffer is used to store a temporary copy of the divider
52898 ** cell that will be inserted into pParent. Such a cell consists of a 4
52899 ** byte page number followed by a variable length integer. In other
52900 ** words, at most 13 bytes. Hence the pSpace buffer must be at
52901 ** least 13 bytes in size.
52903 static int balance_quick(MemPage *pParent, MemPage *pPage, u8 *pSpace){
52904 BtShared *const pBt = pPage->pBt; /* B-Tree Database */
52905 MemPage *pNew; /* Newly allocated page */
52906 int rc; /* Return Code */
52907 Pgno pgnoNew; /* Page number of pNew */
52909 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
52910 assert( sqlite3PagerIswriteable(pParent->pDbPage) );
52911 assert( pPage->nOverflow==1 );
52913 /* This error condition is now caught prior to reaching this function */
52914 if( pPage->nCell<=0 ) return SQLITE_CORRUPT_BKPT;
52916 /* Allocate a new page. This page will become the right-sibling of
52917 ** pPage. Make the parent page writable, so that the new divider cell
52918 ** may be inserted. If both these operations are successful, proceed.
52920 rc = allocateBtreePage(pBt, &pNew, &pgnoNew, 0, 0);
52922 if( rc==SQLITE_OK ){
52924 u8 *pOut = &pSpace[4];
52925 u8 *pCell = pPage->aOvfl[0].pCell;
52926 u16 szCell = cellSizePtr(pPage, pCell);
52927 u8 *pStop;
52929 assert( sqlite3PagerIswriteable(pNew->pDbPage) );
52930 assert( pPage->aData[0]==(PTF_INTKEY|PTF_LEAFDATA|PTF_LEAF) );
52931 zeroPage(pNew, PTF_INTKEY|PTF_LEAFDATA|PTF_LEAF);
52932 assemblePage(pNew, 1, &pCell, &szCell);
52934 /* If this is an auto-vacuum database, update the pointer map
52935 ** with entries for the new page, and any pointer from the
52936 ** cell on the page to an overflow page. If either of these
52937 ** operations fails, the return code is set, but the contents
52938 ** of the parent page are still manipulated by thh code below.
52939 ** That is Ok, at this point the parent page is guaranteed to
52940 ** be marked as dirty. Returning an error code will cause a
52941 ** rollback, undoing any changes made to the parent page.
52943 if( ISAUTOVACUUM ){
52944 ptrmapPut(pBt, pgnoNew, PTRMAP_BTREE, pParent->pgno, &rc);
52945 if( szCell>pNew->minLocal ){
52946 ptrmapPutOvflPtr(pNew, pCell, &rc);
52950 /* Create a divider cell to insert into pParent. The divider cell
52951 ** consists of a 4-byte page number (the page number of pPage) and
52952 ** a variable length key value (which must be the same value as the
52953 ** largest key on pPage).
52955 ** To find the largest key value on pPage, first find the right-most
52956 ** cell on pPage. The first two fields of this cell are the
52957 ** record-length (a variable length integer at most 32-bits in size)
52958 ** and the key value (a variable length integer, may have any value).
52959 ** The first of the while(...) loops below skips over the record-length
52960 ** field. The second while(...) loop copies the key value from the
52961 ** cell on pPage into the pSpace buffer.
52963 pCell = findCell(pPage, pPage->nCell-1);
52964 pStop = &pCell[9];
52965 while( (*(pCell++)&0x80) && pCell<pStop );
52966 pStop = &pCell[9];
52967 while( ((*(pOut++) = *(pCell++))&0x80) && pCell<pStop );
52969 /* Insert the new divider cell into pParent. */
52970 insertCell(pParent, pParent->nCell, pSpace, (int)(pOut-pSpace),
52971 0, pPage->pgno, &rc);
52973 /* Set the right-child pointer of pParent to point to the new page. */
52974 put4byte(&pParent->aData[pParent->hdrOffset+8], pgnoNew);
52976 /* Release the reference to the new page. */
52977 releasePage(pNew);
52980 return rc;
52982 #endif /* SQLITE_OMIT_QUICKBALANCE */
52984 #if 0
52986 ** This function does not contribute anything to the operation of SQLite.
52987 ** it is sometimes activated temporarily while debugging code responsible
52988 ** for setting pointer-map entries.
52990 static int ptrmapCheckPages(MemPage **apPage, int nPage){
52991 int i, j;
52992 for(i=0; i<nPage; i++){
52993 Pgno n;
52994 u8 e;
52995 MemPage *pPage = apPage[i];
52996 BtShared *pBt = pPage->pBt;
52997 assert( pPage->isInit );
52999 for(j=0; j<pPage->nCell; j++){
53000 CellInfo info;
53001 u8 *z;
53003 z = findCell(pPage, j);
53004 btreeParseCellPtr(pPage, z, &info);
53005 if( info.iOverflow ){
53006 Pgno ovfl = get4byte(&z[info.iOverflow]);
53007 ptrmapGet(pBt, ovfl, &e, &n);
53008 assert( n==pPage->pgno && e==PTRMAP_OVERFLOW1 );
53010 if( !pPage->leaf ){
53011 Pgno child = get4byte(z);
53012 ptrmapGet(pBt, child, &e, &n);
53013 assert( n==pPage->pgno && e==PTRMAP_BTREE );
53016 if( !pPage->leaf ){
53017 Pgno child = get4byte(&pPage->aData[pPage->hdrOffset+8]);
53018 ptrmapGet(pBt, child, &e, &n);
53019 assert( n==pPage->pgno && e==PTRMAP_BTREE );
53022 return 1;
53024 #endif
53027 ** This function is used to copy the contents of the b-tree node stored
53028 ** on page pFrom to page pTo. If page pFrom was not a leaf page, then
53029 ** the pointer-map entries for each child page are updated so that the
53030 ** parent page stored in the pointer map is page pTo. If pFrom contained
53031 ** any cells with overflow page pointers, then the corresponding pointer
53032 ** map entries are also updated so that the parent page is page pTo.
53034 ** If pFrom is currently carrying any overflow cells (entries in the
53035 ** MemPage.aOvfl[] array), they are not copied to pTo.
53037 ** Before returning, page pTo is reinitialized using btreeInitPage().
53039 ** The performance of this function is not critical. It is only used by
53040 ** the balance_shallower() and balance_deeper() procedures, neither of
53041 ** which are called often under normal circumstances.
53043 static void copyNodeContent(MemPage *pFrom, MemPage *pTo, int *pRC){
53044 if( (*pRC)==SQLITE_OK ){
53045 BtShared * const pBt = pFrom->pBt;
53046 u8 * const aFrom = pFrom->aData;
53047 u8 * const aTo = pTo->aData;
53048 int const iFromHdr = pFrom->hdrOffset;
53049 int const iToHdr = ((pTo->pgno==1) ? 100 : 0);
53050 int rc;
53051 int iData;
53054 assert( pFrom->isInit );
53055 assert( pFrom->nFree>=iToHdr );
53056 assert( get2byte(&aFrom[iFromHdr+5]) <= (int)pBt->usableSize );
53058 /* Copy the b-tree node content from page pFrom to page pTo. */
53059 iData = get2byte(&aFrom[iFromHdr+5]);
53060 memcpy(&aTo[iData], &aFrom[iData], pBt->usableSize-iData);
53061 memcpy(&aTo[iToHdr], &aFrom[iFromHdr], pFrom->cellOffset + 2*pFrom->nCell);
53063 /* Reinitialize page pTo so that the contents of the MemPage structure
53064 ** match the new data. The initialization of pTo can actually fail under
53065 ** fairly obscure circumstances, even though it is a copy of initialized
53066 ** page pFrom.
53068 pTo->isInit = 0;
53069 rc = btreeInitPage(pTo);
53070 if( rc!=SQLITE_OK ){
53071 *pRC = rc;
53072 return;
53075 /* If this is an auto-vacuum database, update the pointer-map entries
53076 ** for any b-tree or overflow pages that pTo now contains the pointers to.
53078 if( ISAUTOVACUUM ){
53079 *pRC = setChildPtrmaps(pTo);
53085 ** This routine redistributes cells on the iParentIdx'th child of pParent
53086 ** (hereafter "the page") and up to 2 siblings so that all pages have about the
53087 ** same amount of free space. Usually a single sibling on either side of the
53088 ** page are used in the balancing, though both siblings might come from one
53089 ** side if the page is the first or last child of its parent. If the page
53090 ** has fewer than 2 siblings (something which can only happen if the page
53091 ** is a root page or a child of a root page) then all available siblings
53092 ** participate in the balancing.
53094 ** The number of siblings of the page might be increased or decreased by
53095 ** one or two in an effort to keep pages nearly full but not over full.
53097 ** Note that when this routine is called, some of the cells on the page
53098 ** might not actually be stored in MemPage.aData[]. This can happen
53099 ** if the page is overfull. This routine ensures that all cells allocated
53100 ** to the page and its siblings fit into MemPage.aData[] before returning.
53102 ** In the course of balancing the page and its siblings, cells may be
53103 ** inserted into or removed from the parent page (pParent). Doing so
53104 ** may cause the parent page to become overfull or underfull. If this
53105 ** happens, it is the responsibility of the caller to invoke the correct
53106 ** balancing routine to fix this problem (see the balance() routine).
53108 ** If this routine fails for any reason, it might leave the database
53109 ** in a corrupted state. So if this routine fails, the database should
53110 ** be rolled back.
53112 ** The third argument to this function, aOvflSpace, is a pointer to a
53113 ** buffer big enough to hold one page. If while inserting cells into the parent
53114 ** page (pParent) the parent page becomes overfull, this buffer is
53115 ** used to store the parent's overflow cells. Because this function inserts
53116 ** a maximum of four divider cells into the parent page, and the maximum
53117 ** size of a cell stored within an internal node is always less than 1/4
53118 ** of the page-size, the aOvflSpace[] buffer is guaranteed to be large
53119 ** enough for all overflow cells.
53121 ** If aOvflSpace is set to a null pointer, this function returns
53122 ** SQLITE_NOMEM.
53124 static int balance_nonroot(
53125 MemPage *pParent, /* Parent page of siblings being balanced */
53126 int iParentIdx, /* Index of "the page" in pParent */
53127 u8 *aOvflSpace, /* page-size bytes of space for parent ovfl */
53128 int isRoot /* True if pParent is a root-page */
53130 BtShared *pBt; /* The whole database */
53131 int nCell = 0; /* Number of cells in apCell[] */
53132 int nMaxCells = 0; /* Allocated size of apCell, szCell, aFrom. */
53133 int nNew = 0; /* Number of pages in apNew[] */
53134 int nOld; /* Number of pages in apOld[] */
53135 int i, j, k; /* Loop counters */
53136 int nxDiv; /* Next divider slot in pParent->aCell[] */
53137 int rc = SQLITE_OK; /* The return code */
53138 u16 leafCorrection; /* 4 if pPage is a leaf. 0 if not */
53139 int leafData; /* True if pPage is a leaf of a LEAFDATA tree */
53140 int usableSpace; /* Bytes in pPage beyond the header */
53141 int pageFlags; /* Value of pPage->aData[0] */
53142 int subtotal; /* Subtotal of bytes in cells on one page */
53143 int iSpace1 = 0; /* First unused byte of aSpace1[] */
53144 int iOvflSpace = 0; /* First unused byte of aOvflSpace[] */
53145 int szScratch; /* Size of scratch memory requested */
53146 MemPage *apOld[NB]; /* pPage and up to two siblings */
53147 MemPage *apCopy[NB]; /* Private copies of apOld[] pages */
53148 MemPage *apNew[NB+2]; /* pPage and up to NB siblings after balancing */
53149 u8 *pRight; /* Location in parent of right-sibling pointer */
53150 u8 *apDiv[NB-1]; /* Divider cells in pParent */
53151 int cntNew[NB+2]; /* Index in aCell[] of cell after i-th page */
53152 int szNew[NB+2]; /* Combined size of cells place on i-th page */
53153 u8 **apCell = 0; /* All cells begin balanced */
53154 u16 *szCell; /* Local size of all cells in apCell[] */
53155 u8 *aSpace1; /* Space for copies of dividers cells */
53156 Pgno pgno; /* Temp var to store a page number in */
53158 pBt = pParent->pBt;
53159 assert( sqlite3_mutex_held(pBt->mutex) );
53160 assert( sqlite3PagerIswriteable(pParent->pDbPage) );
53162 #if 0
53163 TRACE(("BALANCE: begin page %d child of %d\n", pPage->pgno, pParent->pgno));
53164 #endif
53166 /* At this point pParent may have at most one overflow cell. And if
53167 ** this overflow cell is present, it must be the cell with
53168 ** index iParentIdx. This scenario comes about when this function
53169 ** is called (indirectly) from sqlite3BtreeDelete().
53171 assert( pParent->nOverflow==0 || pParent->nOverflow==1 );
53172 assert( pParent->nOverflow==0 || pParent->aOvfl[0].idx==iParentIdx );
53174 if( !aOvflSpace ){
53175 return SQLITE_NOMEM;
53178 /* Find the sibling pages to balance. Also locate the cells in pParent
53179 ** that divide the siblings. An attempt is made to find NN siblings on
53180 ** either side of pPage. More siblings are taken from one side, however,
53181 ** if there are fewer than NN siblings on the other side. If pParent
53182 ** has NB or fewer children then all children of pParent are taken.
53184 ** This loop also drops the divider cells from the parent page. This
53185 ** way, the remainder of the function does not have to deal with any
53186 ** overflow cells in the parent page, since if any existed they will
53187 ** have already been removed.
53189 i = pParent->nOverflow + pParent->nCell;
53190 if( i<2 ){
53191 nxDiv = 0;
53192 nOld = i+1;
53193 }else{
53194 nOld = 3;
53195 if( iParentIdx==0 ){
53196 nxDiv = 0;
53197 }else if( iParentIdx==i ){
53198 nxDiv = i-2;
53199 }else{
53200 nxDiv = iParentIdx-1;
53202 i = 2;
53204 if( (i+nxDiv-pParent->nOverflow)==pParent->nCell ){
53205 pRight = &pParent->aData[pParent->hdrOffset+8];
53206 }else{
53207 pRight = findCell(pParent, i+nxDiv-pParent->nOverflow);
53209 pgno = get4byte(pRight);
53210 while( 1 ){
53211 rc = getAndInitPage(pBt, pgno, &apOld[i]);
53212 if( rc ){
53213 memset(apOld, 0, (i+1)*sizeof(MemPage*));
53214 goto balance_cleanup;
53216 nMaxCells += 1+apOld[i]->nCell+apOld[i]->nOverflow;
53217 if( (i--)==0 ) break;
53219 if( i+nxDiv==pParent->aOvfl[0].idx && pParent->nOverflow ){
53220 apDiv[i] = pParent->aOvfl[0].pCell;
53221 pgno = get4byte(apDiv[i]);
53222 szNew[i] = cellSizePtr(pParent, apDiv[i]);
53223 pParent->nOverflow = 0;
53224 }else{
53225 apDiv[i] = findCell(pParent, i+nxDiv-pParent->nOverflow);
53226 pgno = get4byte(apDiv[i]);
53227 szNew[i] = cellSizePtr(pParent, apDiv[i]);
53229 /* Drop the cell from the parent page. apDiv[i] still points to
53230 ** the cell within the parent, even though it has been dropped.
53231 ** This is safe because dropping a cell only overwrites the first
53232 ** four bytes of it, and this function does not need the first
53233 ** four bytes of the divider cell. So the pointer is safe to use
53234 ** later on.
53236 ** Unless SQLite is compiled in secure-delete mode. In this case,
53237 ** the dropCell() routine will overwrite the entire cell with zeroes.
53238 ** In this case, temporarily copy the cell into the aOvflSpace[]
53239 ** buffer. It will be copied out again as soon as the aSpace[] buffer
53240 ** is allocated. */
53241 if( pBt->secureDelete ){
53242 int iOff = SQLITE_PTR_TO_INT(apDiv[i]) - SQLITE_PTR_TO_INT(pParent->aData);
53243 if( (iOff+szNew[i])>(int)pBt->usableSize ){
53244 rc = SQLITE_CORRUPT_BKPT;
53245 memset(apOld, 0, (i+1)*sizeof(MemPage*));
53246 goto balance_cleanup;
53247 }else{
53248 memcpy(&aOvflSpace[iOff], apDiv[i], szNew[i]);
53249 apDiv[i] = &aOvflSpace[apDiv[i]-pParent->aData];
53252 dropCell(pParent, i+nxDiv-pParent->nOverflow, szNew[i], &rc);
53256 /* Make nMaxCells a multiple of 4 in order to preserve 8-byte
53257 ** alignment */
53258 nMaxCells = (nMaxCells + 3)&~3;
53261 ** Allocate space for memory structures
53263 k = pBt->pageSize + ROUND8(sizeof(MemPage));
53264 szScratch =
53265 nMaxCells*sizeof(u8*) /* apCell */
53266 + nMaxCells*sizeof(u16) /* szCell */
53267 + pBt->pageSize /* aSpace1 */
53268 + k*nOld; /* Page copies (apCopy) */
53269 apCell = sqlite3ScratchMalloc( szScratch );
53270 if( apCell==0 ){
53271 rc = SQLITE_NOMEM;
53272 goto balance_cleanup;
53274 szCell = (u16*)&apCell[nMaxCells];
53275 aSpace1 = (u8*)&szCell[nMaxCells];
53276 assert( EIGHT_BYTE_ALIGNMENT(aSpace1) );
53279 ** Load pointers to all cells on sibling pages and the divider cells
53280 ** into the local apCell[] array. Make copies of the divider cells
53281 ** into space obtained from aSpace1[] and remove the the divider Cells
53282 ** from pParent.
53284 ** If the siblings are on leaf pages, then the child pointers of the
53285 ** divider cells are stripped from the cells before they are copied
53286 ** into aSpace1[]. In this way, all cells in apCell[] are without
53287 ** child pointers. If siblings are not leaves, then all cell in
53288 ** apCell[] include child pointers. Either way, all cells in apCell[]
53289 ** are alike.
53291 ** leafCorrection: 4 if pPage is a leaf. 0 if pPage is not a leaf.
53292 ** leafData: 1 if pPage holds key+data and pParent holds only keys.
53294 leafCorrection = apOld[0]->leaf*4;
53295 leafData = apOld[0]->hasData;
53296 for(i=0; i<nOld; i++){
53297 int limit;
53299 /* Before doing anything else, take a copy of the i'th original sibling
53300 ** The rest of this function will use data from the copies rather
53301 ** that the original pages since the original pages will be in the
53302 ** process of being overwritten. */
53303 MemPage *pOld = apCopy[i] = (MemPage*)&aSpace1[pBt->pageSize + k*i];
53304 memcpy(pOld, apOld[i], sizeof(MemPage));
53305 pOld->aData = (void*)&pOld[1];
53306 memcpy(pOld->aData, apOld[i]->aData, pBt->pageSize);
53308 limit = pOld->nCell+pOld->nOverflow;
53309 for(j=0; j<limit; j++){
53310 assert( nCell<nMaxCells );
53311 apCell[nCell] = findOverflowCell(pOld, j);
53312 szCell[nCell] = cellSizePtr(pOld, apCell[nCell]);
53313 nCell++;
53315 if( i<nOld-1 && !leafData){
53316 u16 sz = (u16)szNew[i];
53317 u8 *pTemp;
53318 assert( nCell<nMaxCells );
53319 szCell[nCell] = sz;
53320 pTemp = &aSpace1[iSpace1];
53321 iSpace1 += sz;
53322 assert( sz<=pBt->maxLocal+23 );
53323 assert( iSpace1 <= (int)pBt->pageSize );
53324 memcpy(pTemp, apDiv[i], sz);
53325 apCell[nCell] = pTemp+leafCorrection;
53326 assert( leafCorrection==0 || leafCorrection==4 );
53327 szCell[nCell] = szCell[nCell] - leafCorrection;
53328 if( !pOld->leaf ){
53329 assert( leafCorrection==0 );
53330 assert( pOld->hdrOffset==0 );
53331 /* The right pointer of the child page pOld becomes the left
53332 ** pointer of the divider cell */
53333 memcpy(apCell[nCell], &pOld->aData[8], 4);
53334 }else{
53335 assert( leafCorrection==4 );
53336 if( szCell[nCell]<4 ){
53337 /* Do not allow any cells smaller than 4 bytes. */
53338 szCell[nCell] = 4;
53341 nCell++;
53346 ** Figure out the number of pages needed to hold all nCell cells.
53347 ** Store this number in "k". Also compute szNew[] which is the total
53348 ** size of all cells on the i-th page and cntNew[] which is the index
53349 ** in apCell[] of the cell that divides page i from page i+1.
53350 ** cntNew[k] should equal nCell.
53352 ** Values computed by this block:
53354 ** k: The total number of sibling pages
53355 ** szNew[i]: Spaced used on the i-th sibling page.
53356 ** cntNew[i]: Index in apCell[] and szCell[] for the first cell to
53357 ** the right of the i-th sibling page.
53358 ** usableSpace: Number of bytes of space available on each sibling.
53361 usableSpace = pBt->usableSize - 12 + leafCorrection;
53362 for(subtotal=k=i=0; i<nCell; i++){
53363 assert( i<nMaxCells );
53364 subtotal += szCell[i] + 2;
53365 if( subtotal > usableSpace ){
53366 szNew[k] = subtotal - szCell[i];
53367 cntNew[k] = i;
53368 if( leafData ){ i--; }
53369 subtotal = 0;
53370 k++;
53371 if( k>NB+1 ){ rc = SQLITE_CORRUPT_BKPT; goto balance_cleanup; }
53374 szNew[k] = subtotal;
53375 cntNew[k] = nCell;
53376 k++;
53379 ** The packing computed by the previous block is biased toward the siblings
53380 ** on the left side. The left siblings are always nearly full, while the
53381 ** right-most sibling might be nearly empty. This block of code attempts
53382 ** to adjust the packing of siblings to get a better balance.
53384 ** This adjustment is more than an optimization. The packing above might
53385 ** be so out of balance as to be illegal. For example, the right-most
53386 ** sibling might be completely empty. This adjustment is not optional.
53388 for(i=k-1; i>0; i--){
53389 int szRight = szNew[i]; /* Size of sibling on the right */
53390 int szLeft = szNew[i-1]; /* Size of sibling on the left */
53391 int r; /* Index of right-most cell in left sibling */
53392 int d; /* Index of first cell to the left of right sibling */
53394 r = cntNew[i-1] - 1;
53395 d = r + 1 - leafData;
53396 assert( d<nMaxCells );
53397 assert( r<nMaxCells );
53398 while( szRight==0 || szRight+szCell[d]+2<=szLeft-(szCell[r]+2) ){
53399 szRight += szCell[d] + 2;
53400 szLeft -= szCell[r] + 2;
53401 cntNew[i-1]--;
53402 r = cntNew[i-1] - 1;
53403 d = r + 1 - leafData;
53405 szNew[i] = szRight;
53406 szNew[i-1] = szLeft;
53409 /* Either we found one or more cells (cntnew[0])>0) or pPage is
53410 ** a virtual root page. A virtual root page is when the real root
53411 ** page is page 1 and we are the only child of that page.
53413 assert( cntNew[0]>0 || (pParent->pgno==1 && pParent->nCell==0) );
53415 TRACE(("BALANCE: old: %d %d %d ",
53416 apOld[0]->pgno,
53417 nOld>=2 ? apOld[1]->pgno : 0,
53418 nOld>=3 ? apOld[2]->pgno : 0
53422 ** Allocate k new pages. Reuse old pages where possible.
53424 if( apOld[0]->pgno<=1 ){
53425 rc = SQLITE_CORRUPT_BKPT;
53426 goto balance_cleanup;
53428 pageFlags = apOld[0]->aData[0];
53429 for(i=0; i<k; i++){
53430 MemPage *pNew;
53431 if( i<nOld ){
53432 pNew = apNew[i] = apOld[i];
53433 apOld[i] = 0;
53434 rc = sqlite3PagerWrite(pNew->pDbPage);
53435 nNew++;
53436 if( rc ) goto balance_cleanup;
53437 }else{
53438 assert( i>0 );
53439 rc = allocateBtreePage(pBt, &pNew, &pgno, pgno, 0);
53440 if( rc ) goto balance_cleanup;
53441 apNew[i] = pNew;
53442 nNew++;
53444 /* Set the pointer-map entry for the new sibling page. */
53445 if( ISAUTOVACUUM ){
53446 ptrmapPut(pBt, pNew->pgno, PTRMAP_BTREE, pParent->pgno, &rc);
53447 if( rc!=SQLITE_OK ){
53448 goto balance_cleanup;
53454 /* Free any old pages that were not reused as new pages.
53456 while( i<nOld ){
53457 freePage(apOld[i], &rc);
53458 if( rc ) goto balance_cleanup;
53459 releasePage(apOld[i]);
53460 apOld[i] = 0;
53461 i++;
53465 ** Put the new pages in accending order. This helps to
53466 ** keep entries in the disk file in order so that a scan
53467 ** of the table is a linear scan through the file. That
53468 ** in turn helps the operating system to deliver pages
53469 ** from the disk more rapidly.
53471 ** An O(n^2) insertion sort algorithm is used, but since
53472 ** n is never more than NB (a small constant), that should
53473 ** not be a problem.
53475 ** When NB==3, this one optimization makes the database
53476 ** about 25% faster for large insertions and deletions.
53478 for(i=0; i<k-1; i++){
53479 int minV = apNew[i]->pgno;
53480 int minI = i;
53481 for(j=i+1; j<k; j++){
53482 if( apNew[j]->pgno<(unsigned)minV ){
53483 minI = j;
53484 minV = apNew[j]->pgno;
53487 if( minI>i ){
53488 MemPage *pT;
53489 pT = apNew[i];
53490 apNew[i] = apNew[minI];
53491 apNew[minI] = pT;
53494 TRACE(("new: %d(%d) %d(%d) %d(%d) %d(%d) %d(%d)\n",
53495 apNew[0]->pgno, szNew[0],
53496 nNew>=2 ? apNew[1]->pgno : 0, nNew>=2 ? szNew[1] : 0,
53497 nNew>=3 ? apNew[2]->pgno : 0, nNew>=3 ? szNew[2] : 0,
53498 nNew>=4 ? apNew[3]->pgno : 0, nNew>=4 ? szNew[3] : 0,
53499 nNew>=5 ? apNew[4]->pgno : 0, nNew>=5 ? szNew[4] : 0));
53501 assert( sqlite3PagerIswriteable(pParent->pDbPage) );
53502 put4byte(pRight, apNew[nNew-1]->pgno);
53505 ** Evenly distribute the data in apCell[] across the new pages.
53506 ** Insert divider cells into pParent as necessary.
53508 j = 0;
53509 for(i=0; i<nNew; i++){
53510 /* Assemble the new sibling page. */
53511 MemPage *pNew = apNew[i];
53512 assert( j<nMaxCells );
53513 zeroPage(pNew, pageFlags);
53514 assemblePage(pNew, cntNew[i]-j, &apCell[j], &szCell[j]);
53515 assert( pNew->nCell>0 || (nNew==1 && cntNew[0]==0) );
53516 assert( pNew->nOverflow==0 );
53518 j = cntNew[i];
53520 /* If the sibling page assembled above was not the right-most sibling,
53521 ** insert a divider cell into the parent page.
53523 assert( i<nNew-1 || j==nCell );
53524 if( j<nCell ){
53525 u8 *pCell;
53526 u8 *pTemp;
53527 int sz;
53529 assert( j<nMaxCells );
53530 pCell = apCell[j];
53531 sz = szCell[j] + leafCorrection;
53532 pTemp = &aOvflSpace[iOvflSpace];
53533 if( !pNew->leaf ){
53534 memcpy(&pNew->aData[8], pCell, 4);
53535 }else if( leafData ){
53536 /* If the tree is a leaf-data tree, and the siblings are leaves,
53537 ** then there is no divider cell in apCell[]. Instead, the divider
53538 ** cell consists of the integer key for the right-most cell of
53539 ** the sibling-page assembled above only.
53541 CellInfo info;
53542 j--;
53543 btreeParseCellPtr(pNew, apCell[j], &info);
53544 pCell = pTemp;
53545 sz = 4 + putVarint(&pCell[4], info.nKey);
53546 pTemp = 0;
53547 }else{
53548 pCell -= 4;
53549 /* Obscure case for non-leaf-data trees: If the cell at pCell was
53550 ** previously stored on a leaf node, and its reported size was 4
53551 ** bytes, then it may actually be smaller than this
53552 ** (see btreeParseCellPtr(), 4 bytes is the minimum size of
53553 ** any cell). But it is important to pass the correct size to
53554 ** insertCell(), so reparse the cell now.
53556 ** Note that this can never happen in an SQLite data file, as all
53557 ** cells are at least 4 bytes. It only happens in b-trees used
53558 ** to evaluate "IN (SELECT ...)" and similar clauses.
53560 if( szCell[j]==4 ){
53561 assert(leafCorrection==4);
53562 sz = cellSizePtr(pParent, pCell);
53565 iOvflSpace += sz;
53566 assert( sz<=pBt->maxLocal+23 );
53567 assert( iOvflSpace <= (int)pBt->pageSize );
53568 insertCell(pParent, nxDiv, pCell, sz, pTemp, pNew->pgno, &rc);
53569 if( rc!=SQLITE_OK ) goto balance_cleanup;
53570 assert( sqlite3PagerIswriteable(pParent->pDbPage) );
53572 j++;
53573 nxDiv++;
53576 assert( j==nCell );
53577 assert( nOld>0 );
53578 assert( nNew>0 );
53579 if( (pageFlags & PTF_LEAF)==0 ){
53580 u8 *zChild = &apCopy[nOld-1]->aData[8];
53581 memcpy(&apNew[nNew-1]->aData[8], zChild, 4);
53584 if( isRoot && pParent->nCell==0 && pParent->hdrOffset<=apNew[0]->nFree ){
53585 /* The root page of the b-tree now contains no cells. The only sibling
53586 ** page is the right-child of the parent. Copy the contents of the
53587 ** child page into the parent, decreasing the overall height of the
53588 ** b-tree structure by one. This is described as the "balance-shallower"
53589 ** sub-algorithm in some documentation.
53591 ** If this is an auto-vacuum database, the call to copyNodeContent()
53592 ** sets all pointer-map entries corresponding to database image pages
53593 ** for which the pointer is stored within the content being copied.
53595 ** The second assert below verifies that the child page is defragmented
53596 ** (it must be, as it was just reconstructed using assemblePage()). This
53597 ** is important if the parent page happens to be page 1 of the database
53598 ** image. */
53599 assert( nNew==1 );
53600 assert( apNew[0]->nFree ==
53601 (get2byte(&apNew[0]->aData[5])-apNew[0]->cellOffset-apNew[0]->nCell*2)
53603 copyNodeContent(apNew[0], pParent, &rc);
53604 freePage(apNew[0], &rc);
53605 }else if( ISAUTOVACUUM ){
53606 /* Fix the pointer-map entries for all the cells that were shifted around.
53607 ** There are several different types of pointer-map entries that need to
53608 ** be dealt with by this routine. Some of these have been set already, but
53609 ** many have not. The following is a summary:
53611 ** 1) The entries associated with new sibling pages that were not
53612 ** siblings when this function was called. These have already
53613 ** been set. We don't need to worry about old siblings that were
53614 ** moved to the free-list - the freePage() code has taken care
53615 ** of those.
53617 ** 2) The pointer-map entries associated with the first overflow
53618 ** page in any overflow chains used by new divider cells. These
53619 ** have also already been taken care of by the insertCell() code.
53621 ** 3) If the sibling pages are not leaves, then the child pages of
53622 ** cells stored on the sibling pages may need to be updated.
53624 ** 4) If the sibling pages are not internal intkey nodes, then any
53625 ** overflow pages used by these cells may need to be updated
53626 ** (internal intkey nodes never contain pointers to overflow pages).
53628 ** 5) If the sibling pages are not leaves, then the pointer-map
53629 ** entries for the right-child pages of each sibling may need
53630 ** to be updated.
53632 ** Cases 1 and 2 are dealt with above by other code. The next
53633 ** block deals with cases 3 and 4 and the one after that, case 5. Since
53634 ** setting a pointer map entry is a relatively expensive operation, this
53635 ** code only sets pointer map entries for child or overflow pages that have
53636 ** actually moved between pages. */
53637 MemPage *pNew = apNew[0];
53638 MemPage *pOld = apCopy[0];
53639 int nOverflow = pOld->nOverflow;
53640 int iNextOld = pOld->nCell + nOverflow;
53641 int iOverflow = (nOverflow ? pOld->aOvfl[0].idx : -1);
53642 j = 0; /* Current 'old' sibling page */
53643 k = 0; /* Current 'new' sibling page */
53644 for(i=0; i<nCell; i++){
53645 int isDivider = 0;
53646 while( i==iNextOld ){
53647 /* Cell i is the cell immediately following the last cell on old
53648 ** sibling page j. If the siblings are not leaf pages of an
53649 ** intkey b-tree, then cell i was a divider cell. */
53650 pOld = apCopy[++j];
53651 iNextOld = i + !leafData + pOld->nCell + pOld->nOverflow;
53652 if( pOld->nOverflow ){
53653 nOverflow = pOld->nOverflow;
53654 iOverflow = i + !leafData + pOld->aOvfl[0].idx;
53656 isDivider = !leafData;
53659 assert(nOverflow>0 || iOverflow<i );
53660 assert(nOverflow<2 || pOld->aOvfl[0].idx==pOld->aOvfl[1].idx-1);
53661 assert(nOverflow<3 || pOld->aOvfl[1].idx==pOld->aOvfl[2].idx-1);
53662 if( i==iOverflow ){
53663 isDivider = 1;
53664 if( (--nOverflow)>0 ){
53665 iOverflow++;
53669 if( i==cntNew[k] ){
53670 /* Cell i is the cell immediately following the last cell on new
53671 ** sibling page k. If the siblings are not leaf pages of an
53672 ** intkey b-tree, then cell i is a divider cell. */
53673 pNew = apNew[++k];
53674 if( !leafData ) continue;
53676 assert( j<nOld );
53677 assert( k<nNew );
53679 /* If the cell was originally divider cell (and is not now) or
53680 ** an overflow cell, or if the cell was located on a different sibling
53681 ** page before the balancing, then the pointer map entries associated
53682 ** with any child or overflow pages need to be updated. */
53683 if( isDivider || pOld->pgno!=pNew->pgno ){
53684 if( !leafCorrection ){
53685 ptrmapPut(pBt, get4byte(apCell[i]), PTRMAP_BTREE, pNew->pgno, &rc);
53687 if( szCell[i]>pNew->minLocal ){
53688 ptrmapPutOvflPtr(pNew, apCell[i], &rc);
53693 if( !leafCorrection ){
53694 for(i=0; i<nNew; i++){
53695 u32 key = get4byte(&apNew[i]->aData[8]);
53696 ptrmapPut(pBt, key, PTRMAP_BTREE, apNew[i]->pgno, &rc);
53700 #if 0
53701 /* The ptrmapCheckPages() contains assert() statements that verify that
53702 ** all pointer map pages are set correctly. This is helpful while
53703 ** debugging. This is usually disabled because a corrupt database may
53704 ** cause an assert() statement to fail. */
53705 ptrmapCheckPages(apNew, nNew);
53706 ptrmapCheckPages(&pParent, 1);
53707 #endif
53710 assert( pParent->isInit );
53711 TRACE(("BALANCE: finished: old=%d new=%d cells=%d\n",
53712 nOld, nNew, nCell));
53715 ** Cleanup before returning.
53717 balance_cleanup:
53718 sqlite3ScratchFree(apCell);
53719 for(i=0; i<nOld; i++){
53720 releasePage(apOld[i]);
53722 for(i=0; i<nNew; i++){
53723 releasePage(apNew[i]);
53726 return rc;
53731 ** This function is called when the root page of a b-tree structure is
53732 ** overfull (has one or more overflow pages).
53734 ** A new child page is allocated and the contents of the current root
53735 ** page, including overflow cells, are copied into the child. The root
53736 ** page is then overwritten to make it an empty page with the right-child
53737 ** pointer pointing to the new page.
53739 ** Before returning, all pointer-map entries corresponding to pages
53740 ** that the new child-page now contains pointers to are updated. The
53741 ** entry corresponding to the new right-child pointer of the root
53742 ** page is also updated.
53744 ** If successful, *ppChild is set to contain a reference to the child
53745 ** page and SQLITE_OK is returned. In this case the caller is required
53746 ** to call releasePage() on *ppChild exactly once. If an error occurs,
53747 ** an error code is returned and *ppChild is set to 0.
53749 static int balance_deeper(MemPage *pRoot, MemPage **ppChild){
53750 int rc; /* Return value from subprocedures */
53751 MemPage *pChild = 0; /* Pointer to a new child page */
53752 Pgno pgnoChild = 0; /* Page number of the new child page */
53753 BtShared *pBt = pRoot->pBt; /* The BTree */
53755 assert( pRoot->nOverflow>0 );
53756 assert( sqlite3_mutex_held(pBt->mutex) );
53758 /* Make pRoot, the root page of the b-tree, writable. Allocate a new
53759 ** page that will become the new right-child of pPage. Copy the contents
53760 ** of the node stored on pRoot into the new child page.
53762 rc = sqlite3PagerWrite(pRoot->pDbPage);
53763 if( rc==SQLITE_OK ){
53764 rc = allocateBtreePage(pBt,&pChild,&pgnoChild,pRoot->pgno,0);
53765 copyNodeContent(pRoot, pChild, &rc);
53766 if( ISAUTOVACUUM ){
53767 ptrmapPut(pBt, pgnoChild, PTRMAP_BTREE, pRoot->pgno, &rc);
53770 if( rc ){
53771 *ppChild = 0;
53772 releasePage(pChild);
53773 return rc;
53775 assert( sqlite3PagerIswriteable(pChild->pDbPage) );
53776 assert( sqlite3PagerIswriteable(pRoot->pDbPage) );
53777 assert( pChild->nCell==pRoot->nCell );
53779 TRACE(("BALANCE: copy root %d into %d\n", pRoot->pgno, pChild->pgno));
53781 /* Copy the overflow cells from pRoot to pChild */
53782 memcpy(pChild->aOvfl, pRoot->aOvfl, pRoot->nOverflow*sizeof(pRoot->aOvfl[0]));
53783 pChild->nOverflow = pRoot->nOverflow;
53785 /* Zero the contents of pRoot. Then install pChild as the right-child. */
53786 zeroPage(pRoot, pChild->aData[0] & ~PTF_LEAF);
53787 put4byte(&pRoot->aData[pRoot->hdrOffset+8], pgnoChild);
53789 *ppChild = pChild;
53790 return SQLITE_OK;
53794 ** The page that pCur currently points to has just been modified in
53795 ** some way. This function figures out if this modification means the
53796 ** tree needs to be balanced, and if so calls the appropriate balancing
53797 ** routine. Balancing routines are:
53799 ** balance_quick()
53800 ** balance_deeper()
53801 ** balance_nonroot()
53803 static int balance(BtCursor *pCur){
53804 int rc = SQLITE_OK;
53805 const int nMin = pCur->pBt->usableSize * 2 / 3;
53806 u8 aBalanceQuickSpace[13];
53807 u8 *pFree = 0;
53809 TESTONLY( int balance_quick_called = 0 );
53810 TESTONLY( int balance_deeper_called = 0 );
53812 do {
53813 int iPage = pCur->iPage;
53814 MemPage *pPage = pCur->apPage[iPage];
53816 if( iPage==0 ){
53817 if( pPage->nOverflow ){
53818 /* The root page of the b-tree is overfull. In this case call the
53819 ** balance_deeper() function to create a new child for the root-page
53820 ** and copy the current contents of the root-page to it. The
53821 ** next iteration of the do-loop will balance the child page.
53823 assert( (balance_deeper_called++)==0 );
53824 rc = balance_deeper(pPage, &pCur->apPage[1]);
53825 if( rc==SQLITE_OK ){
53826 pCur->iPage = 1;
53827 pCur->aiIdx[0] = 0;
53828 pCur->aiIdx[1] = 0;
53829 assert( pCur->apPage[1]->nOverflow );
53831 }else{
53832 break;
53834 }else if( pPage->nOverflow==0 && pPage->nFree<=nMin ){
53835 break;
53836 }else{
53837 MemPage * const pParent = pCur->apPage[iPage-1];
53838 int const iIdx = pCur->aiIdx[iPage-1];
53840 rc = sqlite3PagerWrite(pParent->pDbPage);
53841 if( rc==SQLITE_OK ){
53842 #ifndef SQLITE_OMIT_QUICKBALANCE
53843 if( pPage->hasData
53844 && pPage->nOverflow==1
53845 && pPage->aOvfl[0].idx==pPage->nCell
53846 && pParent->pgno!=1
53847 && pParent->nCell==iIdx
53849 /* Call balance_quick() to create a new sibling of pPage on which
53850 ** to store the overflow cell. balance_quick() inserts a new cell
53851 ** into pParent, which may cause pParent overflow. If this
53852 ** happens, the next interation of the do-loop will balance pParent
53853 ** use either balance_nonroot() or balance_deeper(). Until this
53854 ** happens, the overflow cell is stored in the aBalanceQuickSpace[]
53855 ** buffer.
53857 ** The purpose of the following assert() is to check that only a
53858 ** single call to balance_quick() is made for each call to this
53859 ** function. If this were not verified, a subtle bug involving reuse
53860 ** of the aBalanceQuickSpace[] might sneak in.
53862 assert( (balance_quick_called++)==0 );
53863 rc = balance_quick(pParent, pPage, aBalanceQuickSpace);
53864 }else
53865 #endif
53867 /* In this case, call balance_nonroot() to redistribute cells
53868 ** between pPage and up to 2 of its sibling pages. This involves
53869 ** modifying the contents of pParent, which may cause pParent to
53870 ** become overfull or underfull. The next iteration of the do-loop
53871 ** will balance the parent page to correct this.
53873 ** If the parent page becomes overfull, the overflow cell or cells
53874 ** are stored in the pSpace buffer allocated immediately below.
53875 ** A subsequent iteration of the do-loop will deal with this by
53876 ** calling balance_nonroot() (balance_deeper() may be called first,
53877 ** but it doesn't deal with overflow cells - just moves them to a
53878 ** different page). Once this subsequent call to balance_nonroot()
53879 ** has completed, it is safe to release the pSpace buffer used by
53880 ** the previous call, as the overflow cell data will have been
53881 ** copied either into the body of a database page or into the new
53882 ** pSpace buffer passed to the latter call to balance_nonroot().
53884 u8 *pSpace = sqlite3PageMalloc(pCur->pBt->pageSize);
53885 rc = balance_nonroot(pParent, iIdx, pSpace, iPage==1);
53886 if( pFree ){
53887 /* If pFree is not NULL, it points to the pSpace buffer used
53888 ** by a previous call to balance_nonroot(). Its contents are
53889 ** now stored either on real database pages or within the
53890 ** new pSpace buffer, so it may be safely freed here. */
53891 sqlite3PageFree(pFree);
53894 /* The pSpace buffer will be freed after the next call to
53895 ** balance_nonroot(), or just before this function returns, whichever
53896 ** comes first. */
53897 pFree = pSpace;
53901 pPage->nOverflow = 0;
53903 /* The next iteration of the do-loop balances the parent page. */
53904 releasePage(pPage);
53905 pCur->iPage--;
53907 }while( rc==SQLITE_OK );
53909 if( pFree ){
53910 sqlite3PageFree(pFree);
53912 return rc;
53917 ** Insert a new record into the BTree. The key is given by (pKey,nKey)
53918 ** and the data is given by (pData,nData). The cursor is used only to
53919 ** define what table the record should be inserted into. The cursor
53920 ** is left pointing at a random location.
53922 ** For an INTKEY table, only the nKey value of the key is used. pKey is
53923 ** ignored. For a ZERODATA table, the pData and nData are both ignored.
53925 ** If the seekResult parameter is non-zero, then a successful call to
53926 ** MovetoUnpacked() to seek cursor pCur to (pKey, nKey) has already
53927 ** been performed. seekResult is the search result returned (a negative
53928 ** number if pCur points at an entry that is smaller than (pKey, nKey), or
53929 ** a positive value if pCur points at an etry that is larger than
53930 ** (pKey, nKey)).
53932 ** If the seekResult parameter is non-zero, then the caller guarantees that
53933 ** cursor pCur is pointing at the existing copy of a row that is to be
53934 ** overwritten. If the seekResult parameter is 0, then cursor pCur may
53935 ** point to any entry or to no entry at all and so this function has to seek
53936 ** the cursor before the new key can be inserted.
53938 SQLITE_PRIVATE int sqlite3BtreeInsert(
53939 BtCursor *pCur, /* Insert data into the table of this cursor */
53940 const void *pKey, i64 nKey, /* The key of the new record */
53941 const void *pData, int nData, /* The data of the new record */
53942 int nZero, /* Number of extra 0 bytes to append to data */
53943 int appendBias, /* True if this is likely an append */
53944 int seekResult /* Result of prior MovetoUnpacked() call */
53946 int rc;
53947 int loc = seekResult; /* -1: before desired location +1: after */
53948 int szNew = 0;
53949 int idx;
53950 MemPage *pPage;
53951 Btree *p = pCur->pBtree;
53952 BtShared *pBt = p->pBt;
53953 unsigned char *oldCell;
53954 unsigned char *newCell = 0;
53956 if( pCur->eState==CURSOR_FAULT ){
53957 assert( pCur->skipNext!=SQLITE_OK );
53958 return pCur->skipNext;
53961 assert( cursorHoldsMutex(pCur) );
53962 assert( pCur->wrFlag && pBt->inTransaction==TRANS_WRITE && !pBt->readOnly );
53963 assert( hasSharedCacheTableLock(p, pCur->pgnoRoot, pCur->pKeyInfo!=0, 2) );
53965 /* Assert that the caller has been consistent. If this cursor was opened
53966 ** expecting an index b-tree, then the caller should be inserting blob
53967 ** keys with no associated data. If the cursor was opened expecting an
53968 ** intkey table, the caller should be inserting integer keys with a
53969 ** blob of associated data. */
53970 assert( (pKey==0)==(pCur->pKeyInfo==0) );
53972 /* If this is an insert into a table b-tree, invalidate any incrblob
53973 ** cursors open on the row being replaced (assuming this is a replace
53974 ** operation - if it is not, the following is a no-op). */
53975 if( pCur->pKeyInfo==0 ){
53976 invalidateIncrblobCursors(p, nKey, 0);
53979 /* Save the positions of any other cursors open on this table.
53981 ** In some cases, the call to btreeMoveto() below is a no-op. For
53982 ** example, when inserting data into a table with auto-generated integer
53983 ** keys, the VDBE layer invokes sqlite3BtreeLast() to figure out the
53984 ** integer key to use. It then calls this function to actually insert the
53985 ** data into the intkey B-Tree. In this case btreeMoveto() recognizes
53986 ** that the cursor is already where it needs to be and returns without
53987 ** doing any work. To avoid thwarting these optimizations, it is important
53988 ** not to clear the cursor here.
53990 rc = saveAllCursors(pBt, pCur->pgnoRoot, pCur);
53991 if( rc ) return rc;
53992 if( !loc ){
53993 rc = btreeMoveto(pCur, pKey, nKey, appendBias, &loc);
53994 if( rc ) return rc;
53996 assert( pCur->eState==CURSOR_VALID || (pCur->eState==CURSOR_INVALID && loc) );
53998 pPage = pCur->apPage[pCur->iPage];
53999 assert( pPage->intKey || nKey>=0 );
54000 assert( pPage->leaf || !pPage->intKey );
54002 TRACE(("INSERT: table=%d nkey=%lld ndata=%d page=%d %s\n",
54003 pCur->pgnoRoot, nKey, nData, pPage->pgno,
54004 loc==0 ? "overwrite" : "new entry"));
54005 assert( pPage->isInit );
54006 allocateTempSpace(pBt);
54007 newCell = pBt->pTmpSpace;
54008 if( newCell==0 ) return SQLITE_NOMEM;
54009 rc = fillInCell(pPage, newCell, pKey, nKey, pData, nData, nZero, &szNew);
54010 if( rc ) goto end_insert;
54011 assert( szNew==cellSizePtr(pPage, newCell) );
54012 assert( szNew <= MX_CELL_SIZE(pBt) );
54013 idx = pCur->aiIdx[pCur->iPage];
54014 if( loc==0 ){
54015 u16 szOld;
54016 assert( idx<pPage->nCell );
54017 rc = sqlite3PagerWrite(pPage->pDbPage);
54018 if( rc ){
54019 goto end_insert;
54021 oldCell = findCell(pPage, idx);
54022 if( !pPage->leaf ){
54023 memcpy(newCell, oldCell, 4);
54025 szOld = cellSizePtr(pPage, oldCell);
54026 rc = clearCell(pPage, oldCell);
54027 dropCell(pPage, idx, szOld, &rc);
54028 if( rc ) goto end_insert;
54029 }else if( loc<0 && pPage->nCell>0 ){
54030 assert( pPage->leaf );
54031 idx = ++pCur->aiIdx[pCur->iPage];
54032 }else{
54033 assert( pPage->leaf );
54035 insertCell(pPage, idx, newCell, szNew, 0, 0, &rc);
54036 assert( rc!=SQLITE_OK || pPage->nCell>0 || pPage->nOverflow>0 );
54038 /* If no error has occured and pPage has an overflow cell, call balance()
54039 ** to redistribute the cells within the tree. Since balance() may move
54040 ** the cursor, zero the BtCursor.info.nSize and BtCursor.validNKey
54041 ** variables.
54043 ** Previous versions of SQLite called moveToRoot() to move the cursor
54044 ** back to the root page as balance() used to invalidate the contents
54045 ** of BtCursor.apPage[] and BtCursor.aiIdx[]. Instead of doing that,
54046 ** set the cursor state to "invalid". This makes common insert operations
54047 ** slightly faster.
54049 ** There is a subtle but important optimization here too. When inserting
54050 ** multiple records into an intkey b-tree using a single cursor (as can
54051 ** happen while processing an "INSERT INTO ... SELECT" statement), it
54052 ** is advantageous to leave the cursor pointing to the last entry in
54053 ** the b-tree if possible. If the cursor is left pointing to the last
54054 ** entry in the table, and the next row inserted has an integer key
54055 ** larger than the largest existing key, it is possible to insert the
54056 ** row without seeking the cursor. This can be a big performance boost.
54058 pCur->info.nSize = 0;
54059 pCur->validNKey = 0;
54060 if( rc==SQLITE_OK && pPage->nOverflow ){
54061 rc = balance(pCur);
54063 /* Must make sure nOverflow is reset to zero even if the balance()
54064 ** fails. Internal data structure corruption will result otherwise.
54065 ** Also, set the cursor state to invalid. This stops saveCursorPosition()
54066 ** from trying to save the current position of the cursor. */
54067 pCur->apPage[pCur->iPage]->nOverflow = 0;
54068 pCur->eState = CURSOR_INVALID;
54070 assert( pCur->apPage[pCur->iPage]->nOverflow==0 );
54072 end_insert:
54073 return rc;
54077 ** Delete the entry that the cursor is pointing to. The cursor
54078 ** is left pointing at a arbitrary location.
54080 SQLITE_PRIVATE int sqlite3BtreeDelete(BtCursor *pCur){
54081 Btree *p = pCur->pBtree;
54082 BtShared *pBt = p->pBt;
54083 int rc; /* Return code */
54084 MemPage *pPage; /* Page to delete cell from */
54085 unsigned char *pCell; /* Pointer to cell to delete */
54086 int iCellIdx; /* Index of cell to delete */
54087 int iCellDepth; /* Depth of node containing pCell */
54089 assert( cursorHoldsMutex(pCur) );
54090 assert( pBt->inTransaction==TRANS_WRITE );
54091 assert( !pBt->readOnly );
54092 assert( pCur->wrFlag );
54093 assert( hasSharedCacheTableLock(p, pCur->pgnoRoot, pCur->pKeyInfo!=0, 2) );
54094 assert( !hasReadConflicts(p, pCur->pgnoRoot) );
54096 if( NEVER(pCur->aiIdx[pCur->iPage]>=pCur->apPage[pCur->iPage]->nCell)
54097 || NEVER(pCur->eState!=CURSOR_VALID)
54099 return SQLITE_ERROR; /* Something has gone awry. */
54102 /* If this is a delete operation to remove a row from a table b-tree,
54103 ** invalidate any incrblob cursors open on the row being deleted. */
54104 if( pCur->pKeyInfo==0 ){
54105 invalidateIncrblobCursors(p, pCur->info.nKey, 0);
54108 iCellDepth = pCur->iPage;
54109 iCellIdx = pCur->aiIdx[iCellDepth];
54110 pPage = pCur->apPage[iCellDepth];
54111 pCell = findCell(pPage, iCellIdx);
54113 /* If the page containing the entry to delete is not a leaf page, move
54114 ** the cursor to the largest entry in the tree that is smaller than
54115 ** the entry being deleted. This cell will replace the cell being deleted
54116 ** from the internal node. The 'previous' entry is used for this instead
54117 ** of the 'next' entry, as the previous entry is always a part of the
54118 ** sub-tree headed by the child page of the cell being deleted. This makes
54119 ** balancing the tree following the delete operation easier. */
54120 if( !pPage->leaf ){
54121 int notUsed;
54122 rc = sqlite3BtreePrevious(pCur, &notUsed);
54123 if( rc ) return rc;
54126 /* Save the positions of any other cursors open on this table before
54127 ** making any modifications. Make the page containing the entry to be
54128 ** deleted writable. Then free any overflow pages associated with the
54129 ** entry and finally remove the cell itself from within the page.
54131 rc = saveAllCursors(pBt, pCur->pgnoRoot, pCur);
54132 if( rc ) return rc;
54133 rc = sqlite3PagerWrite(pPage->pDbPage);
54134 if( rc ) return rc;
54135 rc = clearCell(pPage, pCell);
54136 dropCell(pPage, iCellIdx, cellSizePtr(pPage, pCell), &rc);
54137 if( rc ) return rc;
54139 /* If the cell deleted was not located on a leaf page, then the cursor
54140 ** is currently pointing to the largest entry in the sub-tree headed
54141 ** by the child-page of the cell that was just deleted from an internal
54142 ** node. The cell from the leaf node needs to be moved to the internal
54143 ** node to replace the deleted cell. */
54144 if( !pPage->leaf ){
54145 MemPage *pLeaf = pCur->apPage[pCur->iPage];
54146 int nCell;
54147 Pgno n = pCur->apPage[iCellDepth+1]->pgno;
54148 unsigned char *pTmp;
54150 pCell = findCell(pLeaf, pLeaf->nCell-1);
54151 nCell = cellSizePtr(pLeaf, pCell);
54152 assert( MX_CELL_SIZE(pBt) >= nCell );
54154 allocateTempSpace(pBt);
54155 pTmp = pBt->pTmpSpace;
54157 rc = sqlite3PagerWrite(pLeaf->pDbPage);
54158 insertCell(pPage, iCellIdx, pCell-4, nCell+4, pTmp, n, &rc);
54159 dropCell(pLeaf, pLeaf->nCell-1, nCell, &rc);
54160 if( rc ) return rc;
54163 /* Balance the tree. If the entry deleted was located on a leaf page,
54164 ** then the cursor still points to that page. In this case the first
54165 ** call to balance() repairs the tree, and the if(...) condition is
54166 ** never true.
54168 ** Otherwise, if the entry deleted was on an internal node page, then
54169 ** pCur is pointing to the leaf page from which a cell was removed to
54170 ** replace the cell deleted from the internal node. This is slightly
54171 ** tricky as the leaf node may be underfull, and the internal node may
54172 ** be either under or overfull. In this case run the balancing algorithm
54173 ** on the leaf node first. If the balance proceeds far enough up the
54174 ** tree that we can be sure that any problem in the internal node has
54175 ** been corrected, so be it. Otherwise, after balancing the leaf node,
54176 ** walk the cursor up the tree to the internal node and balance it as
54177 ** well. */
54178 rc = balance(pCur);
54179 if( rc==SQLITE_OK && pCur->iPage>iCellDepth ){
54180 while( pCur->iPage>iCellDepth ){
54181 releasePage(pCur->apPage[pCur->iPage--]);
54183 rc = balance(pCur);
54186 if( rc==SQLITE_OK ){
54187 moveToRoot(pCur);
54189 return rc;
54193 ** Create a new BTree table. Write into *piTable the page
54194 ** number for the root page of the new table.
54196 ** The type of type is determined by the flags parameter. Only the
54197 ** following values of flags are currently in use. Other values for
54198 ** flags might not work:
54200 ** BTREE_INTKEY|BTREE_LEAFDATA Used for SQL tables with rowid keys
54201 ** BTREE_ZERODATA Used for SQL indices
54203 static int btreeCreateTable(Btree *p, int *piTable, int createTabFlags){
54204 BtShared *pBt = p->pBt;
54205 MemPage *pRoot;
54206 Pgno pgnoRoot;
54207 int rc;
54208 int ptfFlags; /* Page-type flage for the root page of new table */
54210 assert( sqlite3BtreeHoldsMutex(p) );
54211 assert( pBt->inTransaction==TRANS_WRITE );
54212 assert( !pBt->readOnly );
54214 #ifdef SQLITE_OMIT_AUTOVACUUM
54215 rc = allocateBtreePage(pBt, &pRoot, &pgnoRoot, 1, 0);
54216 if( rc ){
54217 return rc;
54219 #else
54220 if( pBt->autoVacuum ){
54221 Pgno pgnoMove; /* Move a page here to make room for the root-page */
54222 MemPage *pPageMove; /* The page to move to. */
54224 /* Creating a new table may probably require moving an existing database
54225 ** to make room for the new tables root page. In case this page turns
54226 ** out to be an overflow page, delete all overflow page-map caches
54227 ** held by open cursors.
54229 invalidateAllOverflowCache(pBt);
54231 /* Read the value of meta[3] from the database to determine where the
54232 ** root page of the new table should go. meta[3] is the largest root-page
54233 ** created so far, so the new root-page is (meta[3]+1).
54235 sqlite3BtreeGetMeta(p, BTREE_LARGEST_ROOT_PAGE, &pgnoRoot);
54236 pgnoRoot++;
54238 /* The new root-page may not be allocated on a pointer-map page, or the
54239 ** PENDING_BYTE page.
54241 while( pgnoRoot==PTRMAP_PAGENO(pBt, pgnoRoot) ||
54242 pgnoRoot==PENDING_BYTE_PAGE(pBt) ){
54243 pgnoRoot++;
54245 assert( pgnoRoot>=3 );
54247 /* Allocate a page. The page that currently resides at pgnoRoot will
54248 ** be moved to the allocated page (unless the allocated page happens
54249 ** to reside at pgnoRoot).
54251 rc = allocateBtreePage(pBt, &pPageMove, &pgnoMove, pgnoRoot, 1);
54252 if( rc!=SQLITE_OK ){
54253 return rc;
54256 if( pgnoMove!=pgnoRoot ){
54257 /* pgnoRoot is the page that will be used for the root-page of
54258 ** the new table (assuming an error did not occur). But we were
54259 ** allocated pgnoMove. If required (i.e. if it was not allocated
54260 ** by extending the file), the current page at position pgnoMove
54261 ** is already journaled.
54263 u8 eType = 0;
54264 Pgno iPtrPage = 0;
54266 releasePage(pPageMove);
54268 /* Move the page currently at pgnoRoot to pgnoMove. */
54269 rc = btreeGetPage(pBt, pgnoRoot, &pRoot, 0);
54270 if( rc!=SQLITE_OK ){
54271 return rc;
54273 rc = ptrmapGet(pBt, pgnoRoot, &eType, &iPtrPage);
54274 if( eType==PTRMAP_ROOTPAGE || eType==PTRMAP_FREEPAGE ){
54275 rc = SQLITE_CORRUPT_BKPT;
54277 if( rc!=SQLITE_OK ){
54278 releasePage(pRoot);
54279 return rc;
54281 assert( eType!=PTRMAP_ROOTPAGE );
54282 assert( eType!=PTRMAP_FREEPAGE );
54283 rc = relocatePage(pBt, pRoot, eType, iPtrPage, pgnoMove, 0);
54284 releasePage(pRoot);
54286 /* Obtain the page at pgnoRoot */
54287 if( rc!=SQLITE_OK ){
54288 return rc;
54290 rc = btreeGetPage(pBt, pgnoRoot, &pRoot, 0);
54291 if( rc!=SQLITE_OK ){
54292 return rc;
54294 rc = sqlite3PagerWrite(pRoot->pDbPage);
54295 if( rc!=SQLITE_OK ){
54296 releasePage(pRoot);
54297 return rc;
54299 }else{
54300 pRoot = pPageMove;
54303 /* Update the pointer-map and meta-data with the new root-page number. */
54304 ptrmapPut(pBt, pgnoRoot, PTRMAP_ROOTPAGE, 0, &rc);
54305 if( rc ){
54306 releasePage(pRoot);
54307 return rc;
54310 /* When the new root page was allocated, page 1 was made writable in
54311 ** order either to increase the database filesize, or to decrement the
54312 ** freelist count. Hence, the sqlite3BtreeUpdateMeta() call cannot fail.
54314 assert( sqlite3PagerIswriteable(pBt->pPage1->pDbPage) );
54315 rc = sqlite3BtreeUpdateMeta(p, 4, pgnoRoot);
54316 if( NEVER(rc) ){
54317 releasePage(pRoot);
54318 return rc;
54321 }else{
54322 rc = allocateBtreePage(pBt, &pRoot, &pgnoRoot, 1, 0);
54323 if( rc ) return rc;
54325 #endif
54326 assert( sqlite3PagerIswriteable(pRoot->pDbPage) );
54327 if( createTabFlags & BTREE_INTKEY ){
54328 ptfFlags = PTF_INTKEY | PTF_LEAFDATA | PTF_LEAF;
54329 }else{
54330 ptfFlags = PTF_ZERODATA | PTF_LEAF;
54332 zeroPage(pRoot, ptfFlags);
54333 sqlite3PagerUnref(pRoot->pDbPage);
54334 assert( (pBt->openFlags & BTREE_SINGLE)==0 || pgnoRoot==2 );
54335 *piTable = (int)pgnoRoot;
54336 return SQLITE_OK;
54338 SQLITE_PRIVATE int sqlite3BtreeCreateTable(Btree *p, int *piTable, int flags){
54339 int rc;
54340 sqlite3BtreeEnter(p);
54341 rc = btreeCreateTable(p, piTable, flags);
54342 sqlite3BtreeLeave(p);
54343 return rc;
54347 ** Erase the given database page and all its children. Return
54348 ** the page to the freelist.
54350 static int clearDatabasePage(
54351 BtShared *pBt, /* The BTree that contains the table */
54352 Pgno pgno, /* Page number to clear */
54353 int freePageFlag, /* Deallocate page if true */
54354 int *pnChange /* Add number of Cells freed to this counter */
54356 MemPage *pPage;
54357 int rc;
54358 unsigned char *pCell;
54359 int i;
54361 assert( sqlite3_mutex_held(pBt->mutex) );
54362 if( pgno>btreePagecount(pBt) ){
54363 return SQLITE_CORRUPT_BKPT;
54366 rc = getAndInitPage(pBt, pgno, &pPage);
54367 if( rc ) return rc;
54368 for(i=0; i<pPage->nCell; i++){
54369 pCell = findCell(pPage, i);
54370 if( !pPage->leaf ){
54371 rc = clearDatabasePage(pBt, get4byte(pCell), 1, pnChange);
54372 if( rc ) goto cleardatabasepage_out;
54374 rc = clearCell(pPage, pCell);
54375 if( rc ) goto cleardatabasepage_out;
54377 if( !pPage->leaf ){
54378 rc = clearDatabasePage(pBt, get4byte(&pPage->aData[8]), 1, pnChange);
54379 if( rc ) goto cleardatabasepage_out;
54380 }else if( pnChange ){
54381 assert( pPage->intKey );
54382 *pnChange += pPage->nCell;
54384 if( freePageFlag ){
54385 freePage(pPage, &rc);
54386 }else if( (rc = sqlite3PagerWrite(pPage->pDbPage))==0 ){
54387 zeroPage(pPage, pPage->aData[0] | PTF_LEAF);
54390 cleardatabasepage_out:
54391 releasePage(pPage);
54392 return rc;
54396 ** Delete all information from a single table in the database. iTable is
54397 ** the page number of the root of the table. After this routine returns,
54398 ** the root page is empty, but still exists.
54400 ** This routine will fail with SQLITE_LOCKED if there are any open
54401 ** read cursors on the table. Open write cursors are moved to the
54402 ** root of the table.
54404 ** If pnChange is not NULL, then table iTable must be an intkey table. The
54405 ** integer value pointed to by pnChange is incremented by the number of
54406 ** entries in the table.
54408 SQLITE_PRIVATE int sqlite3BtreeClearTable(Btree *p, int iTable, int *pnChange){
54409 int rc;
54410 BtShared *pBt = p->pBt;
54411 sqlite3BtreeEnter(p);
54412 assert( p->inTrans==TRANS_WRITE );
54414 /* Invalidate all incrblob cursors open on table iTable (assuming iTable
54415 ** is the root of a table b-tree - if it is not, the following call is
54416 ** a no-op). */
54417 invalidateIncrblobCursors(p, 0, 1);
54419 rc = saveAllCursors(pBt, (Pgno)iTable, 0);
54420 if( SQLITE_OK==rc ){
54421 rc = clearDatabasePage(pBt, (Pgno)iTable, 0, pnChange);
54423 sqlite3BtreeLeave(p);
54424 return rc;
54428 ** Erase all information in a table and add the root of the table to
54429 ** the freelist. Except, the root of the principle table (the one on
54430 ** page 1) is never added to the freelist.
54432 ** This routine will fail with SQLITE_LOCKED if there are any open
54433 ** cursors on the table.
54435 ** If AUTOVACUUM is enabled and the page at iTable is not the last
54436 ** root page in the database file, then the last root page
54437 ** in the database file is moved into the slot formerly occupied by
54438 ** iTable and that last slot formerly occupied by the last root page
54439 ** is added to the freelist instead of iTable. In this say, all
54440 ** root pages are kept at the beginning of the database file, which
54441 ** is necessary for AUTOVACUUM to work right. *piMoved is set to the
54442 ** page number that used to be the last root page in the file before
54443 ** the move. If no page gets moved, *piMoved is set to 0.
54444 ** The last root page is recorded in meta[3] and the value of
54445 ** meta[3] is updated by this procedure.
54447 static int btreeDropTable(Btree *p, Pgno iTable, int *piMoved){
54448 int rc;
54449 MemPage *pPage = 0;
54450 BtShared *pBt = p->pBt;
54452 assert( sqlite3BtreeHoldsMutex(p) );
54453 assert( p->inTrans==TRANS_WRITE );
54455 /* It is illegal to drop a table if any cursors are open on the
54456 ** database. This is because in auto-vacuum mode the backend may
54457 ** need to move another root-page to fill a gap left by the deleted
54458 ** root page. If an open cursor was using this page a problem would
54459 ** occur.
54461 ** This error is caught long before control reaches this point.
54463 if( NEVER(pBt->pCursor) ){
54464 sqlite3ConnectionBlocked(p->db, pBt->pCursor->pBtree->db);
54465 return SQLITE_LOCKED_SHAREDCACHE;
54468 rc = btreeGetPage(pBt, (Pgno)iTable, &pPage, 0);
54469 if( rc ) return rc;
54470 rc = sqlite3BtreeClearTable(p, iTable, 0);
54471 if( rc ){
54472 releasePage(pPage);
54473 return rc;
54476 *piMoved = 0;
54478 if( iTable>1 ){
54479 #ifdef SQLITE_OMIT_AUTOVACUUM
54480 freePage(pPage, &rc);
54481 releasePage(pPage);
54482 #else
54483 if( pBt->autoVacuum ){
54484 Pgno maxRootPgno;
54485 sqlite3BtreeGetMeta(p, BTREE_LARGEST_ROOT_PAGE, &maxRootPgno);
54487 if( iTable==maxRootPgno ){
54488 /* If the table being dropped is the table with the largest root-page
54489 ** number in the database, put the root page on the free list.
54491 freePage(pPage, &rc);
54492 releasePage(pPage);
54493 if( rc!=SQLITE_OK ){
54494 return rc;
54496 }else{
54497 /* The table being dropped does not have the largest root-page
54498 ** number in the database. So move the page that does into the
54499 ** gap left by the deleted root-page.
54501 MemPage *pMove;
54502 releasePage(pPage);
54503 rc = btreeGetPage(pBt, maxRootPgno, &pMove, 0);
54504 if( rc!=SQLITE_OK ){
54505 return rc;
54507 rc = relocatePage(pBt, pMove, PTRMAP_ROOTPAGE, 0, iTable, 0);
54508 releasePage(pMove);
54509 if( rc!=SQLITE_OK ){
54510 return rc;
54512 pMove = 0;
54513 rc = btreeGetPage(pBt, maxRootPgno, &pMove, 0);
54514 freePage(pMove, &rc);
54515 releasePage(pMove);
54516 if( rc!=SQLITE_OK ){
54517 return rc;
54519 *piMoved = maxRootPgno;
54522 /* Set the new 'max-root-page' value in the database header. This
54523 ** is the old value less one, less one more if that happens to
54524 ** be a root-page number, less one again if that is the
54525 ** PENDING_BYTE_PAGE.
54527 maxRootPgno--;
54528 while( maxRootPgno==PENDING_BYTE_PAGE(pBt)
54529 || PTRMAP_ISPAGE(pBt, maxRootPgno) ){
54530 maxRootPgno--;
54532 assert( maxRootPgno!=PENDING_BYTE_PAGE(pBt) );
54534 rc = sqlite3BtreeUpdateMeta(p, 4, maxRootPgno);
54535 }else{
54536 freePage(pPage, &rc);
54537 releasePage(pPage);
54539 #endif
54540 }else{
54541 /* If sqlite3BtreeDropTable was called on page 1.
54542 ** This really never should happen except in a corrupt
54543 ** database.
54545 zeroPage(pPage, PTF_INTKEY|PTF_LEAF );
54546 releasePage(pPage);
54548 return rc;
54550 SQLITE_PRIVATE int sqlite3BtreeDropTable(Btree *p, int iTable, int *piMoved){
54551 int rc;
54552 sqlite3BtreeEnter(p);
54553 rc = btreeDropTable(p, iTable, piMoved);
54554 sqlite3BtreeLeave(p);
54555 return rc;
54560 ** This function may only be called if the b-tree connection already
54561 ** has a read or write transaction open on the database.
54563 ** Read the meta-information out of a database file. Meta[0]
54564 ** is the number of free pages currently in the database. Meta[1]
54565 ** through meta[15] are available for use by higher layers. Meta[0]
54566 ** is read-only, the others are read/write.
54568 ** The schema layer numbers meta values differently. At the schema
54569 ** layer (and the SetCookie and ReadCookie opcodes) the number of
54570 ** free pages is not visible. So Cookie[0] is the same as Meta[1].
54572 SQLITE_PRIVATE void sqlite3BtreeGetMeta(Btree *p, int idx, u32 *pMeta){
54573 BtShared *pBt = p->pBt;
54575 sqlite3BtreeEnter(p);
54576 assert( p->inTrans>TRANS_NONE );
54577 assert( SQLITE_OK==querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK) );
54578 assert( pBt->pPage1 );
54579 assert( idx>=0 && idx<=15 );
54581 *pMeta = get4byte(&pBt->pPage1->aData[36 + idx*4]);
54583 /* If auto-vacuum is disabled in this build and this is an auto-vacuum
54584 ** database, mark the database as read-only. */
54585 #ifdef SQLITE_OMIT_AUTOVACUUM
54586 if( idx==BTREE_LARGEST_ROOT_PAGE && *pMeta>0 ) pBt->readOnly = 1;
54587 #endif
54589 sqlite3BtreeLeave(p);
54593 ** Write meta-information back into the database. Meta[0] is
54594 ** read-only and may not be written.
54596 SQLITE_PRIVATE int sqlite3BtreeUpdateMeta(Btree *p, int idx, u32 iMeta){
54597 BtShared *pBt = p->pBt;
54598 unsigned char *pP1;
54599 int rc;
54600 assert( idx>=1 && idx<=15 );
54601 sqlite3BtreeEnter(p);
54602 assert( p->inTrans==TRANS_WRITE );
54603 assert( pBt->pPage1!=0 );
54604 pP1 = pBt->pPage1->aData;
54605 rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
54606 if( rc==SQLITE_OK ){
54607 put4byte(&pP1[36 + idx*4], iMeta);
54608 #ifndef SQLITE_OMIT_AUTOVACUUM
54609 if( idx==BTREE_INCR_VACUUM ){
54610 assert( pBt->autoVacuum || iMeta==0 );
54611 assert( iMeta==0 || iMeta==1 );
54612 pBt->incrVacuum = (u8)iMeta;
54614 #endif
54616 sqlite3BtreeLeave(p);
54617 return rc;
54620 #ifndef SQLITE_OMIT_BTREECOUNT
54622 ** The first argument, pCur, is a cursor opened on some b-tree. Count the
54623 ** number of entries in the b-tree and write the result to *pnEntry.
54625 ** SQLITE_OK is returned if the operation is successfully executed.
54626 ** Otherwise, if an error is encountered (i.e. an IO error or database
54627 ** corruption) an SQLite error code is returned.
54629 SQLITE_PRIVATE int sqlite3BtreeCount(BtCursor *pCur, i64 *pnEntry){
54630 i64 nEntry = 0; /* Value to return in *pnEntry */
54631 int rc; /* Return code */
54632 rc = moveToRoot(pCur);
54634 /* Unless an error occurs, the following loop runs one iteration for each
54635 ** page in the B-Tree structure (not including overflow pages).
54637 while( rc==SQLITE_OK ){
54638 int iIdx; /* Index of child node in parent */
54639 MemPage *pPage; /* Current page of the b-tree */
54641 /* If this is a leaf page or the tree is not an int-key tree, then
54642 ** this page contains countable entries. Increment the entry counter
54643 ** accordingly.
54645 pPage = pCur->apPage[pCur->iPage];
54646 if( pPage->leaf || !pPage->intKey ){
54647 nEntry += pPage->nCell;
54650 /* pPage is a leaf node. This loop navigates the cursor so that it
54651 ** points to the first interior cell that it points to the parent of
54652 ** the next page in the tree that has not yet been visited. The
54653 ** pCur->aiIdx[pCur->iPage] value is set to the index of the parent cell
54654 ** of the page, or to the number of cells in the page if the next page
54655 ** to visit is the right-child of its parent.
54657 ** If all pages in the tree have been visited, return SQLITE_OK to the
54658 ** caller.
54660 if( pPage->leaf ){
54661 do {
54662 if( pCur->iPage==0 ){
54663 /* All pages of the b-tree have been visited. Return successfully. */
54664 *pnEntry = nEntry;
54665 return SQLITE_OK;
54667 moveToParent(pCur);
54668 }while ( pCur->aiIdx[pCur->iPage]>=pCur->apPage[pCur->iPage]->nCell );
54670 pCur->aiIdx[pCur->iPage]++;
54671 pPage = pCur->apPage[pCur->iPage];
54674 /* Descend to the child node of the cell that the cursor currently
54675 ** points at. This is the right-child if (iIdx==pPage->nCell).
54677 iIdx = pCur->aiIdx[pCur->iPage];
54678 if( iIdx==pPage->nCell ){
54679 rc = moveToChild(pCur, get4byte(&pPage->aData[pPage->hdrOffset+8]));
54680 }else{
54681 rc = moveToChild(pCur, get4byte(findCell(pPage, iIdx)));
54685 /* An error has occurred. Return an error code. */
54686 return rc;
54688 #endif
54691 ** Return the pager associated with a BTree. This routine is used for
54692 ** testing and debugging only.
54694 SQLITE_PRIVATE Pager *sqlite3BtreePager(Btree *p){
54695 return p->pBt->pPager;
54698 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
54700 ** Append a message to the error message string.
54702 static void checkAppendMsg(
54703 IntegrityCk *pCheck,
54704 char *zMsg1,
54705 const char *zFormat,
54708 va_list ap;
54709 if( !pCheck->mxErr ) return;
54710 pCheck->mxErr--;
54711 pCheck->nErr++;
54712 va_start(ap, zFormat);
54713 if( pCheck->errMsg.nChar ){
54714 sqlite3StrAccumAppend(&pCheck->errMsg, "\n", 1);
54716 if( zMsg1 ){
54717 sqlite3StrAccumAppend(&pCheck->errMsg, zMsg1, -1);
54719 sqlite3VXPrintf(&pCheck->errMsg, 1, zFormat, ap);
54720 va_end(ap);
54721 if( pCheck->errMsg.mallocFailed ){
54722 pCheck->mallocFailed = 1;
54725 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
54727 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
54729 ** Add 1 to the reference count for page iPage. If this is the second
54730 ** reference to the page, add an error message to pCheck->zErrMsg.
54731 ** Return 1 if there are 2 ore more references to the page and 0 if
54732 ** if this is the first reference to the page.
54734 ** Also check that the page number is in bounds.
54736 static int checkRef(IntegrityCk *pCheck, Pgno iPage, char *zContext){
54737 if( iPage==0 ) return 1;
54738 if( iPage>pCheck->nPage ){
54739 checkAppendMsg(pCheck, zContext, "invalid page number %d", iPage);
54740 return 1;
54742 if( pCheck->anRef[iPage]==1 ){
54743 checkAppendMsg(pCheck, zContext, "2nd reference to page %d", iPage);
54744 return 1;
54746 return (pCheck->anRef[iPage]++)>1;
54749 #ifndef SQLITE_OMIT_AUTOVACUUM
54751 ** Check that the entry in the pointer-map for page iChild maps to
54752 ** page iParent, pointer type ptrType. If not, append an error message
54753 ** to pCheck.
54755 static void checkPtrmap(
54756 IntegrityCk *pCheck, /* Integrity check context */
54757 Pgno iChild, /* Child page number */
54758 u8 eType, /* Expected pointer map type */
54759 Pgno iParent, /* Expected pointer map parent page number */
54760 char *zContext /* Context description (used for error msg) */
54762 int rc;
54763 u8 ePtrmapType;
54764 Pgno iPtrmapParent;
54766 rc = ptrmapGet(pCheck->pBt, iChild, &ePtrmapType, &iPtrmapParent);
54767 if( rc!=SQLITE_OK ){
54768 if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ) pCheck->mallocFailed = 1;
54769 checkAppendMsg(pCheck, zContext, "Failed to read ptrmap key=%d", iChild);
54770 return;
54773 if( ePtrmapType!=eType || iPtrmapParent!=iParent ){
54774 checkAppendMsg(pCheck, zContext,
54775 "Bad ptr map entry key=%d expected=(%d,%d) got=(%d,%d)",
54776 iChild, eType, iParent, ePtrmapType, iPtrmapParent);
54779 #endif
54782 ** Check the integrity of the freelist or of an overflow page list.
54783 ** Verify that the number of pages on the list is N.
54785 static void checkList(
54786 IntegrityCk *pCheck, /* Integrity checking context */
54787 int isFreeList, /* True for a freelist. False for overflow page list */
54788 int iPage, /* Page number for first page in the list */
54789 int N, /* Expected number of pages in the list */
54790 char *zContext /* Context for error messages */
54792 int i;
54793 int expected = N;
54794 int iFirst = iPage;
54795 while( N-- > 0 && pCheck->mxErr ){
54796 DbPage *pOvflPage;
54797 unsigned char *pOvflData;
54798 if( iPage<1 ){
54799 checkAppendMsg(pCheck, zContext,
54800 "%d of %d pages missing from overflow list starting at %d",
54801 N+1, expected, iFirst);
54802 break;
54804 if( checkRef(pCheck, iPage, zContext) ) break;
54805 if( sqlite3PagerGet(pCheck->pPager, (Pgno)iPage, &pOvflPage) ){
54806 checkAppendMsg(pCheck, zContext, "failed to get page %d", iPage);
54807 break;
54809 pOvflData = (unsigned char *)sqlite3PagerGetData(pOvflPage);
54810 if( isFreeList ){
54811 int n = get4byte(&pOvflData[4]);
54812 #ifndef SQLITE_OMIT_AUTOVACUUM
54813 if( pCheck->pBt->autoVacuum ){
54814 checkPtrmap(pCheck, iPage, PTRMAP_FREEPAGE, 0, zContext);
54816 #endif
54817 if( n>(int)pCheck->pBt->usableSize/4-2 ){
54818 checkAppendMsg(pCheck, zContext,
54819 "freelist leaf count too big on page %d", iPage);
54820 N--;
54821 }else{
54822 for(i=0; i<n; i++){
54823 Pgno iFreePage = get4byte(&pOvflData[8+i*4]);
54824 #ifndef SQLITE_OMIT_AUTOVACUUM
54825 if( pCheck->pBt->autoVacuum ){
54826 checkPtrmap(pCheck, iFreePage, PTRMAP_FREEPAGE, 0, zContext);
54828 #endif
54829 checkRef(pCheck, iFreePage, zContext);
54831 N -= n;
54834 #ifndef SQLITE_OMIT_AUTOVACUUM
54835 else{
54836 /* If this database supports auto-vacuum and iPage is not the last
54837 ** page in this overflow list, check that the pointer-map entry for
54838 ** the following page matches iPage.
54840 if( pCheck->pBt->autoVacuum && N>0 ){
54841 i = get4byte(pOvflData);
54842 checkPtrmap(pCheck, i, PTRMAP_OVERFLOW2, iPage, zContext);
54845 #endif
54846 iPage = get4byte(pOvflData);
54847 sqlite3PagerUnref(pOvflPage);
54850 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
54852 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
54854 ** Do various sanity checks on a single page of a tree. Return
54855 ** the tree depth. Root pages return 0. Parents of root pages
54856 ** return 1, and so forth.
54858 ** These checks are done:
54860 ** 1. Make sure that cells and freeblocks do not overlap
54861 ** but combine to completely cover the page.
54862 ** NO 2. Make sure cell keys are in order.
54863 ** NO 3. Make sure no key is less than or equal to zLowerBound.
54864 ** NO 4. Make sure no key is greater than or equal to zUpperBound.
54865 ** 5. Check the integrity of overflow pages.
54866 ** 6. Recursively call checkTreePage on all children.
54867 ** 7. Verify that the depth of all children is the same.
54868 ** 8. Make sure this page is at least 33% full or else it is
54869 ** the root of the tree.
54871 static int checkTreePage(
54872 IntegrityCk *pCheck, /* Context for the sanity check */
54873 int iPage, /* Page number of the page to check */
54874 char *zParentContext, /* Parent context */
54875 i64 *pnParentMinKey,
54876 i64 *pnParentMaxKey
54878 MemPage *pPage;
54879 int i, rc, depth, d2, pgno, cnt;
54880 int hdr, cellStart;
54881 int nCell;
54882 u8 *data;
54883 BtShared *pBt;
54884 int usableSize;
54885 char zContext[100];
54886 char *hit = 0;
54887 i64 nMinKey = 0;
54888 i64 nMaxKey = 0;
54890 sqlite3_snprintf(sizeof(zContext), zContext, "Page %d: ", iPage);
54892 /* Check that the page exists
54894 pBt = pCheck->pBt;
54895 usableSize = pBt->usableSize;
54896 if( iPage==0 ) return 0;
54897 if( checkRef(pCheck, iPage, zParentContext) ) return 0;
54898 if( (rc = btreeGetPage(pBt, (Pgno)iPage, &pPage, 0))!=0 ){
54899 checkAppendMsg(pCheck, zContext,
54900 "unable to get the page. error code=%d", rc);
54901 return 0;
54904 /* Clear MemPage.isInit to make sure the corruption detection code in
54905 ** btreeInitPage() is executed. */
54906 pPage->isInit = 0;
54907 if( (rc = btreeInitPage(pPage))!=0 ){
54908 assert( rc==SQLITE_CORRUPT ); /* The only possible error from InitPage */
54909 checkAppendMsg(pCheck, zContext,
54910 "btreeInitPage() returns error code %d", rc);
54911 releasePage(pPage);
54912 return 0;
54915 /* Check out all the cells.
54917 depth = 0;
54918 for(i=0; i<pPage->nCell && pCheck->mxErr; i++){
54919 u8 *pCell;
54920 u32 sz;
54921 CellInfo info;
54923 /* Check payload overflow pages
54925 sqlite3_snprintf(sizeof(zContext), zContext,
54926 "On tree page %d cell %d: ", iPage, i);
54927 pCell = findCell(pPage,i);
54928 btreeParseCellPtr(pPage, pCell, &info);
54929 sz = info.nData;
54930 if( !pPage->intKey ) sz += (int)info.nKey;
54931 /* For intKey pages, check that the keys are in order.
54933 else if( i==0 ) nMinKey = nMaxKey = info.nKey;
54934 else{
54935 if( info.nKey <= nMaxKey ){
54936 checkAppendMsg(pCheck, zContext,
54937 "Rowid %lld out of order (previous was %lld)", info.nKey, nMaxKey);
54939 nMaxKey = info.nKey;
54941 assert( sz==info.nPayload );
54942 if( (sz>info.nLocal)
54943 && (&pCell[info.iOverflow]<=&pPage->aData[pBt->usableSize])
54945 int nPage = (sz - info.nLocal + usableSize - 5)/(usableSize - 4);
54946 Pgno pgnoOvfl = get4byte(&pCell[info.iOverflow]);
54947 #ifndef SQLITE_OMIT_AUTOVACUUM
54948 if( pBt->autoVacuum ){
54949 checkPtrmap(pCheck, pgnoOvfl, PTRMAP_OVERFLOW1, iPage, zContext);
54951 #endif
54952 checkList(pCheck, 0, pgnoOvfl, nPage, zContext);
54955 /* Check sanity of left child page.
54957 if( !pPage->leaf ){
54958 pgno = get4byte(pCell);
54959 #ifndef SQLITE_OMIT_AUTOVACUUM
54960 if( pBt->autoVacuum ){
54961 checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage, zContext);
54963 #endif
54964 d2 = checkTreePage(pCheck, pgno, zContext, &nMinKey, i==0 ? NULL : &nMaxKey);
54965 if( i>0 && d2!=depth ){
54966 checkAppendMsg(pCheck, zContext, "Child page depth differs");
54968 depth = d2;
54972 if( !pPage->leaf ){
54973 pgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
54974 sqlite3_snprintf(sizeof(zContext), zContext,
54975 "On page %d at right child: ", iPage);
54976 #ifndef SQLITE_OMIT_AUTOVACUUM
54977 if( pBt->autoVacuum ){
54978 checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage, zContext);
54980 #endif
54981 checkTreePage(pCheck, pgno, zContext, NULL, !pPage->nCell ? NULL : &nMaxKey);
54984 /* For intKey leaf pages, check that the min/max keys are in order
54985 ** with any left/parent/right pages.
54987 if( pPage->leaf && pPage->intKey ){
54988 /* if we are a left child page */
54989 if( pnParentMinKey ){
54990 /* if we are the left most child page */
54991 if( !pnParentMaxKey ){
54992 if( nMaxKey > *pnParentMinKey ){
54993 checkAppendMsg(pCheck, zContext,
54994 "Rowid %lld out of order (max larger than parent min of %lld)",
54995 nMaxKey, *pnParentMinKey);
54997 }else{
54998 if( nMinKey <= *pnParentMinKey ){
54999 checkAppendMsg(pCheck, zContext,
55000 "Rowid %lld out of order (min less than parent min of %lld)",
55001 nMinKey, *pnParentMinKey);
55003 if( nMaxKey > *pnParentMaxKey ){
55004 checkAppendMsg(pCheck, zContext,
55005 "Rowid %lld out of order (max larger than parent max of %lld)",
55006 nMaxKey, *pnParentMaxKey);
55008 *pnParentMinKey = nMaxKey;
55010 /* else if we're a right child page */
55011 } else if( pnParentMaxKey ){
55012 if( nMinKey <= *pnParentMaxKey ){
55013 checkAppendMsg(pCheck, zContext,
55014 "Rowid %lld out of order (min less than parent max of %lld)",
55015 nMinKey, *pnParentMaxKey);
55020 /* Check for complete coverage of the page
55022 data = pPage->aData;
55023 hdr = pPage->hdrOffset;
55024 hit = sqlite3PageMalloc( pBt->pageSize );
55025 if( hit==0 ){
55026 pCheck->mallocFailed = 1;
55027 }else{
55028 int contentOffset = get2byteNotZero(&data[hdr+5]);
55029 assert( contentOffset<=usableSize ); /* Enforced by btreeInitPage() */
55030 memset(hit+contentOffset, 0, usableSize-contentOffset);
55031 memset(hit, 1, contentOffset);
55032 nCell = get2byte(&data[hdr+3]);
55033 cellStart = hdr + 12 - 4*pPage->leaf;
55034 for(i=0; i<nCell; i++){
55035 int pc = get2byte(&data[cellStart+i*2]);
55036 u32 size = 65536;
55037 int j;
55038 if( pc<=usableSize-4 ){
55039 size = cellSizePtr(pPage, &data[pc]);
55041 if( (int)(pc+size-1)>=usableSize ){
55042 checkAppendMsg(pCheck, 0,
55043 "Corruption detected in cell %d on page %d",i,iPage);
55044 }else{
55045 for(j=pc+size-1; j>=pc; j--) hit[j]++;
55048 i = get2byte(&data[hdr+1]);
55049 while( i>0 ){
55050 int size, j;
55051 assert( i<=usableSize-4 ); /* Enforced by btreeInitPage() */
55052 size = get2byte(&data[i+2]);
55053 assert( i+size<=usableSize ); /* Enforced by btreeInitPage() */
55054 for(j=i+size-1; j>=i; j--) hit[j]++;
55055 j = get2byte(&data[i]);
55056 assert( j==0 || j>i+size ); /* Enforced by btreeInitPage() */
55057 assert( j<=usableSize-4 ); /* Enforced by btreeInitPage() */
55058 i = j;
55060 for(i=cnt=0; i<usableSize; i++){
55061 if( hit[i]==0 ){
55062 cnt++;
55063 }else if( hit[i]>1 ){
55064 checkAppendMsg(pCheck, 0,
55065 "Multiple uses for byte %d of page %d", i, iPage);
55066 break;
55069 if( cnt!=data[hdr+7] ){
55070 checkAppendMsg(pCheck, 0,
55071 "Fragmentation of %d bytes reported as %d on page %d",
55072 cnt, data[hdr+7], iPage);
55075 sqlite3PageFree(hit);
55076 releasePage(pPage);
55077 return depth+1;
55079 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
55081 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
55083 ** This routine does a complete check of the given BTree file. aRoot[] is
55084 ** an array of pages numbers were each page number is the root page of
55085 ** a table. nRoot is the number of entries in aRoot.
55087 ** A read-only or read-write transaction must be opened before calling
55088 ** this function.
55090 ** Write the number of error seen in *pnErr. Except for some memory
55091 ** allocation errors, an error message held in memory obtained from
55092 ** malloc is returned if *pnErr is non-zero. If *pnErr==0 then NULL is
55093 ** returned. If a memory allocation error occurs, NULL is returned.
55095 SQLITE_PRIVATE char *sqlite3BtreeIntegrityCheck(
55096 Btree *p, /* The btree to be checked */
55097 int *aRoot, /* An array of root pages numbers for individual trees */
55098 int nRoot, /* Number of entries in aRoot[] */
55099 int mxErr, /* Stop reporting errors after this many */
55100 int *pnErr /* Write number of errors seen to this variable */
55102 Pgno i;
55103 int nRef;
55104 IntegrityCk sCheck;
55105 BtShared *pBt = p->pBt;
55106 char zErr[100];
55108 sqlite3BtreeEnter(p);
55109 assert( p->inTrans>TRANS_NONE && pBt->inTransaction>TRANS_NONE );
55110 nRef = sqlite3PagerRefcount(pBt->pPager);
55111 sCheck.pBt = pBt;
55112 sCheck.pPager = pBt->pPager;
55113 sCheck.nPage = btreePagecount(sCheck.pBt);
55114 sCheck.mxErr = mxErr;
55115 sCheck.nErr = 0;
55116 sCheck.mallocFailed = 0;
55117 *pnErr = 0;
55118 if( sCheck.nPage==0 ){
55119 sqlite3BtreeLeave(p);
55120 return 0;
55122 sCheck.anRef = sqlite3Malloc( (sCheck.nPage+1)*sizeof(sCheck.anRef[0]) );
55123 if( !sCheck.anRef ){
55124 *pnErr = 1;
55125 sqlite3BtreeLeave(p);
55126 return 0;
55128 for(i=0; i<=sCheck.nPage; i++){ sCheck.anRef[i] = 0; }
55129 i = PENDING_BYTE_PAGE(pBt);
55130 if( i<=sCheck.nPage ){
55131 sCheck.anRef[i] = 1;
55133 sqlite3StrAccumInit(&sCheck.errMsg, zErr, sizeof(zErr), 20000);
55134 sCheck.errMsg.useMalloc = 2;
55136 /* Check the integrity of the freelist
55138 checkList(&sCheck, 1, get4byte(&pBt->pPage1->aData[32]),
55139 get4byte(&pBt->pPage1->aData[36]), "Main freelist: ");
55141 /* Check all the tables.
55143 for(i=0; (int)i<nRoot && sCheck.mxErr; i++){
55144 if( aRoot[i]==0 ) continue;
55145 #ifndef SQLITE_OMIT_AUTOVACUUM
55146 if( pBt->autoVacuum && aRoot[i]>1 ){
55147 checkPtrmap(&sCheck, aRoot[i], PTRMAP_ROOTPAGE, 0, 0);
55149 #endif
55150 checkTreePage(&sCheck, aRoot[i], "List of tree roots: ", NULL, NULL);
55153 /* Make sure every page in the file is referenced
55155 for(i=1; i<=sCheck.nPage && sCheck.mxErr; i++){
55156 #ifdef SQLITE_OMIT_AUTOVACUUM
55157 if( sCheck.anRef[i]==0 ){
55158 checkAppendMsg(&sCheck, 0, "Page %d is never used", i);
55160 #else
55161 /* If the database supports auto-vacuum, make sure no tables contain
55162 ** references to pointer-map pages.
55164 if( sCheck.anRef[i]==0 &&
55165 (PTRMAP_PAGENO(pBt, i)!=i || !pBt->autoVacuum) ){
55166 checkAppendMsg(&sCheck, 0, "Page %d is never used", i);
55168 if( sCheck.anRef[i]!=0 &&
55169 (PTRMAP_PAGENO(pBt, i)==i && pBt->autoVacuum) ){
55170 checkAppendMsg(&sCheck, 0, "Pointer map page %d is referenced", i);
55172 #endif
55175 /* Make sure this analysis did not leave any unref() pages.
55176 ** This is an internal consistency check; an integrity check
55177 ** of the integrity check.
55179 if( NEVER(nRef != sqlite3PagerRefcount(pBt->pPager)) ){
55180 checkAppendMsg(&sCheck, 0,
55181 "Outstanding page count goes from %d to %d during this analysis",
55182 nRef, sqlite3PagerRefcount(pBt->pPager)
55186 /* Clean up and report errors.
55188 sqlite3BtreeLeave(p);
55189 sqlite3_free(sCheck.anRef);
55190 if( sCheck.mallocFailed ){
55191 sqlite3StrAccumReset(&sCheck.errMsg);
55192 *pnErr = sCheck.nErr+1;
55193 return 0;
55195 *pnErr = sCheck.nErr;
55196 if( sCheck.nErr==0 ) sqlite3StrAccumReset(&sCheck.errMsg);
55197 return sqlite3StrAccumFinish(&sCheck.errMsg);
55199 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
55202 ** Return the full pathname of the underlying database file.
55204 ** The pager filename is invariant as long as the pager is
55205 ** open so it is safe to access without the BtShared mutex.
55207 SQLITE_PRIVATE const char *sqlite3BtreeGetFilename(Btree *p){
55208 assert( p->pBt->pPager!=0 );
55209 return sqlite3PagerFilename(p->pBt->pPager);
55213 ** Return the pathname of the journal file for this database. The return
55214 ** value of this routine is the same regardless of whether the journal file
55215 ** has been created or not.
55217 ** The pager journal filename is invariant as long as the pager is
55218 ** open so it is safe to access without the BtShared mutex.
55220 SQLITE_PRIVATE const char *sqlite3BtreeGetJournalname(Btree *p){
55221 assert( p->pBt->pPager!=0 );
55222 return sqlite3PagerJournalname(p->pBt->pPager);
55226 ** Return non-zero if a transaction is active.
55228 SQLITE_PRIVATE int sqlite3BtreeIsInTrans(Btree *p){
55229 assert( p==0 || sqlite3_mutex_held(p->db->mutex) );
55230 return (p && (p->inTrans==TRANS_WRITE));
55233 #ifndef SQLITE_OMIT_WAL
55235 ** Run a checkpoint on the Btree passed as the first argument.
55237 ** Return SQLITE_LOCKED if this or any other connection has an open
55238 ** transaction on the shared-cache the argument Btree is connected to.
55240 ** Parameter eMode is one of SQLITE_CHECKPOINT_PASSIVE, FULL or RESTART.
55242 SQLITE_PRIVATE int sqlite3BtreeCheckpoint(Btree *p, int eMode, int *pnLog, int *pnCkpt){
55243 int rc = SQLITE_OK;
55244 if( p ){
55245 BtShared *pBt = p->pBt;
55246 sqlite3BtreeEnter(p);
55247 if( pBt->inTransaction!=TRANS_NONE ){
55248 rc = SQLITE_LOCKED;
55249 }else{
55250 rc = sqlite3PagerCheckpoint(pBt->pPager, eMode, pnLog, pnCkpt);
55252 sqlite3BtreeLeave(p);
55254 return rc;
55256 #endif
55259 ** Return non-zero if a read (or write) transaction is active.
55261 SQLITE_PRIVATE int sqlite3BtreeIsInReadTrans(Btree *p){
55262 assert( p );
55263 assert( sqlite3_mutex_held(p->db->mutex) );
55264 return p->inTrans!=TRANS_NONE;
55267 SQLITE_PRIVATE int sqlite3BtreeIsInBackup(Btree *p){
55268 assert( p );
55269 assert( sqlite3_mutex_held(p->db->mutex) );
55270 return p->nBackup!=0;
55274 ** This function returns a pointer to a blob of memory associated with
55275 ** a single shared-btree. The memory is used by client code for its own
55276 ** purposes (for example, to store a high-level schema associated with
55277 ** the shared-btree). The btree layer manages reference counting issues.
55279 ** The first time this is called on a shared-btree, nBytes bytes of memory
55280 ** are allocated, zeroed, and returned to the caller. For each subsequent
55281 ** call the nBytes parameter is ignored and a pointer to the same blob
55282 ** of memory returned.
55284 ** If the nBytes parameter is 0 and the blob of memory has not yet been
55285 ** allocated, a null pointer is returned. If the blob has already been
55286 ** allocated, it is returned as normal.
55288 ** Just before the shared-btree is closed, the function passed as the
55289 ** xFree argument when the memory allocation was made is invoked on the
55290 ** blob of allocated memory. The xFree function should not call sqlite3_free()
55291 ** on the memory, the btree layer does that.
55293 SQLITE_PRIVATE void *sqlite3BtreeSchema(Btree *p, int nBytes, void(*xFree)(void *)){
55294 BtShared *pBt = p->pBt;
55295 sqlite3BtreeEnter(p);
55296 if( !pBt->pSchema && nBytes ){
55297 pBt->pSchema = sqlite3DbMallocZero(0, nBytes);
55298 pBt->xFreeSchema = xFree;
55300 sqlite3BtreeLeave(p);
55301 return pBt->pSchema;
55305 ** Return SQLITE_LOCKED_SHAREDCACHE if another user of the same shared
55306 ** btree as the argument handle holds an exclusive lock on the
55307 ** sqlite_master table. Otherwise SQLITE_OK.
55309 SQLITE_PRIVATE int sqlite3BtreeSchemaLocked(Btree *p){
55310 int rc;
55311 assert( sqlite3_mutex_held(p->db->mutex) );
55312 sqlite3BtreeEnter(p);
55313 rc = querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK);
55314 assert( rc==SQLITE_OK || rc==SQLITE_LOCKED_SHAREDCACHE );
55315 sqlite3BtreeLeave(p);
55316 return rc;
55320 #ifndef SQLITE_OMIT_SHARED_CACHE
55322 ** Obtain a lock on the table whose root page is iTab. The
55323 ** lock is a write lock if isWritelock is true or a read lock
55324 ** if it is false.
55326 SQLITE_PRIVATE int sqlite3BtreeLockTable(Btree *p, int iTab, u8 isWriteLock){
55327 int rc = SQLITE_OK;
55328 assert( p->inTrans!=TRANS_NONE );
55329 if( p->sharable ){
55330 u8 lockType = READ_LOCK + isWriteLock;
55331 assert( READ_LOCK+1==WRITE_LOCK );
55332 assert( isWriteLock==0 || isWriteLock==1 );
55334 sqlite3BtreeEnter(p);
55335 rc = querySharedCacheTableLock(p, iTab, lockType);
55336 if( rc==SQLITE_OK ){
55337 rc = setSharedCacheTableLock(p, iTab, lockType);
55339 sqlite3BtreeLeave(p);
55341 return rc;
55343 #endif
55345 #ifndef SQLITE_OMIT_INCRBLOB
55347 ** Argument pCsr must be a cursor opened for writing on an
55348 ** INTKEY table currently pointing at a valid table entry.
55349 ** This function modifies the data stored as part of that entry.
55351 ** Only the data content may only be modified, it is not possible to
55352 ** change the length of the data stored. If this function is called with
55353 ** parameters that attempt to write past the end of the existing data,
55354 ** no modifications are made and SQLITE_CORRUPT is returned.
55356 SQLITE_PRIVATE int sqlite3BtreePutData(BtCursor *pCsr, u32 offset, u32 amt, void *z){
55357 int rc;
55358 assert( cursorHoldsMutex(pCsr) );
55359 assert( sqlite3_mutex_held(pCsr->pBtree->db->mutex) );
55360 assert( pCsr->isIncrblobHandle );
55362 rc = restoreCursorPosition(pCsr);
55363 if( rc!=SQLITE_OK ){
55364 return rc;
55366 assert( pCsr->eState!=CURSOR_REQUIRESEEK );
55367 if( pCsr->eState!=CURSOR_VALID ){
55368 return SQLITE_ABORT;
55371 /* Check some assumptions:
55372 ** (a) the cursor is open for writing,
55373 ** (b) there is a read/write transaction open,
55374 ** (c) the connection holds a write-lock on the table (if required),
55375 ** (d) there are no conflicting read-locks, and
55376 ** (e) the cursor points at a valid row of an intKey table.
55378 if( !pCsr->wrFlag ){
55379 return SQLITE_READONLY;
55381 assert( !pCsr->pBt->readOnly && pCsr->pBt->inTransaction==TRANS_WRITE );
55382 assert( hasSharedCacheTableLock(pCsr->pBtree, pCsr->pgnoRoot, 0, 2) );
55383 assert( !hasReadConflicts(pCsr->pBtree, pCsr->pgnoRoot) );
55384 assert( pCsr->apPage[pCsr->iPage]->intKey );
55386 return accessPayload(pCsr, offset, amt, (unsigned char *)z, 1);
55390 ** Set a flag on this cursor to cache the locations of pages from the
55391 ** overflow list for the current row. This is used by cursors opened
55392 ** for incremental blob IO only.
55394 ** This function sets a flag only. The actual page location cache
55395 ** (stored in BtCursor.aOverflow[]) is allocated and used by function
55396 ** accessPayload() (the worker function for sqlite3BtreeData() and
55397 ** sqlite3BtreePutData()).
55399 SQLITE_PRIVATE void sqlite3BtreeCacheOverflow(BtCursor *pCur){
55400 assert( cursorHoldsMutex(pCur) );
55401 assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
55402 invalidateOverflowCache(pCur);
55403 pCur->isIncrblobHandle = 1;
55405 #endif
55408 ** Set both the "read version" (single byte at byte offset 18) and
55409 ** "write version" (single byte at byte offset 19) fields in the database
55410 ** header to iVersion.
55412 SQLITE_PRIVATE int sqlite3BtreeSetVersion(Btree *pBtree, int iVersion){
55413 BtShared *pBt = pBtree->pBt;
55414 int rc; /* Return code */
55416 assert( pBtree->inTrans==TRANS_NONE );
55417 assert( iVersion==1 || iVersion==2 );
55419 /* If setting the version fields to 1, do not automatically open the
55420 ** WAL connection, even if the version fields are currently set to 2.
55422 pBt->doNotUseWAL = (u8)(iVersion==1);
55424 rc = sqlite3BtreeBeginTrans(pBtree, 0);
55425 if( rc==SQLITE_OK ){
55426 u8 *aData = pBt->pPage1->aData;
55427 if( aData[18]!=(u8)iVersion || aData[19]!=(u8)iVersion ){
55428 rc = sqlite3BtreeBeginTrans(pBtree, 2);
55429 if( rc==SQLITE_OK ){
55430 rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
55431 if( rc==SQLITE_OK ){
55432 aData[18] = (u8)iVersion;
55433 aData[19] = (u8)iVersion;
55439 pBt->doNotUseWAL = 0;
55440 return rc;
55443 /************** End of btree.c ***********************************************/
55444 /************** Begin file backup.c ******************************************/
55446 ** 2009 January 28
55448 ** The author disclaims copyright to this source code. In place of
55449 ** a legal notice, here is a blessing:
55451 ** May you do good and not evil.
55452 ** May you find forgiveness for yourself and forgive others.
55453 ** May you share freely, never taking more than you give.
55455 *************************************************************************
55456 ** This file contains the implementation of the sqlite3_backup_XXX()
55457 ** API functions and the related features.
55460 /* Macro to find the minimum of two numeric values.
55462 #ifndef MIN
55463 # define MIN(x,y) ((x)<(y)?(x):(y))
55464 #endif
55467 ** Structure allocated for each backup operation.
55469 struct sqlite3_backup {
55470 sqlite3* pDestDb; /* Destination database handle */
55471 Btree *pDest; /* Destination b-tree file */
55472 u32 iDestSchema; /* Original schema cookie in destination */
55473 int bDestLocked; /* True once a write-transaction is open on pDest */
55475 Pgno iNext; /* Page number of the next source page to copy */
55476 sqlite3* pSrcDb; /* Source database handle */
55477 Btree *pSrc; /* Source b-tree file */
55479 int rc; /* Backup process error code */
55481 /* These two variables are set by every call to backup_step(). They are
55482 ** read by calls to backup_remaining() and backup_pagecount().
55484 Pgno nRemaining; /* Number of pages left to copy */
55485 Pgno nPagecount; /* Total number of pages to copy */
55487 int isAttached; /* True once backup has been registered with pager */
55488 sqlite3_backup *pNext; /* Next backup associated with source pager */
55492 ** THREAD SAFETY NOTES:
55494 ** Once it has been created using backup_init(), a single sqlite3_backup
55495 ** structure may be accessed via two groups of thread-safe entry points:
55497 ** * Via the sqlite3_backup_XXX() API function backup_step() and
55498 ** backup_finish(). Both these functions obtain the source database
55499 ** handle mutex and the mutex associated with the source BtShared
55500 ** structure, in that order.
55502 ** * Via the BackupUpdate() and BackupRestart() functions, which are
55503 ** invoked by the pager layer to report various state changes in
55504 ** the page cache associated with the source database. The mutex
55505 ** associated with the source database BtShared structure will always
55506 ** be held when either of these functions are invoked.
55508 ** The other sqlite3_backup_XXX() API functions, backup_remaining() and
55509 ** backup_pagecount() are not thread-safe functions. If they are called
55510 ** while some other thread is calling backup_step() or backup_finish(),
55511 ** the values returned may be invalid. There is no way for a call to
55512 ** BackupUpdate() or BackupRestart() to interfere with backup_remaining()
55513 ** or backup_pagecount().
55515 ** Depending on the SQLite configuration, the database handles and/or
55516 ** the Btree objects may have their own mutexes that require locking.
55517 ** Non-sharable Btrees (in-memory databases for example), do not have
55518 ** associated mutexes.
55522 ** Return a pointer corresponding to database zDb (i.e. "main", "temp")
55523 ** in connection handle pDb. If such a database cannot be found, return
55524 ** a NULL pointer and write an error message to pErrorDb.
55526 ** If the "temp" database is requested, it may need to be opened by this
55527 ** function. If an error occurs while doing so, return 0 and write an
55528 ** error message to pErrorDb.
55530 static Btree *findBtree(sqlite3 *pErrorDb, sqlite3 *pDb, const char *zDb){
55531 int i = sqlite3FindDbName(pDb, zDb);
55533 if( i==1 ){
55534 Parse *pParse;
55535 int rc = 0;
55536 pParse = sqlite3StackAllocZero(pErrorDb, sizeof(*pParse));
55537 if( pParse==0 ){
55538 sqlite3Error(pErrorDb, SQLITE_NOMEM, "out of memory");
55539 rc = SQLITE_NOMEM;
55540 }else{
55541 pParse->db = pDb;
55542 if( sqlite3OpenTempDatabase(pParse) ){
55543 sqlite3Error(pErrorDb, pParse->rc, "%s", pParse->zErrMsg);
55544 rc = SQLITE_ERROR;
55546 sqlite3DbFree(pErrorDb, pParse->zErrMsg);
55547 sqlite3StackFree(pErrorDb, pParse);
55549 if( rc ){
55550 return 0;
55554 if( i<0 ){
55555 sqlite3Error(pErrorDb, SQLITE_ERROR, "unknown database %s", zDb);
55556 return 0;
55559 return pDb->aDb[i].pBt;
55563 ** Attempt to set the page size of the destination to match the page size
55564 ** of the source.
55566 static int setDestPgsz(sqlite3_backup *p){
55567 int rc;
55568 rc = sqlite3BtreeSetPageSize(p->pDest,sqlite3BtreeGetPageSize(p->pSrc),-1,0);
55569 return rc;
55573 ** Create an sqlite3_backup process to copy the contents of zSrcDb from
55574 ** connection handle pSrcDb to zDestDb in pDestDb. If successful, return
55575 ** a pointer to the new sqlite3_backup object.
55577 ** If an error occurs, NULL is returned and an error code and error message
55578 ** stored in database handle pDestDb.
55580 SQLITE_API sqlite3_backup *sqlite3_backup_init(
55581 sqlite3* pDestDb, /* Database to write to */
55582 const char *zDestDb, /* Name of database within pDestDb */
55583 sqlite3* pSrcDb, /* Database connection to read from */
55584 const char *zSrcDb /* Name of database within pSrcDb */
55586 sqlite3_backup *p; /* Value to return */
55588 /* Lock the source database handle. The destination database
55589 ** handle is not locked in this routine, but it is locked in
55590 ** sqlite3_backup_step(). The user is required to ensure that no
55591 ** other thread accesses the destination handle for the duration
55592 ** of the backup operation. Any attempt to use the destination
55593 ** database connection while a backup is in progress may cause
55594 ** a malfunction or a deadlock.
55596 sqlite3_mutex_enter(pSrcDb->mutex);
55597 sqlite3_mutex_enter(pDestDb->mutex);
55599 if( pSrcDb==pDestDb ){
55600 sqlite3Error(
55601 pDestDb, SQLITE_ERROR, "source and destination must be distinct"
55603 p = 0;
55604 }else {
55605 /* Allocate space for a new sqlite3_backup object...
55606 ** EVIDENCE-OF: R-64852-21591 The sqlite3_backup object is created by a
55607 ** call to sqlite3_backup_init() and is destroyed by a call to
55608 ** sqlite3_backup_finish(). */
55609 p = (sqlite3_backup *)sqlite3_malloc(sizeof(sqlite3_backup));
55610 if( !p ){
55611 sqlite3Error(pDestDb, SQLITE_NOMEM, 0);
55615 /* If the allocation succeeded, populate the new object. */
55616 if( p ){
55617 memset(p, 0, sizeof(sqlite3_backup));
55618 p->pSrc = findBtree(pDestDb, pSrcDb, zSrcDb);
55619 p->pDest = findBtree(pDestDb, pDestDb, zDestDb);
55620 p->pDestDb = pDestDb;
55621 p->pSrcDb = pSrcDb;
55622 p->iNext = 1;
55623 p->isAttached = 0;
55625 if( 0==p->pSrc || 0==p->pDest || setDestPgsz(p)==SQLITE_NOMEM ){
55626 /* One (or both) of the named databases did not exist or an OOM
55627 ** error was hit. The error has already been written into the
55628 ** pDestDb handle. All that is left to do here is free the
55629 ** sqlite3_backup structure.
55631 sqlite3_free(p);
55632 p = 0;
55635 if( p ){
55636 p->pSrc->nBackup++;
55639 sqlite3_mutex_leave(pDestDb->mutex);
55640 sqlite3_mutex_leave(pSrcDb->mutex);
55641 return p;
55645 ** Argument rc is an SQLite error code. Return true if this error is
55646 ** considered fatal if encountered during a backup operation. All errors
55647 ** are considered fatal except for SQLITE_BUSY and SQLITE_LOCKED.
55649 static int isFatalError(int rc){
55650 return (rc!=SQLITE_OK && rc!=SQLITE_BUSY && ALWAYS(rc!=SQLITE_LOCKED));
55654 ** Parameter zSrcData points to a buffer containing the data for
55655 ** page iSrcPg from the source database. Copy this data into the
55656 ** destination database.
55658 static int backupOnePage(sqlite3_backup *p, Pgno iSrcPg, const u8 *zSrcData){
55659 Pager * const pDestPager = sqlite3BtreePager(p->pDest);
55660 const int nSrcPgsz = sqlite3BtreeGetPageSize(p->pSrc);
55661 int nDestPgsz = sqlite3BtreeGetPageSize(p->pDest);
55662 const int nCopy = MIN(nSrcPgsz, nDestPgsz);
55663 const i64 iEnd = (i64)iSrcPg*(i64)nSrcPgsz;
55664 #ifdef SQLITE_HAS_CODEC
55665 int nSrcReserve = sqlite3BtreeGetReserve(p->pSrc);
55666 int nDestReserve = sqlite3BtreeGetReserve(p->pDest);
55667 #endif
55669 int rc = SQLITE_OK;
55670 i64 iOff;
55672 assert( p->bDestLocked );
55673 assert( !isFatalError(p->rc) );
55674 assert( iSrcPg!=PENDING_BYTE_PAGE(p->pSrc->pBt) );
55675 assert( zSrcData );
55677 /* Catch the case where the destination is an in-memory database and the
55678 ** page sizes of the source and destination differ.
55680 if( nSrcPgsz!=nDestPgsz && sqlite3PagerIsMemdb(pDestPager) ){
55681 rc = SQLITE_READONLY;
55684 #ifdef SQLITE_HAS_CODEC
55685 /* Backup is not possible if the page size of the destination is changing
55686 ** and a codec is in use.
55688 if( nSrcPgsz!=nDestPgsz && sqlite3PagerGetCodec(pDestPager)!=0 ){
55689 rc = SQLITE_READONLY;
55692 /* Backup is not possible if the number of bytes of reserve space differ
55693 ** between source and destination. If there is a difference, try to
55694 ** fix the destination to agree with the source. If that is not possible,
55695 ** then the backup cannot proceed.
55697 if( nSrcReserve!=nDestReserve ){
55698 u32 newPgsz = nSrcPgsz;
55699 rc = sqlite3PagerSetPagesize(pDestPager, &newPgsz, nSrcReserve);
55700 if( rc==SQLITE_OK && newPgsz!=nSrcPgsz ) rc = SQLITE_READONLY;
55702 #endif
55704 /* This loop runs once for each destination page spanned by the source
55705 ** page. For each iteration, variable iOff is set to the byte offset
55706 ** of the destination page.
55708 for(iOff=iEnd-(i64)nSrcPgsz; rc==SQLITE_OK && iOff<iEnd; iOff+=nDestPgsz){
55709 DbPage *pDestPg = 0;
55710 Pgno iDest = (Pgno)(iOff/nDestPgsz)+1;
55711 if( iDest==PENDING_BYTE_PAGE(p->pDest->pBt) ) continue;
55712 if( SQLITE_OK==(rc = sqlite3PagerGet(pDestPager, iDest, &pDestPg))
55713 && SQLITE_OK==(rc = sqlite3PagerWrite(pDestPg))
55715 const u8 *zIn = &zSrcData[iOff%nSrcPgsz];
55716 u8 *zDestData = sqlite3PagerGetData(pDestPg);
55717 u8 *zOut = &zDestData[iOff%nDestPgsz];
55719 /* Copy the data from the source page into the destination page.
55720 ** Then clear the Btree layer MemPage.isInit flag. Both this module
55721 ** and the pager code use this trick (clearing the first byte
55722 ** of the page 'extra' space to invalidate the Btree layers
55723 ** cached parse of the page). MemPage.isInit is marked
55724 ** "MUST BE FIRST" for this purpose.
55726 memcpy(zOut, zIn, nCopy);
55727 ((u8 *)sqlite3PagerGetExtra(pDestPg))[0] = 0;
55729 sqlite3PagerUnref(pDestPg);
55732 return rc;
55736 ** If pFile is currently larger than iSize bytes, then truncate it to
55737 ** exactly iSize bytes. If pFile is not larger than iSize bytes, then
55738 ** this function is a no-op.
55740 ** Return SQLITE_OK if everything is successful, or an SQLite error
55741 ** code if an error occurs.
55743 static int backupTruncateFile(sqlite3_file *pFile, i64 iSize){
55744 i64 iCurrent;
55745 int rc = sqlite3OsFileSize(pFile, &iCurrent);
55746 if( rc==SQLITE_OK && iCurrent>iSize ){
55747 rc = sqlite3OsTruncate(pFile, iSize);
55749 return rc;
55753 ** Register this backup object with the associated source pager for
55754 ** callbacks when pages are changed or the cache invalidated.
55756 static void attachBackupObject(sqlite3_backup *p){
55757 sqlite3_backup **pp;
55758 assert( sqlite3BtreeHoldsMutex(p->pSrc) );
55759 pp = sqlite3PagerBackupPtr(sqlite3BtreePager(p->pSrc));
55760 p->pNext = *pp;
55761 *pp = p;
55762 p->isAttached = 1;
55766 ** Copy nPage pages from the source b-tree to the destination.
55768 SQLITE_API int sqlite3_backup_step(sqlite3_backup *p, int nPage){
55769 int rc;
55770 int destMode; /* Destination journal mode */
55771 int pgszSrc = 0; /* Source page size */
55772 int pgszDest = 0; /* Destination page size */
55774 sqlite3_mutex_enter(p->pSrcDb->mutex);
55775 sqlite3BtreeEnter(p->pSrc);
55776 if( p->pDestDb ){
55777 sqlite3_mutex_enter(p->pDestDb->mutex);
55780 rc = p->rc;
55781 if( !isFatalError(rc) ){
55782 Pager * const pSrcPager = sqlite3BtreePager(p->pSrc); /* Source pager */
55783 Pager * const pDestPager = sqlite3BtreePager(p->pDest); /* Dest pager */
55784 int ii; /* Iterator variable */
55785 int nSrcPage = -1; /* Size of source db in pages */
55786 int bCloseTrans = 0; /* True if src db requires unlocking */
55788 /* If the source pager is currently in a write-transaction, return
55789 ** SQLITE_BUSY immediately.
55791 if( p->pDestDb && p->pSrc->pBt->inTransaction==TRANS_WRITE ){
55792 rc = SQLITE_BUSY;
55793 }else{
55794 rc = SQLITE_OK;
55797 /* Lock the destination database, if it is not locked already. */
55798 if( SQLITE_OK==rc && p->bDestLocked==0
55799 && SQLITE_OK==(rc = sqlite3BtreeBeginTrans(p->pDest, 2))
55801 p->bDestLocked = 1;
55802 sqlite3BtreeGetMeta(p->pDest, BTREE_SCHEMA_VERSION, &p->iDestSchema);
55805 /* If there is no open read-transaction on the source database, open
55806 ** one now. If a transaction is opened here, then it will be closed
55807 ** before this function exits.
55809 if( rc==SQLITE_OK && 0==sqlite3BtreeIsInReadTrans(p->pSrc) ){
55810 rc = sqlite3BtreeBeginTrans(p->pSrc, 0);
55811 bCloseTrans = 1;
55814 /* Do not allow backup if the destination database is in WAL mode
55815 ** and the page sizes are different between source and destination */
55816 pgszSrc = sqlite3BtreeGetPageSize(p->pSrc);
55817 pgszDest = sqlite3BtreeGetPageSize(p->pDest);
55818 destMode = sqlite3PagerGetJournalMode(sqlite3BtreePager(p->pDest));
55819 if( SQLITE_OK==rc && destMode==PAGER_JOURNALMODE_WAL && pgszSrc!=pgszDest ){
55820 rc = SQLITE_READONLY;
55823 /* Now that there is a read-lock on the source database, query the
55824 ** source pager for the number of pages in the database.
55826 nSrcPage = (int)sqlite3BtreeLastPage(p->pSrc);
55827 assert( nSrcPage>=0 );
55828 for(ii=0; (nPage<0 || ii<nPage) && p->iNext<=(Pgno)nSrcPage && !rc; ii++){
55829 const Pgno iSrcPg = p->iNext; /* Source page number */
55830 if( iSrcPg!=PENDING_BYTE_PAGE(p->pSrc->pBt) ){
55831 DbPage *pSrcPg; /* Source page object */
55832 rc = sqlite3PagerGet(pSrcPager, iSrcPg, &pSrcPg);
55833 if( rc==SQLITE_OK ){
55834 rc = backupOnePage(p, iSrcPg, sqlite3PagerGetData(pSrcPg));
55835 sqlite3PagerUnref(pSrcPg);
55838 p->iNext++;
55840 if( rc==SQLITE_OK ){
55841 p->nPagecount = nSrcPage;
55842 p->nRemaining = nSrcPage+1-p->iNext;
55843 if( p->iNext>(Pgno)nSrcPage ){
55844 rc = SQLITE_DONE;
55845 }else if( !p->isAttached ){
55846 attachBackupObject(p);
55850 /* Update the schema version field in the destination database. This
55851 ** is to make sure that the schema-version really does change in
55852 ** the case where the source and destination databases have the
55853 ** same schema version.
55855 if( rc==SQLITE_DONE
55856 && (rc = sqlite3BtreeUpdateMeta(p->pDest,1,p->iDestSchema+1))==SQLITE_OK
55858 int nDestTruncate;
55860 if( p->pDestDb ){
55861 sqlite3ResetInternalSchema(p->pDestDb, -1);
55864 /* Set nDestTruncate to the final number of pages in the destination
55865 ** database. The complication here is that the destination page
55866 ** size may be different to the source page size.
55868 ** If the source page size is smaller than the destination page size,
55869 ** round up. In this case the call to sqlite3OsTruncate() below will
55870 ** fix the size of the file. However it is important to call
55871 ** sqlite3PagerTruncateImage() here so that any pages in the
55872 ** destination file that lie beyond the nDestTruncate page mark are
55873 ** journalled by PagerCommitPhaseOne() before they are destroyed
55874 ** by the file truncation.
55876 assert( pgszSrc==sqlite3BtreeGetPageSize(p->pSrc) );
55877 assert( pgszDest==sqlite3BtreeGetPageSize(p->pDest) );
55878 if( pgszSrc<pgszDest ){
55879 int ratio = pgszDest/pgszSrc;
55880 nDestTruncate = (nSrcPage+ratio-1)/ratio;
55881 if( nDestTruncate==(int)PENDING_BYTE_PAGE(p->pDest->pBt) ){
55882 nDestTruncate--;
55884 }else{
55885 nDestTruncate = nSrcPage * (pgszSrc/pgszDest);
55887 sqlite3PagerTruncateImage(pDestPager, nDestTruncate);
55889 if( pgszSrc<pgszDest ){
55890 /* If the source page-size is smaller than the destination page-size,
55891 ** two extra things may need to happen:
55893 ** * The destination may need to be truncated, and
55895 ** * Data stored on the pages immediately following the
55896 ** pending-byte page in the source database may need to be
55897 ** copied into the destination database.
55899 const i64 iSize = (i64)pgszSrc * (i64)nSrcPage;
55900 sqlite3_file * const pFile = sqlite3PagerFile(pDestPager);
55901 i64 iOff;
55902 i64 iEnd;
55904 assert( pFile );
55905 assert( (i64)nDestTruncate*(i64)pgszDest >= iSize || (
55906 nDestTruncate==(int)(PENDING_BYTE_PAGE(p->pDest->pBt)-1)
55907 && iSize>=PENDING_BYTE && iSize<=PENDING_BYTE+pgszDest
55910 /* This call ensures that all data required to recreate the original
55911 ** database has been stored in the journal for pDestPager and the
55912 ** journal synced to disk. So at this point we may safely modify
55913 ** the database file in any way, knowing that if a power failure
55914 ** occurs, the original database will be reconstructed from the
55915 ** journal file. */
55916 rc = sqlite3PagerCommitPhaseOne(pDestPager, 0, 1);
55918 /* Write the extra pages and truncate the database file as required. */
55919 iEnd = MIN(PENDING_BYTE + pgszDest, iSize);
55920 for(
55921 iOff=PENDING_BYTE+pgszSrc;
55922 rc==SQLITE_OK && iOff<iEnd;
55923 iOff+=pgszSrc
55925 PgHdr *pSrcPg = 0;
55926 const Pgno iSrcPg = (Pgno)((iOff/pgszSrc)+1);
55927 rc = sqlite3PagerGet(pSrcPager, iSrcPg, &pSrcPg);
55928 if( rc==SQLITE_OK ){
55929 u8 *zData = sqlite3PagerGetData(pSrcPg);
55930 rc = sqlite3OsWrite(pFile, zData, pgszSrc, iOff);
55932 sqlite3PagerUnref(pSrcPg);
55934 if( rc==SQLITE_OK ){
55935 rc = backupTruncateFile(pFile, iSize);
55938 /* Sync the database file to disk. */
55939 if( rc==SQLITE_OK ){
55940 rc = sqlite3PagerSync(pDestPager);
55942 }else{
55943 rc = sqlite3PagerCommitPhaseOne(pDestPager, 0, 0);
55946 /* Finish committing the transaction to the destination database. */
55947 if( SQLITE_OK==rc
55948 && SQLITE_OK==(rc = sqlite3BtreeCommitPhaseTwo(p->pDest, 0))
55950 rc = SQLITE_DONE;
55954 /* If bCloseTrans is true, then this function opened a read transaction
55955 ** on the source database. Close the read transaction here. There is
55956 ** no need to check the return values of the btree methods here, as
55957 ** "committing" a read-only transaction cannot fail.
55959 if( bCloseTrans ){
55960 TESTONLY( int rc2 );
55961 TESTONLY( rc2 = ) sqlite3BtreeCommitPhaseOne(p->pSrc, 0);
55962 TESTONLY( rc2 |= ) sqlite3BtreeCommitPhaseTwo(p->pSrc, 0);
55963 assert( rc2==SQLITE_OK );
55966 if( rc==SQLITE_IOERR_NOMEM ){
55967 rc = SQLITE_NOMEM;
55969 p->rc = rc;
55971 if( p->pDestDb ){
55972 sqlite3_mutex_leave(p->pDestDb->mutex);
55974 sqlite3BtreeLeave(p->pSrc);
55975 sqlite3_mutex_leave(p->pSrcDb->mutex);
55976 return rc;
55980 ** Release all resources associated with an sqlite3_backup* handle.
55982 SQLITE_API int sqlite3_backup_finish(sqlite3_backup *p){
55983 sqlite3_backup **pp; /* Ptr to head of pagers backup list */
55984 sqlite3_mutex *mutex; /* Mutex to protect source database */
55985 int rc; /* Value to return */
55987 /* Enter the mutexes */
55988 if( p==0 ) return SQLITE_OK;
55989 sqlite3_mutex_enter(p->pSrcDb->mutex);
55990 sqlite3BtreeEnter(p->pSrc);
55991 mutex = p->pSrcDb->mutex;
55992 if( p->pDestDb ){
55993 sqlite3_mutex_enter(p->pDestDb->mutex);
55996 /* Detach this backup from the source pager. */
55997 if( p->pDestDb ){
55998 p->pSrc->nBackup--;
56000 if( p->isAttached ){
56001 pp = sqlite3PagerBackupPtr(sqlite3BtreePager(p->pSrc));
56002 while( *pp!=p ){
56003 pp = &(*pp)->pNext;
56005 *pp = p->pNext;
56008 /* If a transaction is still open on the Btree, roll it back. */
56009 sqlite3BtreeRollback(p->pDest);
56011 /* Set the error code of the destination database handle. */
56012 rc = (p->rc==SQLITE_DONE) ? SQLITE_OK : p->rc;
56013 sqlite3Error(p->pDestDb, rc, 0);
56015 /* Exit the mutexes and free the backup context structure. */
56016 if( p->pDestDb ){
56017 sqlite3_mutex_leave(p->pDestDb->mutex);
56019 sqlite3BtreeLeave(p->pSrc);
56020 if( p->pDestDb ){
56021 /* EVIDENCE-OF: R-64852-21591 The sqlite3_backup object is created by a
56022 ** call to sqlite3_backup_init() and is destroyed by a call to
56023 ** sqlite3_backup_finish(). */
56024 sqlite3_free(p);
56026 sqlite3_mutex_leave(mutex);
56027 return rc;
56031 ** Return the number of pages still to be backed up as of the most recent
56032 ** call to sqlite3_backup_step().
56034 SQLITE_API int sqlite3_backup_remaining(sqlite3_backup *p){
56035 return p->nRemaining;
56039 ** Return the total number of pages in the source database as of the most
56040 ** recent call to sqlite3_backup_step().
56042 SQLITE_API int sqlite3_backup_pagecount(sqlite3_backup *p){
56043 return p->nPagecount;
56047 ** This function is called after the contents of page iPage of the
56048 ** source database have been modified. If page iPage has already been
56049 ** copied into the destination database, then the data written to the
56050 ** destination is now invalidated. The destination copy of iPage needs
56051 ** to be updated with the new data before the backup operation is
56052 ** complete.
56054 ** It is assumed that the mutex associated with the BtShared object
56055 ** corresponding to the source database is held when this function is
56056 ** called.
56058 SQLITE_PRIVATE void sqlite3BackupUpdate(sqlite3_backup *pBackup, Pgno iPage, const u8 *aData){
56059 sqlite3_backup *p; /* Iterator variable */
56060 for(p=pBackup; p; p=p->pNext){
56061 assert( sqlite3_mutex_held(p->pSrc->pBt->mutex) );
56062 if( !isFatalError(p->rc) && iPage<p->iNext ){
56063 /* The backup process p has already copied page iPage. But now it
56064 ** has been modified by a transaction on the source pager. Copy
56065 ** the new data into the backup.
56067 int rc;
56068 assert( p->pDestDb );
56069 sqlite3_mutex_enter(p->pDestDb->mutex);
56070 rc = backupOnePage(p, iPage, aData);
56071 sqlite3_mutex_leave(p->pDestDb->mutex);
56072 assert( rc!=SQLITE_BUSY && rc!=SQLITE_LOCKED );
56073 if( rc!=SQLITE_OK ){
56074 p->rc = rc;
56081 ** Restart the backup process. This is called when the pager layer
56082 ** detects that the database has been modified by an external database
56083 ** connection. In this case there is no way of knowing which of the
56084 ** pages that have been copied into the destination database are still
56085 ** valid and which are not, so the entire process needs to be restarted.
56087 ** It is assumed that the mutex associated with the BtShared object
56088 ** corresponding to the source database is held when this function is
56089 ** called.
56091 SQLITE_PRIVATE void sqlite3BackupRestart(sqlite3_backup *pBackup){
56092 sqlite3_backup *p; /* Iterator variable */
56093 for(p=pBackup; p; p=p->pNext){
56094 assert( sqlite3_mutex_held(p->pSrc->pBt->mutex) );
56095 p->iNext = 1;
56099 #ifndef SQLITE_OMIT_VACUUM
56101 ** Copy the complete content of pBtFrom into pBtTo. A transaction
56102 ** must be active for both files.
56104 ** The size of file pTo may be reduced by this operation. If anything
56105 ** goes wrong, the transaction on pTo is rolled back. If successful, the
56106 ** transaction is committed before returning.
56108 SQLITE_PRIVATE int sqlite3BtreeCopyFile(Btree *pTo, Btree *pFrom){
56109 int rc;
56110 sqlite3_backup b;
56111 sqlite3BtreeEnter(pTo);
56112 sqlite3BtreeEnter(pFrom);
56114 /* Set up an sqlite3_backup object. sqlite3_backup.pDestDb must be set
56115 ** to 0. This is used by the implementations of sqlite3_backup_step()
56116 ** and sqlite3_backup_finish() to detect that they are being called
56117 ** from this function, not directly by the user.
56119 memset(&b, 0, sizeof(b));
56120 b.pSrcDb = pFrom->db;
56121 b.pSrc = pFrom;
56122 b.pDest = pTo;
56123 b.iNext = 1;
56125 /* 0x7FFFFFFF is the hard limit for the number of pages in a database
56126 ** file. By passing this as the number of pages to copy to
56127 ** sqlite3_backup_step(), we can guarantee that the copy finishes
56128 ** within a single call (unless an error occurs). The assert() statement
56129 ** checks this assumption - (p->rc) should be set to either SQLITE_DONE
56130 ** or an error code.
56132 sqlite3_backup_step(&b, 0x7FFFFFFF);
56133 assert( b.rc!=SQLITE_OK );
56134 rc = sqlite3_backup_finish(&b);
56135 if( rc==SQLITE_OK ){
56136 pTo->pBt->pageSizeFixed = 0;
56139 sqlite3BtreeLeave(pFrom);
56140 sqlite3BtreeLeave(pTo);
56141 return rc;
56143 #endif /* SQLITE_OMIT_VACUUM */
56145 /************** End of backup.c **********************************************/
56146 /************** Begin file vdbemem.c *****************************************/
56148 ** 2004 May 26
56150 ** The author disclaims copyright to this source code. In place of
56151 ** a legal notice, here is a blessing:
56153 ** May you do good and not evil.
56154 ** May you find forgiveness for yourself and forgive others.
56155 ** May you share freely, never taking more than you give.
56157 *************************************************************************
56159 ** This file contains code use to manipulate "Mem" structure. A "Mem"
56160 ** stores a single value in the VDBE. Mem is an opaque structure visible
56161 ** only within the VDBE. Interface routines refer to a Mem using the
56162 ** name sqlite_value
56166 ** Call sqlite3VdbeMemExpandBlob() on the supplied value (type Mem*)
56167 ** P if required.
56169 #define expandBlob(P) (((P)->flags&MEM_Zero)?sqlite3VdbeMemExpandBlob(P):0)
56172 ** If pMem is an object with a valid string representation, this routine
56173 ** ensures the internal encoding for the string representation is
56174 ** 'desiredEnc', one of SQLITE_UTF8, SQLITE_UTF16LE or SQLITE_UTF16BE.
56176 ** If pMem is not a string object, or the encoding of the string
56177 ** representation is already stored using the requested encoding, then this
56178 ** routine is a no-op.
56180 ** SQLITE_OK is returned if the conversion is successful (or not required).
56181 ** SQLITE_NOMEM may be returned if a malloc() fails during conversion
56182 ** between formats.
56184 SQLITE_PRIVATE int sqlite3VdbeChangeEncoding(Mem *pMem, int desiredEnc){
56185 int rc;
56186 assert( (pMem->flags&MEM_RowSet)==0 );
56187 assert( desiredEnc==SQLITE_UTF8 || desiredEnc==SQLITE_UTF16LE
56188 || desiredEnc==SQLITE_UTF16BE );
56189 if( !(pMem->flags&MEM_Str) || pMem->enc==desiredEnc ){
56190 return SQLITE_OK;
56192 assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
56193 #ifdef SQLITE_OMIT_UTF16
56194 return SQLITE_ERROR;
56195 #else
56197 /* MemTranslate() may return SQLITE_OK or SQLITE_NOMEM. If NOMEM is returned,
56198 ** then the encoding of the value may not have changed.
56200 rc = sqlite3VdbeMemTranslate(pMem, (u8)desiredEnc);
56201 assert(rc==SQLITE_OK || rc==SQLITE_NOMEM);
56202 assert(rc==SQLITE_OK || pMem->enc!=desiredEnc);
56203 assert(rc==SQLITE_NOMEM || pMem->enc==desiredEnc);
56204 return rc;
56205 #endif
56209 ** Make sure pMem->z points to a writable allocation of at least
56210 ** n bytes.
56212 ** If the memory cell currently contains string or blob data
56213 ** and the third argument passed to this function is true, the
56214 ** current content of the cell is preserved. Otherwise, it may
56215 ** be discarded.
56217 ** This function sets the MEM_Dyn flag and clears any xDel callback.
56218 ** It also clears MEM_Ephem and MEM_Static. If the preserve flag is
56219 ** not set, Mem.n is zeroed.
56221 SQLITE_PRIVATE int sqlite3VdbeMemGrow(Mem *pMem, int n, int preserve){
56222 assert( 1 >=
56223 ((pMem->zMalloc && pMem->zMalloc==pMem->z) ? 1 : 0) +
56224 (((pMem->flags&MEM_Dyn)&&pMem->xDel) ? 1 : 0) +
56225 ((pMem->flags&MEM_Ephem) ? 1 : 0) +
56226 ((pMem->flags&MEM_Static) ? 1 : 0)
56228 assert( (pMem->flags&MEM_RowSet)==0 );
56230 if( n<32 ) n = 32;
56231 if( sqlite3DbMallocSize(pMem->db, pMem->zMalloc)<n ){
56232 if( preserve && pMem->z==pMem->zMalloc ){
56233 pMem->z = pMem->zMalloc = sqlite3DbReallocOrFree(pMem->db, pMem->z, n);
56234 preserve = 0;
56235 }else{
56236 sqlite3DbFree(pMem->db, pMem->zMalloc);
56237 pMem->zMalloc = sqlite3DbMallocRaw(pMem->db, n);
56241 if( pMem->z && preserve && pMem->zMalloc && pMem->z!=pMem->zMalloc ){
56242 memcpy(pMem->zMalloc, pMem->z, pMem->n);
56244 if( pMem->flags&MEM_Dyn && pMem->xDel ){
56245 pMem->xDel((void *)(pMem->z));
56248 pMem->z = pMem->zMalloc;
56249 if( pMem->z==0 ){
56250 pMem->flags = MEM_Null;
56251 }else{
56252 pMem->flags &= ~(MEM_Ephem|MEM_Static);
56254 pMem->xDel = 0;
56255 return (pMem->z ? SQLITE_OK : SQLITE_NOMEM);
56259 ** Make the given Mem object MEM_Dyn. In other words, make it so
56260 ** that any TEXT or BLOB content is stored in memory obtained from
56261 ** malloc(). In this way, we know that the memory is safe to be
56262 ** overwritten or altered.
56264 ** Return SQLITE_OK on success or SQLITE_NOMEM if malloc fails.
56266 SQLITE_PRIVATE int sqlite3VdbeMemMakeWriteable(Mem *pMem){
56267 int f;
56268 assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
56269 assert( (pMem->flags&MEM_RowSet)==0 );
56270 expandBlob(pMem);
56271 f = pMem->flags;
56272 if( (f&(MEM_Str|MEM_Blob)) && pMem->z!=pMem->zMalloc ){
56273 if( sqlite3VdbeMemGrow(pMem, pMem->n + 2, 1) ){
56274 return SQLITE_NOMEM;
56276 pMem->z[pMem->n] = 0;
56277 pMem->z[pMem->n+1] = 0;
56278 pMem->flags |= MEM_Term;
56279 #ifdef SQLITE_DEBUG
56280 pMem->pScopyFrom = 0;
56281 #endif
56284 return SQLITE_OK;
56288 ** If the given Mem* has a zero-filled tail, turn it into an ordinary
56289 ** blob stored in dynamically allocated space.
56291 #ifndef SQLITE_OMIT_INCRBLOB
56292 SQLITE_PRIVATE int sqlite3VdbeMemExpandBlob(Mem *pMem){
56293 if( pMem->flags & MEM_Zero ){
56294 int nByte;
56295 assert( pMem->flags&MEM_Blob );
56296 assert( (pMem->flags&MEM_RowSet)==0 );
56297 assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
56299 /* Set nByte to the number of bytes required to store the expanded blob. */
56300 nByte = pMem->n + pMem->u.nZero;
56301 if( nByte<=0 ){
56302 nByte = 1;
56304 if( sqlite3VdbeMemGrow(pMem, nByte, 1) ){
56305 return SQLITE_NOMEM;
56308 memset(&pMem->z[pMem->n], 0, pMem->u.nZero);
56309 pMem->n += pMem->u.nZero;
56310 pMem->flags &= ~(MEM_Zero|MEM_Term);
56312 return SQLITE_OK;
56314 #endif
56318 ** Make sure the given Mem is \u0000 terminated.
56320 SQLITE_PRIVATE int sqlite3VdbeMemNulTerminate(Mem *pMem){
56321 assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
56322 if( (pMem->flags & MEM_Term)!=0 || (pMem->flags & MEM_Str)==0 ){
56323 return SQLITE_OK; /* Nothing to do */
56325 if( sqlite3VdbeMemGrow(pMem, pMem->n+2, 1) ){
56326 return SQLITE_NOMEM;
56328 pMem->z[pMem->n] = 0;
56329 pMem->z[pMem->n+1] = 0;
56330 pMem->flags |= MEM_Term;
56331 return SQLITE_OK;
56335 ** Add MEM_Str to the set of representations for the given Mem. Numbers
56336 ** are converted using sqlite3_snprintf(). Converting a BLOB to a string
56337 ** is a no-op.
56339 ** Existing representations MEM_Int and MEM_Real are *not* invalidated.
56341 ** A MEM_Null value will never be passed to this function. This function is
56342 ** used for converting values to text for returning to the user (i.e. via
56343 ** sqlite3_value_text()), or for ensuring that values to be used as btree
56344 ** keys are strings. In the former case a NULL pointer is returned the
56345 ** user and the later is an internal programming error.
56347 SQLITE_PRIVATE int sqlite3VdbeMemStringify(Mem *pMem, int enc){
56348 int rc = SQLITE_OK;
56349 int fg = pMem->flags;
56350 const int nByte = 32;
56352 assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
56353 assert( !(fg&MEM_Zero) );
56354 assert( !(fg&(MEM_Str|MEM_Blob)) );
56355 assert( fg&(MEM_Int|MEM_Real) );
56356 assert( (pMem->flags&MEM_RowSet)==0 );
56357 assert( EIGHT_BYTE_ALIGNMENT(pMem) );
56360 if( sqlite3VdbeMemGrow(pMem, nByte, 0) ){
56361 return SQLITE_NOMEM;
56364 /* For a Real or Integer, use sqlite3_mprintf() to produce the UTF-8
56365 ** string representation of the value. Then, if the required encoding
56366 ** is UTF-16le or UTF-16be do a translation.
56368 ** FIX ME: It would be better if sqlite3_snprintf() could do UTF-16.
56370 if( fg & MEM_Int ){
56371 sqlite3_snprintf(nByte, pMem->z, "%lld", pMem->u.i);
56372 }else{
56373 assert( fg & MEM_Real );
56374 sqlite3_snprintf(nByte, pMem->z, "%!.15g", pMem->r);
56376 pMem->n = sqlite3Strlen30(pMem->z);
56377 pMem->enc = SQLITE_UTF8;
56378 pMem->flags |= MEM_Str|MEM_Term;
56379 sqlite3VdbeChangeEncoding(pMem, enc);
56380 return rc;
56384 ** Memory cell pMem contains the context of an aggregate function.
56385 ** This routine calls the finalize method for that function. The
56386 ** result of the aggregate is stored back into pMem.
56388 ** Return SQLITE_ERROR if the finalizer reports an error. SQLITE_OK
56389 ** otherwise.
56391 SQLITE_PRIVATE int sqlite3VdbeMemFinalize(Mem *pMem, FuncDef *pFunc){
56392 int rc = SQLITE_OK;
56393 if( ALWAYS(pFunc && pFunc->xFinalize) ){
56394 sqlite3_context ctx;
56395 assert( (pMem->flags & MEM_Null)!=0 || pFunc==pMem->u.pDef );
56396 assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
56397 memset(&ctx, 0, sizeof(ctx));
56398 ctx.s.flags = MEM_Null;
56399 ctx.s.db = pMem->db;
56400 ctx.pMem = pMem;
56401 ctx.pFunc = pFunc;
56402 pFunc->xFinalize(&ctx); /* IMP: R-24505-23230 */
56403 assert( 0==(pMem->flags&MEM_Dyn) && !pMem->xDel );
56404 sqlite3DbFree(pMem->db, pMem->zMalloc);
56405 memcpy(pMem, &ctx.s, sizeof(ctx.s));
56406 rc = ctx.isError;
56408 return rc;
56412 ** If the memory cell contains a string value that must be freed by
56413 ** invoking an external callback, free it now. Calling this function
56414 ** does not free any Mem.zMalloc buffer.
56416 SQLITE_PRIVATE void sqlite3VdbeMemReleaseExternal(Mem *p){
56417 assert( p->db==0 || sqlite3_mutex_held(p->db->mutex) );
56418 testcase( p->flags & MEM_Agg );
56419 testcase( p->flags & MEM_Dyn );
56420 testcase( p->flags & MEM_RowSet );
56421 testcase( p->flags & MEM_Frame );
56422 if( p->flags&(MEM_Agg|MEM_Dyn|MEM_RowSet|MEM_Frame) ){
56423 if( p->flags&MEM_Agg ){
56424 sqlite3VdbeMemFinalize(p, p->u.pDef);
56425 assert( (p->flags & MEM_Agg)==0 );
56426 sqlite3VdbeMemRelease(p);
56427 }else if( p->flags&MEM_Dyn && p->xDel ){
56428 assert( (p->flags&MEM_RowSet)==0 );
56429 p->xDel((void *)p->z);
56430 p->xDel = 0;
56431 }else if( p->flags&MEM_RowSet ){
56432 sqlite3RowSetClear(p->u.pRowSet);
56433 }else if( p->flags&MEM_Frame ){
56434 sqlite3VdbeMemSetNull(p);
56440 ** Release any memory held by the Mem. This may leave the Mem in an
56441 ** inconsistent state, for example with (Mem.z==0) and
56442 ** (Mem.type==SQLITE_TEXT).
56444 SQLITE_PRIVATE void sqlite3VdbeMemRelease(Mem *p){
56445 sqlite3VdbeMemReleaseExternal(p);
56446 sqlite3DbFree(p->db, p->zMalloc);
56447 p->z = 0;
56448 p->zMalloc = 0;
56449 p->xDel = 0;
56453 ** Convert a 64-bit IEEE double into a 64-bit signed integer.
56454 ** If the double is too large, return 0x8000000000000000.
56456 ** Most systems appear to do this simply by assigning
56457 ** variables and without the extra range tests. But
56458 ** there are reports that windows throws an expection
56459 ** if the floating point value is out of range. (See ticket #2880.)
56460 ** Because we do not completely understand the problem, we will
56461 ** take the conservative approach and always do range tests
56462 ** before attempting the conversion.
56464 static i64 doubleToInt64(double r){
56465 #ifdef SQLITE_OMIT_FLOATING_POINT
56466 /* When floating-point is omitted, double and int64 are the same thing */
56467 return r;
56468 #else
56470 ** Many compilers we encounter do not define constants for the
56471 ** minimum and maximum 64-bit integers, or they define them
56472 ** inconsistently. And many do not understand the "LL" notation.
56473 ** So we define our own static constants here using nothing
56474 ** larger than a 32-bit integer constant.
56476 static const i64 maxInt = LARGEST_INT64;
56477 static const i64 minInt = SMALLEST_INT64;
56479 if( r<(double)minInt ){
56480 return minInt;
56481 }else if( r>(double)maxInt ){
56482 /* minInt is correct here - not maxInt. It turns out that assigning
56483 ** a very large positive number to an integer results in a very large
56484 ** negative integer. This makes no sense, but it is what x86 hardware
56485 ** does so for compatibility we will do the same in software. */
56486 return minInt;
56487 }else{
56488 return (i64)r;
56490 #endif
56494 ** Return some kind of integer value which is the best we can do
56495 ** at representing the value that *pMem describes as an integer.
56496 ** If pMem is an integer, then the value is exact. If pMem is
56497 ** a floating-point then the value returned is the integer part.
56498 ** If pMem is a string or blob, then we make an attempt to convert
56499 ** it into a integer and return that. If pMem represents an
56500 ** an SQL-NULL value, return 0.
56502 ** If pMem represents a string value, its encoding might be changed.
56504 SQLITE_PRIVATE i64 sqlite3VdbeIntValue(Mem *pMem){
56505 int flags;
56506 assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
56507 assert( EIGHT_BYTE_ALIGNMENT(pMem) );
56508 flags = pMem->flags;
56509 if( flags & MEM_Int ){
56510 return pMem->u.i;
56511 }else if( flags & MEM_Real ){
56512 return doubleToInt64(pMem->r);
56513 }else if( flags & (MEM_Str|MEM_Blob) ){
56514 i64 value = 0;
56515 assert( pMem->z || pMem->n==0 );
56516 testcase( pMem->z==0 );
56517 sqlite3Atoi64(pMem->z, &value, pMem->n, pMem->enc);
56518 return value;
56519 }else{
56520 return 0;
56525 ** Return the best representation of pMem that we can get into a
56526 ** double. If pMem is already a double or an integer, return its
56527 ** value. If it is a string or blob, try to convert it to a double.
56528 ** If it is a NULL, return 0.0.
56530 SQLITE_PRIVATE double sqlite3VdbeRealValue(Mem *pMem){
56531 assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
56532 assert( EIGHT_BYTE_ALIGNMENT(pMem) );
56533 if( pMem->flags & MEM_Real ){
56534 return pMem->r;
56535 }else if( pMem->flags & MEM_Int ){
56536 return (double)pMem->u.i;
56537 }else if( pMem->flags & (MEM_Str|MEM_Blob) ){
56538 /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
56539 double val = (double)0;
56540 sqlite3AtoF(pMem->z, &val, pMem->n, pMem->enc);
56541 return val;
56542 }else{
56543 /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
56544 return (double)0;
56549 ** The MEM structure is already a MEM_Real. Try to also make it a
56550 ** MEM_Int if we can.
56552 SQLITE_PRIVATE void sqlite3VdbeIntegerAffinity(Mem *pMem){
56553 assert( pMem->flags & MEM_Real );
56554 assert( (pMem->flags & MEM_RowSet)==0 );
56555 assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
56556 assert( EIGHT_BYTE_ALIGNMENT(pMem) );
56558 pMem->u.i = doubleToInt64(pMem->r);
56560 /* Only mark the value as an integer if
56562 ** (1) the round-trip conversion real->int->real is a no-op, and
56563 ** (2) The integer is neither the largest nor the smallest
56564 ** possible integer (ticket #3922)
56566 ** The second and third terms in the following conditional enforces
56567 ** the second condition under the assumption that addition overflow causes
56568 ** values to wrap around. On x86 hardware, the third term is always
56569 ** true and could be omitted. But we leave it in because other
56570 ** architectures might behave differently.
56572 if( pMem->r==(double)pMem->u.i && pMem->u.i>SMALLEST_INT64
56573 && ALWAYS(pMem->u.i<LARGEST_INT64) ){
56574 pMem->flags |= MEM_Int;
56579 ** Convert pMem to type integer. Invalidate any prior representations.
56581 SQLITE_PRIVATE int sqlite3VdbeMemIntegerify(Mem *pMem){
56582 assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
56583 assert( (pMem->flags & MEM_RowSet)==0 );
56584 assert( EIGHT_BYTE_ALIGNMENT(pMem) );
56586 pMem->u.i = sqlite3VdbeIntValue(pMem);
56587 MemSetTypeFlag(pMem, MEM_Int);
56588 return SQLITE_OK;
56592 ** Convert pMem so that it is of type MEM_Real.
56593 ** Invalidate any prior representations.
56595 SQLITE_PRIVATE int sqlite3VdbeMemRealify(Mem *pMem){
56596 assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
56597 assert( EIGHT_BYTE_ALIGNMENT(pMem) );
56599 pMem->r = sqlite3VdbeRealValue(pMem);
56600 MemSetTypeFlag(pMem, MEM_Real);
56601 return SQLITE_OK;
56605 ** Convert pMem so that it has types MEM_Real or MEM_Int or both.
56606 ** Invalidate any prior representations.
56608 ** Every effort is made to force the conversion, even if the input
56609 ** is a string that does not look completely like a number. Convert
56610 ** as much of the string as we can and ignore the rest.
56612 SQLITE_PRIVATE int sqlite3VdbeMemNumerify(Mem *pMem){
56613 if( (pMem->flags & (MEM_Int|MEM_Real|MEM_Null))==0 ){
56614 assert( (pMem->flags & (MEM_Blob|MEM_Str))!=0 );
56615 assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
56616 if( 0==sqlite3Atoi64(pMem->z, &pMem->u.i, pMem->n, pMem->enc) ){
56617 MemSetTypeFlag(pMem, MEM_Int);
56618 }else{
56619 pMem->r = sqlite3VdbeRealValue(pMem);
56620 MemSetTypeFlag(pMem, MEM_Real);
56621 sqlite3VdbeIntegerAffinity(pMem);
56624 assert( (pMem->flags & (MEM_Int|MEM_Real|MEM_Null))!=0 );
56625 pMem->flags &= ~(MEM_Str|MEM_Blob);
56626 return SQLITE_OK;
56630 ** Delete any previous value and set the value stored in *pMem to NULL.
56632 SQLITE_PRIVATE void sqlite3VdbeMemSetNull(Mem *pMem){
56633 if( pMem->flags & MEM_Frame ){
56634 VdbeFrame *pFrame = pMem->u.pFrame;
56635 pFrame->pParent = pFrame->v->pDelFrame;
56636 pFrame->v->pDelFrame = pFrame;
56638 if( pMem->flags & MEM_RowSet ){
56639 sqlite3RowSetClear(pMem->u.pRowSet);
56641 MemSetTypeFlag(pMem, MEM_Null);
56642 pMem->type = SQLITE_NULL;
56646 ** Delete any previous value and set the value to be a BLOB of length
56647 ** n containing all zeros.
56649 SQLITE_PRIVATE void sqlite3VdbeMemSetZeroBlob(Mem *pMem, int n){
56650 sqlite3VdbeMemRelease(pMem);
56651 pMem->flags = MEM_Blob|MEM_Zero;
56652 pMem->type = SQLITE_BLOB;
56653 pMem->n = 0;
56654 if( n<0 ) n = 0;
56655 pMem->u.nZero = n;
56656 pMem->enc = SQLITE_UTF8;
56658 #ifdef SQLITE_OMIT_INCRBLOB
56659 sqlite3VdbeMemGrow(pMem, n, 0);
56660 if( pMem->z ){
56661 pMem->n = n;
56662 memset(pMem->z, 0, n);
56664 #endif
56668 ** Delete any previous value and set the value stored in *pMem to val,
56669 ** manifest type INTEGER.
56671 SQLITE_PRIVATE void sqlite3VdbeMemSetInt64(Mem *pMem, i64 val){
56672 sqlite3VdbeMemRelease(pMem);
56673 pMem->u.i = val;
56674 pMem->flags = MEM_Int;
56675 pMem->type = SQLITE_INTEGER;
56678 #ifndef SQLITE_OMIT_FLOATING_POINT
56680 ** Delete any previous value and set the value stored in *pMem to val,
56681 ** manifest type REAL.
56683 SQLITE_PRIVATE void sqlite3VdbeMemSetDouble(Mem *pMem, double val){
56684 if( sqlite3IsNaN(val) ){
56685 sqlite3VdbeMemSetNull(pMem);
56686 }else{
56687 sqlite3VdbeMemRelease(pMem);
56688 pMem->r = val;
56689 pMem->flags = MEM_Real;
56690 pMem->type = SQLITE_FLOAT;
56693 #endif
56696 ** Delete any previous value and set the value of pMem to be an
56697 ** empty boolean index.
56699 SQLITE_PRIVATE void sqlite3VdbeMemSetRowSet(Mem *pMem){
56700 sqlite3 *db = pMem->db;
56701 assert( db!=0 );
56702 assert( (pMem->flags & MEM_RowSet)==0 );
56703 sqlite3VdbeMemRelease(pMem);
56704 pMem->zMalloc = sqlite3DbMallocRaw(db, 64);
56705 if( db->mallocFailed ){
56706 pMem->flags = MEM_Null;
56707 }else{
56708 assert( pMem->zMalloc );
56709 pMem->u.pRowSet = sqlite3RowSetInit(db, pMem->zMalloc,
56710 sqlite3DbMallocSize(db, pMem->zMalloc));
56711 assert( pMem->u.pRowSet!=0 );
56712 pMem->flags = MEM_RowSet;
56717 ** Return true if the Mem object contains a TEXT or BLOB that is
56718 ** too large - whose size exceeds SQLITE_MAX_LENGTH.
56720 SQLITE_PRIVATE int sqlite3VdbeMemTooBig(Mem *p){
56721 assert( p->db!=0 );
56722 if( p->flags & (MEM_Str|MEM_Blob) ){
56723 int n = p->n;
56724 if( p->flags & MEM_Zero ){
56725 n += p->u.nZero;
56727 return n>p->db->aLimit[SQLITE_LIMIT_LENGTH];
56729 return 0;
56732 #ifdef SQLITE_DEBUG
56734 ** This routine prepares a memory cell for modication by breaking
56735 ** its link to a shallow copy and by marking any current shallow
56736 ** copies of this cell as invalid.
56738 ** This is used for testing and debugging only - to make sure shallow
56739 ** copies are not misused.
56741 SQLITE_PRIVATE void sqlite3VdbeMemPrepareToChange(Vdbe *pVdbe, Mem *pMem){
56742 int i;
56743 Mem *pX;
56744 for(i=1, pX=&pVdbe->aMem[1]; i<=pVdbe->nMem; i++, pX++){
56745 if( pX->pScopyFrom==pMem ){
56746 pX->flags |= MEM_Invalid;
56747 pX->pScopyFrom = 0;
56750 pMem->pScopyFrom = 0;
56752 #endif /* SQLITE_DEBUG */
56755 ** Size of struct Mem not including the Mem.zMalloc member.
56757 #define MEMCELLSIZE (size_t)(&(((Mem *)0)->zMalloc))
56760 ** Make an shallow copy of pFrom into pTo. Prior contents of
56761 ** pTo are freed. The pFrom->z field is not duplicated. If
56762 ** pFrom->z is used, then pTo->z points to the same thing as pFrom->z
56763 ** and flags gets srcType (either MEM_Ephem or MEM_Static).
56765 SQLITE_PRIVATE void sqlite3VdbeMemShallowCopy(Mem *pTo, const Mem *pFrom, int srcType){
56766 assert( (pFrom->flags & MEM_RowSet)==0 );
56767 sqlite3VdbeMemReleaseExternal(pTo);
56768 memcpy(pTo, pFrom, MEMCELLSIZE);
56769 pTo->xDel = 0;
56770 if( (pFrom->flags&MEM_Static)==0 ){
56771 pTo->flags &= ~(MEM_Dyn|MEM_Static|MEM_Ephem);
56772 assert( srcType==MEM_Ephem || srcType==MEM_Static );
56773 pTo->flags |= srcType;
56778 ** Make a full copy of pFrom into pTo. Prior contents of pTo are
56779 ** freed before the copy is made.
56781 SQLITE_PRIVATE int sqlite3VdbeMemCopy(Mem *pTo, const Mem *pFrom){
56782 int rc = SQLITE_OK;
56784 assert( (pFrom->flags & MEM_RowSet)==0 );
56785 sqlite3VdbeMemReleaseExternal(pTo);
56786 memcpy(pTo, pFrom, MEMCELLSIZE);
56787 pTo->flags &= ~MEM_Dyn;
56789 if( pTo->flags&(MEM_Str|MEM_Blob) ){
56790 if( 0==(pFrom->flags&MEM_Static) ){
56791 pTo->flags |= MEM_Ephem;
56792 rc = sqlite3VdbeMemMakeWriteable(pTo);
56796 return rc;
56800 ** Transfer the contents of pFrom to pTo. Any existing value in pTo is
56801 ** freed. If pFrom contains ephemeral data, a copy is made.
56803 ** pFrom contains an SQL NULL when this routine returns.
56805 SQLITE_PRIVATE void sqlite3VdbeMemMove(Mem *pTo, Mem *pFrom){
56806 assert( pFrom->db==0 || sqlite3_mutex_held(pFrom->db->mutex) );
56807 assert( pTo->db==0 || sqlite3_mutex_held(pTo->db->mutex) );
56808 assert( pFrom->db==0 || pTo->db==0 || pFrom->db==pTo->db );
56810 sqlite3VdbeMemRelease(pTo);
56811 memcpy(pTo, pFrom, sizeof(Mem));
56812 pFrom->flags = MEM_Null;
56813 pFrom->xDel = 0;
56814 pFrom->zMalloc = 0;
56818 ** Change the value of a Mem to be a string or a BLOB.
56820 ** The memory management strategy depends on the value of the xDel
56821 ** parameter. If the value passed is SQLITE_TRANSIENT, then the
56822 ** string is copied into a (possibly existing) buffer managed by the
56823 ** Mem structure. Otherwise, any existing buffer is freed and the
56824 ** pointer copied.
56826 ** If the string is too large (if it exceeds the SQLITE_LIMIT_LENGTH
56827 ** size limit) then no memory allocation occurs. If the string can be
56828 ** stored without allocating memory, then it is. If a memory allocation
56829 ** is required to store the string, then value of pMem is unchanged. In
56830 ** either case, SQLITE_TOOBIG is returned.
56832 SQLITE_PRIVATE int sqlite3VdbeMemSetStr(
56833 Mem *pMem, /* Memory cell to set to string value */
56834 const char *z, /* String pointer */
56835 int n, /* Bytes in string, or negative */
56836 u8 enc, /* Encoding of z. 0 for BLOBs */
56837 void (*xDel)(void*) /* Destructor function */
56839 int nByte = n; /* New value for pMem->n */
56840 int iLimit; /* Maximum allowed string or blob size */
56841 u16 flags = 0; /* New value for pMem->flags */
56843 assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
56844 assert( (pMem->flags & MEM_RowSet)==0 );
56846 /* If z is a NULL pointer, set pMem to contain an SQL NULL. */
56847 if( !z ){
56848 sqlite3VdbeMemSetNull(pMem);
56849 return SQLITE_OK;
56852 if( pMem->db ){
56853 iLimit = pMem->db->aLimit[SQLITE_LIMIT_LENGTH];
56854 }else{
56855 iLimit = SQLITE_MAX_LENGTH;
56857 flags = (enc==0?MEM_Blob:MEM_Str);
56858 if( nByte<0 ){
56859 assert( enc!=0 );
56860 if( enc==SQLITE_UTF8 ){
56861 for(nByte=0; nByte<=iLimit && z[nByte]; nByte++){}
56862 }else{
56863 for(nByte=0; nByte<=iLimit && (z[nByte] | z[nByte+1]); nByte+=2){}
56865 flags |= MEM_Term;
56868 /* The following block sets the new values of Mem.z and Mem.xDel. It
56869 ** also sets a flag in local variable "flags" to indicate the memory
56870 ** management (one of MEM_Dyn or MEM_Static).
56872 if( xDel==SQLITE_TRANSIENT ){
56873 int nAlloc = nByte;
56874 if( flags&MEM_Term ){
56875 nAlloc += (enc==SQLITE_UTF8?1:2);
56877 if( nByte>iLimit ){
56878 return SQLITE_TOOBIG;
56880 if( sqlite3VdbeMemGrow(pMem, nAlloc, 0) ){
56881 return SQLITE_NOMEM;
56883 memcpy(pMem->z, z, nAlloc);
56884 }else if( xDel==SQLITE_DYNAMIC ){
56885 sqlite3VdbeMemRelease(pMem);
56886 pMem->zMalloc = pMem->z = (char *)z;
56887 pMem->xDel = 0;
56888 }else{
56889 sqlite3VdbeMemRelease(pMem);
56890 pMem->z = (char *)z;
56891 pMem->xDel = xDel;
56892 flags |= ((xDel==SQLITE_STATIC)?MEM_Static:MEM_Dyn);
56895 pMem->n = nByte;
56896 pMem->flags = flags;
56897 pMem->enc = (enc==0 ? SQLITE_UTF8 : enc);
56898 pMem->type = (enc==0 ? SQLITE_BLOB : SQLITE_TEXT);
56900 #ifndef SQLITE_OMIT_UTF16
56901 if( pMem->enc!=SQLITE_UTF8 && sqlite3VdbeMemHandleBom(pMem) ){
56902 return SQLITE_NOMEM;
56904 #endif
56906 if( nByte>iLimit ){
56907 return SQLITE_TOOBIG;
56910 return SQLITE_OK;
56914 ** Compare the values contained by the two memory cells, returning
56915 ** negative, zero or positive if pMem1 is less than, equal to, or greater
56916 ** than pMem2. Sorting order is NULL's first, followed by numbers (integers
56917 ** and reals) sorted numerically, followed by text ordered by the collating
56918 ** sequence pColl and finally blob's ordered by memcmp().
56920 ** Two NULL values are considered equal by this function.
56922 SQLITE_PRIVATE int sqlite3MemCompare(const Mem *pMem1, const Mem *pMem2, const CollSeq *pColl){
56923 int rc;
56924 int f1, f2;
56925 int combined_flags;
56927 f1 = pMem1->flags;
56928 f2 = pMem2->flags;
56929 combined_flags = f1|f2;
56930 assert( (combined_flags & MEM_RowSet)==0 );
56932 /* If one value is NULL, it is less than the other. If both values
56933 ** are NULL, return 0.
56935 if( combined_flags&MEM_Null ){
56936 return (f2&MEM_Null) - (f1&MEM_Null);
56939 /* If one value is a number and the other is not, the number is less.
56940 ** If both are numbers, compare as reals if one is a real, or as integers
56941 ** if both values are integers.
56943 if( combined_flags&(MEM_Int|MEM_Real) ){
56944 if( !(f1&(MEM_Int|MEM_Real)) ){
56945 return 1;
56947 if( !(f2&(MEM_Int|MEM_Real)) ){
56948 return -1;
56950 if( (f1 & f2 & MEM_Int)==0 ){
56951 double r1, r2;
56952 if( (f1&MEM_Real)==0 ){
56953 r1 = (double)pMem1->u.i;
56954 }else{
56955 r1 = pMem1->r;
56957 if( (f2&MEM_Real)==0 ){
56958 r2 = (double)pMem2->u.i;
56959 }else{
56960 r2 = pMem2->r;
56962 if( r1<r2 ) return -1;
56963 if( r1>r2 ) return 1;
56964 return 0;
56965 }else{
56966 assert( f1&MEM_Int );
56967 assert( f2&MEM_Int );
56968 if( pMem1->u.i < pMem2->u.i ) return -1;
56969 if( pMem1->u.i > pMem2->u.i ) return 1;
56970 return 0;
56974 /* If one value is a string and the other is a blob, the string is less.
56975 ** If both are strings, compare using the collating functions.
56977 if( combined_flags&MEM_Str ){
56978 if( (f1 & MEM_Str)==0 ){
56979 return 1;
56981 if( (f2 & MEM_Str)==0 ){
56982 return -1;
56985 assert( pMem1->enc==pMem2->enc );
56986 assert( pMem1->enc==SQLITE_UTF8 ||
56987 pMem1->enc==SQLITE_UTF16LE || pMem1->enc==SQLITE_UTF16BE );
56989 /* The collation sequence must be defined at this point, even if
56990 ** the user deletes the collation sequence after the vdbe program is
56991 ** compiled (this was not always the case).
56993 assert( !pColl || pColl->xCmp );
56995 if( pColl ){
56996 if( pMem1->enc==pColl->enc ){
56997 /* The strings are already in the correct encoding. Call the
56998 ** comparison function directly */
56999 return pColl->xCmp(pColl->pUser,pMem1->n,pMem1->z,pMem2->n,pMem2->z);
57000 }else{
57001 const void *v1, *v2;
57002 int n1, n2;
57003 Mem c1;
57004 Mem c2;
57005 memset(&c1, 0, sizeof(c1));
57006 memset(&c2, 0, sizeof(c2));
57007 sqlite3VdbeMemShallowCopy(&c1, pMem1, MEM_Ephem);
57008 sqlite3VdbeMemShallowCopy(&c2, pMem2, MEM_Ephem);
57009 v1 = sqlite3ValueText((sqlite3_value*)&c1, pColl->enc);
57010 n1 = v1==0 ? 0 : c1.n;
57011 v2 = sqlite3ValueText((sqlite3_value*)&c2, pColl->enc);
57012 n2 = v2==0 ? 0 : c2.n;
57013 rc = pColl->xCmp(pColl->pUser, n1, v1, n2, v2);
57014 sqlite3VdbeMemRelease(&c1);
57015 sqlite3VdbeMemRelease(&c2);
57016 return rc;
57019 /* If a NULL pointer was passed as the collate function, fall through
57020 ** to the blob case and use memcmp(). */
57023 /* Both values must be blobs. Compare using memcmp(). */
57024 rc = memcmp(pMem1->z, pMem2->z, (pMem1->n>pMem2->n)?pMem2->n:pMem1->n);
57025 if( rc==0 ){
57026 rc = pMem1->n - pMem2->n;
57028 return rc;
57032 ** Move data out of a btree key or data field and into a Mem structure.
57033 ** The data or key is taken from the entry that pCur is currently pointing
57034 ** to. offset and amt determine what portion of the data or key to retrieve.
57035 ** key is true to get the key or false to get data. The result is written
57036 ** into the pMem element.
57038 ** The pMem structure is assumed to be uninitialized. Any prior content
57039 ** is overwritten without being freed.
57041 ** If this routine fails for any reason (malloc returns NULL or unable
57042 ** to read from the disk) then the pMem is left in an inconsistent state.
57044 SQLITE_PRIVATE int sqlite3VdbeMemFromBtree(
57045 BtCursor *pCur, /* Cursor pointing at record to retrieve. */
57046 int offset, /* Offset from the start of data to return bytes from. */
57047 int amt, /* Number of bytes to return. */
57048 int key, /* If true, retrieve from the btree key, not data. */
57049 Mem *pMem /* OUT: Return data in this Mem structure. */
57051 char *zData; /* Data from the btree layer */
57052 int available = 0; /* Number of bytes available on the local btree page */
57053 int rc = SQLITE_OK; /* Return code */
57055 assert( sqlite3BtreeCursorIsValid(pCur) );
57057 /* Note: the calls to BtreeKeyFetch() and DataFetch() below assert()
57058 ** that both the BtShared and database handle mutexes are held. */
57059 assert( (pMem->flags & MEM_RowSet)==0 );
57060 if( key ){
57061 zData = (char *)sqlite3BtreeKeyFetch(pCur, &available);
57062 }else{
57063 zData = (char *)sqlite3BtreeDataFetch(pCur, &available);
57065 assert( zData!=0 );
57067 if( offset+amt<=available && (pMem->flags&MEM_Dyn)==0 ){
57068 sqlite3VdbeMemRelease(pMem);
57069 pMem->z = &zData[offset];
57070 pMem->flags = MEM_Blob|MEM_Ephem;
57071 }else if( SQLITE_OK==(rc = sqlite3VdbeMemGrow(pMem, amt+2, 0)) ){
57072 pMem->flags = MEM_Blob|MEM_Dyn|MEM_Term;
57073 pMem->enc = 0;
57074 pMem->type = SQLITE_BLOB;
57075 if( key ){
57076 rc = sqlite3BtreeKey(pCur, offset, amt, pMem->z);
57077 }else{
57078 rc = sqlite3BtreeData(pCur, offset, amt, pMem->z);
57080 pMem->z[amt] = 0;
57081 pMem->z[amt+1] = 0;
57082 if( rc!=SQLITE_OK ){
57083 sqlite3VdbeMemRelease(pMem);
57086 pMem->n = amt;
57088 return rc;
57091 /* This function is only available internally, it is not part of the
57092 ** external API. It works in a similar way to sqlite3_value_text(),
57093 ** except the data returned is in the encoding specified by the second
57094 ** parameter, which must be one of SQLITE_UTF16BE, SQLITE_UTF16LE or
57095 ** SQLITE_UTF8.
57097 ** (2006-02-16:) The enc value can be or-ed with SQLITE_UTF16_ALIGNED.
57098 ** If that is the case, then the result must be aligned on an even byte
57099 ** boundary.
57101 SQLITE_PRIVATE const void *sqlite3ValueText(sqlite3_value* pVal, u8 enc){
57102 if( !pVal ) return 0;
57104 assert( pVal->db==0 || sqlite3_mutex_held(pVal->db->mutex) );
57105 assert( (enc&3)==(enc&~SQLITE_UTF16_ALIGNED) );
57106 assert( (pVal->flags & MEM_RowSet)==0 );
57108 if( pVal->flags&MEM_Null ){
57109 return 0;
57111 assert( (MEM_Blob>>3) == MEM_Str );
57112 pVal->flags |= (pVal->flags & MEM_Blob)>>3;
57113 expandBlob(pVal);
57114 if( pVal->flags&MEM_Str ){
57115 sqlite3VdbeChangeEncoding(pVal, enc & ~SQLITE_UTF16_ALIGNED);
57116 if( (enc & SQLITE_UTF16_ALIGNED)!=0 && 1==(1&SQLITE_PTR_TO_INT(pVal->z)) ){
57117 assert( (pVal->flags & (MEM_Ephem|MEM_Static))!=0 );
57118 if( sqlite3VdbeMemMakeWriteable(pVal)!=SQLITE_OK ){
57119 return 0;
57122 sqlite3VdbeMemNulTerminate(pVal); /* IMP: R-59893-45467 */
57123 }else{
57124 assert( (pVal->flags&MEM_Blob)==0 );
57125 sqlite3VdbeMemStringify(pVal, enc);
57126 assert( 0==(1&SQLITE_PTR_TO_INT(pVal->z)) );
57128 assert(pVal->enc==(enc & ~SQLITE_UTF16_ALIGNED) || pVal->db==0
57129 || pVal->db->mallocFailed );
57130 if( pVal->enc==(enc & ~SQLITE_UTF16_ALIGNED) ){
57131 return pVal->z;
57132 }else{
57133 return 0;
57138 ** Create a new sqlite3_value object.
57140 SQLITE_PRIVATE sqlite3_value *sqlite3ValueNew(sqlite3 *db){
57141 Mem *p = sqlite3DbMallocZero(db, sizeof(*p));
57142 if( p ){
57143 p->flags = MEM_Null;
57144 p->type = SQLITE_NULL;
57145 p->db = db;
57147 return p;
57151 ** Create a new sqlite3_value object, containing the value of pExpr.
57153 ** This only works for very simple expressions that consist of one constant
57154 ** token (i.e. "5", "5.1", "'a string'"). If the expression can
57155 ** be converted directly into a value, then the value is allocated and
57156 ** a pointer written to *ppVal. The caller is responsible for deallocating
57157 ** the value by passing it to sqlite3ValueFree() later on. If the expression
57158 ** cannot be converted to a value, then *ppVal is set to NULL.
57160 SQLITE_PRIVATE int sqlite3ValueFromExpr(
57161 sqlite3 *db, /* The database connection */
57162 Expr *pExpr, /* The expression to evaluate */
57163 u8 enc, /* Encoding to use */
57164 u8 affinity, /* Affinity to use */
57165 sqlite3_value **ppVal /* Write the new value here */
57167 int op;
57168 char *zVal = 0;
57169 sqlite3_value *pVal = 0;
57170 int negInt = 1;
57171 const char *zNeg = "";
57173 if( !pExpr ){
57174 *ppVal = 0;
57175 return SQLITE_OK;
57177 op = pExpr->op;
57179 /* op can only be TK_REGISTER if we have compiled with SQLITE_ENABLE_STAT2.
57180 ** The ifdef here is to enable us to achieve 100% branch test coverage even
57181 ** when SQLITE_ENABLE_STAT2 is omitted.
57183 #ifdef SQLITE_ENABLE_STAT2
57184 if( op==TK_REGISTER ) op = pExpr->op2;
57185 #else
57186 if( NEVER(op==TK_REGISTER) ) op = pExpr->op2;
57187 #endif
57189 /* Handle negative integers in a single step. This is needed in the
57190 ** case when the value is -9223372036854775808.
57192 if( op==TK_UMINUS
57193 && (pExpr->pLeft->op==TK_INTEGER || pExpr->pLeft->op==TK_FLOAT) ){
57194 pExpr = pExpr->pLeft;
57195 op = pExpr->op;
57196 negInt = -1;
57197 zNeg = "-";
57200 if( op==TK_STRING || op==TK_FLOAT || op==TK_INTEGER ){
57201 pVal = sqlite3ValueNew(db);
57202 if( pVal==0 ) goto no_mem;
57203 if( ExprHasProperty(pExpr, EP_IntValue) ){
57204 sqlite3VdbeMemSetInt64(pVal, (i64)pExpr->u.iValue*negInt);
57205 }else{
57206 zVal = sqlite3MPrintf(db, "%s%s", zNeg, pExpr->u.zToken);
57207 if( zVal==0 ) goto no_mem;
57208 sqlite3ValueSetStr(pVal, -1, zVal, SQLITE_UTF8, SQLITE_DYNAMIC);
57209 if( op==TK_FLOAT ) pVal->type = SQLITE_FLOAT;
57211 if( (op==TK_INTEGER || op==TK_FLOAT ) && affinity==SQLITE_AFF_NONE ){
57212 sqlite3ValueApplyAffinity(pVal, SQLITE_AFF_NUMERIC, SQLITE_UTF8);
57213 }else{
57214 sqlite3ValueApplyAffinity(pVal, affinity, SQLITE_UTF8);
57216 if( pVal->flags & (MEM_Int|MEM_Real) ) pVal->flags &= ~MEM_Str;
57217 if( enc!=SQLITE_UTF8 ){
57218 sqlite3VdbeChangeEncoding(pVal, enc);
57220 }else if( op==TK_UMINUS ) {
57221 /* This branch happens for multiple negative signs. Ex: -(-5) */
57222 if( SQLITE_OK==sqlite3ValueFromExpr(db,pExpr->pLeft,enc,affinity,&pVal) ){
57223 sqlite3VdbeMemNumerify(pVal);
57224 if( pVal->u.i==SMALLEST_INT64 ){
57225 pVal->flags &= MEM_Int;
57226 pVal->flags |= MEM_Real;
57227 pVal->r = (double)LARGEST_INT64;
57228 }else{
57229 pVal->u.i = -pVal->u.i;
57231 pVal->r = -pVal->r;
57232 sqlite3ValueApplyAffinity(pVal, affinity, enc);
57234 }else if( op==TK_NULL ){
57235 pVal = sqlite3ValueNew(db);
57236 if( pVal==0 ) goto no_mem;
57238 #ifndef SQLITE_OMIT_BLOB_LITERAL
57239 else if( op==TK_BLOB ){
57240 int nVal;
57241 assert( pExpr->u.zToken[0]=='x' || pExpr->u.zToken[0]=='X' );
57242 assert( pExpr->u.zToken[1]=='\'' );
57243 pVal = sqlite3ValueNew(db);
57244 if( !pVal ) goto no_mem;
57245 zVal = &pExpr->u.zToken[2];
57246 nVal = sqlite3Strlen30(zVal)-1;
57247 assert( zVal[nVal]=='\'' );
57248 sqlite3VdbeMemSetStr(pVal, sqlite3HexToBlob(db, zVal, nVal), nVal/2,
57249 0, SQLITE_DYNAMIC);
57251 #endif
57253 if( pVal ){
57254 sqlite3VdbeMemStoreType(pVal);
57256 *ppVal = pVal;
57257 return SQLITE_OK;
57259 no_mem:
57260 db->mallocFailed = 1;
57261 sqlite3DbFree(db, zVal);
57262 sqlite3ValueFree(pVal);
57263 *ppVal = 0;
57264 return SQLITE_NOMEM;
57268 ** Change the string value of an sqlite3_value object
57270 SQLITE_PRIVATE void sqlite3ValueSetStr(
57271 sqlite3_value *v, /* Value to be set */
57272 int n, /* Length of string z */
57273 const void *z, /* Text of the new string */
57274 u8 enc, /* Encoding to use */
57275 void (*xDel)(void*) /* Destructor for the string */
57277 if( v ) sqlite3VdbeMemSetStr((Mem *)v, z, n, enc, xDel);
57281 ** Free an sqlite3_value object
57283 SQLITE_PRIVATE void sqlite3ValueFree(sqlite3_value *v){
57284 if( !v ) return;
57285 sqlite3VdbeMemRelease((Mem *)v);
57286 sqlite3DbFree(((Mem*)v)->db, v);
57290 ** Return the number of bytes in the sqlite3_value object assuming
57291 ** that it uses the encoding "enc"
57293 SQLITE_PRIVATE int sqlite3ValueBytes(sqlite3_value *pVal, u8 enc){
57294 Mem *p = (Mem*)pVal;
57295 if( (p->flags & MEM_Blob)!=0 || sqlite3ValueText(pVal, enc) ){
57296 if( p->flags & MEM_Zero ){
57297 return p->n + p->u.nZero;
57298 }else{
57299 return p->n;
57302 return 0;
57305 /************** End of vdbemem.c *********************************************/
57306 /************** Begin file vdbeaux.c *****************************************/
57308 ** 2003 September 6
57310 ** The author disclaims copyright to this source code. In place of
57311 ** a legal notice, here is a blessing:
57313 ** May you do good and not evil.
57314 ** May you find forgiveness for yourself and forgive others.
57315 ** May you share freely, never taking more than you give.
57317 *************************************************************************
57318 ** This file contains code used for creating, destroying, and populating
57319 ** a VDBE (or an "sqlite3_stmt" as it is known to the outside world.) Prior
57320 ** to version 2.8.7, all this code was combined into the vdbe.c source file.
57321 ** But that file was getting too big so this subroutines were split out.
57327 ** When debugging the code generator in a symbolic debugger, one can
57328 ** set the sqlite3VdbeAddopTrace to 1 and all opcodes will be printed
57329 ** as they are added to the instruction stream.
57331 #ifdef SQLITE_DEBUG
57332 SQLITE_PRIVATE int sqlite3VdbeAddopTrace = 0;
57333 #endif
57337 ** Create a new virtual database engine.
57339 SQLITE_PRIVATE Vdbe *sqlite3VdbeCreate(sqlite3 *db){
57340 Vdbe *p;
57341 p = sqlite3DbMallocZero(db, sizeof(Vdbe) );
57342 if( p==0 ) return 0;
57343 p->db = db;
57344 if( db->pVdbe ){
57345 db->pVdbe->pPrev = p;
57347 p->pNext = db->pVdbe;
57348 p->pPrev = 0;
57349 db->pVdbe = p;
57350 p->magic = VDBE_MAGIC_INIT;
57351 return p;
57355 ** Remember the SQL string for a prepared statement.
57357 SQLITE_PRIVATE void sqlite3VdbeSetSql(Vdbe *p, const char *z, int n, int isPrepareV2){
57358 assert( isPrepareV2==1 || isPrepareV2==0 );
57359 if( p==0 ) return;
57360 #ifdef SQLITE_OMIT_TRACE
57361 if( !isPrepareV2 ) return;
57362 #endif
57363 assert( p->zSql==0 );
57364 p->zSql = sqlite3DbStrNDup(p->db, z, n);
57365 p->isPrepareV2 = (u8)isPrepareV2;
57369 ** Return the SQL associated with a prepared statement
57371 SQLITE_API const char *sqlite3_sql(sqlite3_stmt *pStmt){
57372 Vdbe *p = (Vdbe *)pStmt;
57373 return (p && p->isPrepareV2) ? p->zSql : 0;
57377 ** Swap all content between two VDBE structures.
57379 SQLITE_PRIVATE void sqlite3VdbeSwap(Vdbe *pA, Vdbe *pB){
57380 Vdbe tmp, *pTmp;
57381 char *zTmp;
57382 tmp = *pA;
57383 *pA = *pB;
57384 *pB = tmp;
57385 pTmp = pA->pNext;
57386 pA->pNext = pB->pNext;
57387 pB->pNext = pTmp;
57388 pTmp = pA->pPrev;
57389 pA->pPrev = pB->pPrev;
57390 pB->pPrev = pTmp;
57391 zTmp = pA->zSql;
57392 pA->zSql = pB->zSql;
57393 pB->zSql = zTmp;
57394 pB->isPrepareV2 = pA->isPrepareV2;
57397 #ifdef SQLITE_DEBUG
57399 ** Turn tracing on or off
57401 SQLITE_PRIVATE void sqlite3VdbeTrace(Vdbe *p, FILE *trace){
57402 p->trace = trace;
57404 #endif
57407 ** Resize the Vdbe.aOp array so that it is at least one op larger than
57408 ** it was.
57410 ** If an out-of-memory error occurs while resizing the array, return
57411 ** SQLITE_NOMEM. In this case Vdbe.aOp and Vdbe.nOpAlloc remain
57412 ** unchanged (this is so that any opcodes already allocated can be
57413 ** correctly deallocated along with the rest of the Vdbe).
57415 static int growOpArray(Vdbe *p){
57416 VdbeOp *pNew;
57417 int nNew = (p->nOpAlloc ? p->nOpAlloc*2 : (int)(1024/sizeof(Op)));
57418 pNew = sqlite3DbRealloc(p->db, p->aOp, nNew*sizeof(Op));
57419 if( pNew ){
57420 p->nOpAlloc = sqlite3DbMallocSize(p->db, pNew)/sizeof(Op);
57421 p->aOp = pNew;
57423 return (pNew ? SQLITE_OK : SQLITE_NOMEM);
57427 ** Add a new instruction to the list of instructions current in the
57428 ** VDBE. Return the address of the new instruction.
57430 ** Parameters:
57432 ** p Pointer to the VDBE
57434 ** op The opcode for this instruction
57436 ** p1, p2, p3 Operands
57438 ** Use the sqlite3VdbeResolveLabel() function to fix an address and
57439 ** the sqlite3VdbeChangeP4() function to change the value of the P4
57440 ** operand.
57442 SQLITE_PRIVATE int sqlite3VdbeAddOp3(Vdbe *p, int op, int p1, int p2, int p3){
57443 int i;
57444 VdbeOp *pOp;
57446 i = p->nOp;
57447 assert( p->magic==VDBE_MAGIC_INIT );
57448 assert( op>0 && op<0xff );
57449 if( p->nOpAlloc<=i ){
57450 if( growOpArray(p) ){
57451 return 1;
57454 p->nOp++;
57455 pOp = &p->aOp[i];
57456 pOp->opcode = (u8)op;
57457 pOp->p5 = 0;
57458 pOp->p1 = p1;
57459 pOp->p2 = p2;
57460 pOp->p3 = p3;
57461 pOp->p4.p = 0;
57462 pOp->p4type = P4_NOTUSED;
57463 p->expired = 0;
57464 if( op==OP_ParseSchema ){
57465 /* Any program that uses the OP_ParseSchema opcode needs to lock
57466 ** all btrees. */
57467 int j;
57468 for(j=0; j<p->db->nDb; j++) sqlite3VdbeUsesBtree(p, j);
57470 #ifdef SQLITE_DEBUG
57471 pOp->zComment = 0;
57472 if( sqlite3VdbeAddopTrace ) sqlite3VdbePrintOp(0, i, &p->aOp[i]);
57473 #endif
57474 #ifdef VDBE_PROFILE
57475 pOp->cycles = 0;
57476 pOp->cnt = 0;
57477 #endif
57478 return i;
57480 SQLITE_PRIVATE int sqlite3VdbeAddOp0(Vdbe *p, int op){
57481 return sqlite3VdbeAddOp3(p, op, 0, 0, 0);
57483 SQLITE_PRIVATE int sqlite3VdbeAddOp1(Vdbe *p, int op, int p1){
57484 return sqlite3VdbeAddOp3(p, op, p1, 0, 0);
57486 SQLITE_PRIVATE int sqlite3VdbeAddOp2(Vdbe *p, int op, int p1, int p2){
57487 return sqlite3VdbeAddOp3(p, op, p1, p2, 0);
57492 ** Add an opcode that includes the p4 value as a pointer.
57494 SQLITE_PRIVATE int sqlite3VdbeAddOp4(
57495 Vdbe *p, /* Add the opcode to this VM */
57496 int op, /* The new opcode */
57497 int p1, /* The P1 operand */
57498 int p2, /* The P2 operand */
57499 int p3, /* The P3 operand */
57500 const char *zP4, /* The P4 operand */
57501 int p4type /* P4 operand type */
57503 int addr = sqlite3VdbeAddOp3(p, op, p1, p2, p3);
57504 sqlite3VdbeChangeP4(p, addr, zP4, p4type);
57505 return addr;
57509 ** Add an opcode that includes the p4 value as an integer.
57511 SQLITE_PRIVATE int sqlite3VdbeAddOp4Int(
57512 Vdbe *p, /* Add the opcode to this VM */
57513 int op, /* The new opcode */
57514 int p1, /* The P1 operand */
57515 int p2, /* The P2 operand */
57516 int p3, /* The P3 operand */
57517 int p4 /* The P4 operand as an integer */
57519 int addr = sqlite3VdbeAddOp3(p, op, p1, p2, p3);
57520 sqlite3VdbeChangeP4(p, addr, SQLITE_INT_TO_PTR(p4), P4_INT32);
57521 return addr;
57525 ** Create a new symbolic label for an instruction that has yet to be
57526 ** coded. The symbolic label is really just a negative number. The
57527 ** label can be used as the P2 value of an operation. Later, when
57528 ** the label is resolved to a specific address, the VDBE will scan
57529 ** through its operation list and change all values of P2 which match
57530 ** the label into the resolved address.
57532 ** The VDBE knows that a P2 value is a label because labels are
57533 ** always negative and P2 values are suppose to be non-negative.
57534 ** Hence, a negative P2 value is a label that has yet to be resolved.
57536 ** Zero is returned if a malloc() fails.
57538 SQLITE_PRIVATE int sqlite3VdbeMakeLabel(Vdbe *p){
57539 int i;
57540 i = p->nLabel++;
57541 assert( p->magic==VDBE_MAGIC_INIT );
57542 if( i>=p->nLabelAlloc ){
57543 int n = p->nLabelAlloc*2 + 5;
57544 p->aLabel = sqlite3DbReallocOrFree(p->db, p->aLabel,
57545 n*sizeof(p->aLabel[0]));
57546 p->nLabelAlloc = sqlite3DbMallocSize(p->db, p->aLabel)/sizeof(p->aLabel[0]);
57548 if( p->aLabel ){
57549 p->aLabel[i] = -1;
57551 return -1-i;
57555 ** Resolve label "x" to be the address of the next instruction to
57556 ** be inserted. The parameter "x" must have been obtained from
57557 ** a prior call to sqlite3VdbeMakeLabel().
57559 SQLITE_PRIVATE void sqlite3VdbeResolveLabel(Vdbe *p, int x){
57560 int j = -1-x;
57561 assert( p->magic==VDBE_MAGIC_INIT );
57562 assert( j>=0 && j<p->nLabel );
57563 if( p->aLabel ){
57564 p->aLabel[j] = p->nOp;
57569 ** Mark the VDBE as one that can only be run one time.
57571 SQLITE_PRIVATE void sqlite3VdbeRunOnlyOnce(Vdbe *p){
57572 p->runOnlyOnce = 1;
57575 #ifdef SQLITE_DEBUG /* sqlite3AssertMayAbort() logic */
57578 ** The following type and function are used to iterate through all opcodes
57579 ** in a Vdbe main program and each of the sub-programs (triggers) it may
57580 ** invoke directly or indirectly. It should be used as follows:
57582 ** Op *pOp;
57583 ** VdbeOpIter sIter;
57585 ** memset(&sIter, 0, sizeof(sIter));
57586 ** sIter.v = v; // v is of type Vdbe*
57587 ** while( (pOp = opIterNext(&sIter)) ){
57588 ** // Do something with pOp
57589 ** }
57590 ** sqlite3DbFree(v->db, sIter.apSub);
57593 typedef struct VdbeOpIter VdbeOpIter;
57594 struct VdbeOpIter {
57595 Vdbe *v; /* Vdbe to iterate through the opcodes of */
57596 SubProgram **apSub; /* Array of subprograms */
57597 int nSub; /* Number of entries in apSub */
57598 int iAddr; /* Address of next instruction to return */
57599 int iSub; /* 0 = main program, 1 = first sub-program etc. */
57601 static Op *opIterNext(VdbeOpIter *p){
57602 Vdbe *v = p->v;
57603 Op *pRet = 0;
57604 Op *aOp;
57605 int nOp;
57607 if( p->iSub<=p->nSub ){
57609 if( p->iSub==0 ){
57610 aOp = v->aOp;
57611 nOp = v->nOp;
57612 }else{
57613 aOp = p->apSub[p->iSub-1]->aOp;
57614 nOp = p->apSub[p->iSub-1]->nOp;
57616 assert( p->iAddr<nOp );
57618 pRet = &aOp[p->iAddr];
57619 p->iAddr++;
57620 if( p->iAddr==nOp ){
57621 p->iSub++;
57622 p->iAddr = 0;
57625 if( pRet->p4type==P4_SUBPROGRAM ){
57626 int nByte = (p->nSub+1)*sizeof(SubProgram*);
57627 int j;
57628 for(j=0; j<p->nSub; j++){
57629 if( p->apSub[j]==pRet->p4.pProgram ) break;
57631 if( j==p->nSub ){
57632 p->apSub = sqlite3DbReallocOrFree(v->db, p->apSub, nByte);
57633 if( !p->apSub ){
57634 pRet = 0;
57635 }else{
57636 p->apSub[p->nSub++] = pRet->p4.pProgram;
57642 return pRet;
57646 ** Check if the program stored in the VM associated with pParse may
57647 ** throw an ABORT exception (causing the statement, but not entire transaction
57648 ** to be rolled back). This condition is true if the main program or any
57649 ** sub-programs contains any of the following:
57651 ** * OP_Halt with P1=SQLITE_CONSTRAINT and P2=OE_Abort.
57652 ** * OP_HaltIfNull with P1=SQLITE_CONSTRAINT and P2=OE_Abort.
57653 ** * OP_Destroy
57654 ** * OP_VUpdate
57655 ** * OP_VRename
57656 ** * OP_FkCounter with P2==0 (immediate foreign key constraint)
57658 ** Then check that the value of Parse.mayAbort is true if an
57659 ** ABORT may be thrown, or false otherwise. Return true if it does
57660 ** match, or false otherwise. This function is intended to be used as
57661 ** part of an assert statement in the compiler. Similar to:
57663 ** assert( sqlite3VdbeAssertMayAbort(pParse->pVdbe, pParse->mayAbort) );
57665 SQLITE_PRIVATE int sqlite3VdbeAssertMayAbort(Vdbe *v, int mayAbort){
57666 int hasAbort = 0;
57667 Op *pOp;
57668 VdbeOpIter sIter;
57669 memset(&sIter, 0, sizeof(sIter));
57670 sIter.v = v;
57672 while( (pOp = opIterNext(&sIter))!=0 ){
57673 int opcode = pOp->opcode;
57674 if( opcode==OP_Destroy || opcode==OP_VUpdate || opcode==OP_VRename
57675 #ifndef SQLITE_OMIT_FOREIGN_KEY
57676 || (opcode==OP_FkCounter && pOp->p1==0 && pOp->p2==1)
57677 #endif
57678 || ((opcode==OP_Halt || opcode==OP_HaltIfNull)
57679 && (pOp->p1==SQLITE_CONSTRAINT && pOp->p2==OE_Abort))
57681 hasAbort = 1;
57682 break;
57685 sqlite3DbFree(v->db, sIter.apSub);
57687 /* Return true if hasAbort==mayAbort. Or if a malloc failure occured.
57688 ** If malloc failed, then the while() loop above may not have iterated
57689 ** through all opcodes and hasAbort may be set incorrectly. Return
57690 ** true for this case to prevent the assert() in the callers frame
57691 ** from failing. */
57692 return ( v->db->mallocFailed || hasAbort==mayAbort );
57694 #endif /* SQLITE_DEBUG - the sqlite3AssertMayAbort() function */
57697 ** Loop through the program looking for P2 values that are negative
57698 ** on jump instructions. Each such value is a label. Resolve the
57699 ** label by setting the P2 value to its correct non-zero value.
57701 ** This routine is called once after all opcodes have been inserted.
57703 ** Variable *pMaxFuncArgs is set to the maximum value of any P2 argument
57704 ** to an OP_Function, OP_AggStep or OP_VFilter opcode. This is used by
57705 ** sqlite3VdbeMakeReady() to size the Vdbe.apArg[] array.
57707 ** The Op.opflags field is set on all opcodes.
57709 static void resolveP2Values(Vdbe *p, int *pMaxFuncArgs){
57710 int i;
57711 int nMaxArgs = *pMaxFuncArgs;
57712 Op *pOp;
57713 int *aLabel = p->aLabel;
57714 p->readOnly = 1;
57715 for(pOp=p->aOp, i=p->nOp-1; i>=0; i--, pOp++){
57716 u8 opcode = pOp->opcode;
57718 pOp->opflags = sqlite3OpcodeProperty[opcode];
57719 if( opcode==OP_Function || opcode==OP_AggStep ){
57720 if( pOp->p5>nMaxArgs ) nMaxArgs = pOp->p5;
57721 }else if( (opcode==OP_Transaction && pOp->p2!=0) || opcode==OP_Vacuum ){
57722 p->readOnly = 0;
57723 #ifndef SQLITE_OMIT_VIRTUALTABLE
57724 }else if( opcode==OP_VUpdate ){
57725 if( pOp->p2>nMaxArgs ) nMaxArgs = pOp->p2;
57726 }else if( opcode==OP_VFilter ){
57727 int n;
57728 assert( p->nOp - i >= 3 );
57729 assert( pOp[-1].opcode==OP_Integer );
57730 n = pOp[-1].p1;
57731 if( n>nMaxArgs ) nMaxArgs = n;
57732 #endif
57735 if( (pOp->opflags & OPFLG_JUMP)!=0 && pOp->p2<0 ){
57736 assert( -1-pOp->p2<p->nLabel );
57737 pOp->p2 = aLabel[-1-pOp->p2];
57740 sqlite3DbFree(p->db, p->aLabel);
57741 p->aLabel = 0;
57743 *pMaxFuncArgs = nMaxArgs;
57747 ** Return the address of the next instruction to be inserted.
57749 SQLITE_PRIVATE int sqlite3VdbeCurrentAddr(Vdbe *p){
57750 assert( p->magic==VDBE_MAGIC_INIT );
57751 return p->nOp;
57755 ** This function returns a pointer to the array of opcodes associated with
57756 ** the Vdbe passed as the first argument. It is the callers responsibility
57757 ** to arrange for the returned array to be eventually freed using the
57758 ** vdbeFreeOpArray() function.
57760 ** Before returning, *pnOp is set to the number of entries in the returned
57761 ** array. Also, *pnMaxArg is set to the larger of its current value and
57762 ** the number of entries in the Vdbe.apArg[] array required to execute the
57763 ** returned program.
57765 SQLITE_PRIVATE VdbeOp *sqlite3VdbeTakeOpArray(Vdbe *p, int *pnOp, int *pnMaxArg){
57766 VdbeOp *aOp = p->aOp;
57767 assert( aOp && !p->db->mallocFailed );
57769 /* Check that sqlite3VdbeUsesBtree() was not called on this VM */
57770 assert( p->btreeMask==0 );
57772 resolveP2Values(p, pnMaxArg);
57773 *pnOp = p->nOp;
57774 p->aOp = 0;
57775 return aOp;
57779 ** Add a whole list of operations to the operation stack. Return the
57780 ** address of the first operation added.
57782 SQLITE_PRIVATE int sqlite3VdbeAddOpList(Vdbe *p, int nOp, VdbeOpList const *aOp){
57783 int addr;
57784 assert( p->magic==VDBE_MAGIC_INIT );
57785 if( p->nOp + nOp > p->nOpAlloc && growOpArray(p) ){
57786 return 0;
57788 addr = p->nOp;
57789 if( ALWAYS(nOp>0) ){
57790 int i;
57791 VdbeOpList const *pIn = aOp;
57792 for(i=0; i<nOp; i++, pIn++){
57793 int p2 = pIn->p2;
57794 VdbeOp *pOut = &p->aOp[i+addr];
57795 pOut->opcode = pIn->opcode;
57796 pOut->p1 = pIn->p1;
57797 if( p2<0 && (sqlite3OpcodeProperty[pOut->opcode] & OPFLG_JUMP)!=0 ){
57798 pOut->p2 = addr + ADDR(p2);
57799 }else{
57800 pOut->p2 = p2;
57802 pOut->p3 = pIn->p3;
57803 pOut->p4type = P4_NOTUSED;
57804 pOut->p4.p = 0;
57805 pOut->p5 = 0;
57806 #ifdef SQLITE_DEBUG
57807 pOut->zComment = 0;
57808 if( sqlite3VdbeAddopTrace ){
57809 sqlite3VdbePrintOp(0, i+addr, &p->aOp[i+addr]);
57811 #endif
57813 p->nOp += nOp;
57815 return addr;
57819 ** Change the value of the P1 operand for a specific instruction.
57820 ** This routine is useful when a large program is loaded from a
57821 ** static array using sqlite3VdbeAddOpList but we want to make a
57822 ** few minor changes to the program.
57824 SQLITE_PRIVATE void sqlite3VdbeChangeP1(Vdbe *p, int addr, int val){
57825 assert( p!=0 );
57826 assert( addr>=0 );
57827 if( p->nOp>addr ){
57828 p->aOp[addr].p1 = val;
57833 ** Change the value of the P2 operand for a specific instruction.
57834 ** This routine is useful for setting a jump destination.
57836 SQLITE_PRIVATE void sqlite3VdbeChangeP2(Vdbe *p, int addr, int val){
57837 assert( p!=0 );
57838 assert( addr>=0 );
57839 if( p->nOp>addr ){
57840 p->aOp[addr].p2 = val;
57845 ** Change the value of the P3 operand for a specific instruction.
57847 SQLITE_PRIVATE void sqlite3VdbeChangeP3(Vdbe *p, int addr, int val){
57848 assert( p!=0 );
57849 assert( addr>=0 );
57850 if( p->nOp>addr ){
57851 p->aOp[addr].p3 = val;
57856 ** Change the value of the P5 operand for the most recently
57857 ** added operation.
57859 SQLITE_PRIVATE void sqlite3VdbeChangeP5(Vdbe *p, u8 val){
57860 assert( p!=0 );
57861 if( p->aOp ){
57862 assert( p->nOp>0 );
57863 p->aOp[p->nOp-1].p5 = val;
57868 ** Change the P2 operand of instruction addr so that it points to
57869 ** the address of the next instruction to be coded.
57871 SQLITE_PRIVATE void sqlite3VdbeJumpHere(Vdbe *p, int addr){
57872 assert( addr>=0 );
57873 sqlite3VdbeChangeP2(p, addr, p->nOp);
57878 ** If the input FuncDef structure is ephemeral, then free it. If
57879 ** the FuncDef is not ephermal, then do nothing.
57881 static void freeEphemeralFunction(sqlite3 *db, FuncDef *pDef){
57882 if( ALWAYS(pDef) && (pDef->flags & SQLITE_FUNC_EPHEM)!=0 ){
57883 sqlite3DbFree(db, pDef);
57887 static void vdbeFreeOpArray(sqlite3 *, Op *, int);
57890 ** Delete a P4 value if necessary.
57892 static void freeP4(sqlite3 *db, int p4type, void *p4){
57893 if( p4 ){
57894 assert( db );
57895 switch( p4type ){
57896 case P4_REAL:
57897 case P4_INT64:
57898 case P4_DYNAMIC:
57899 case P4_KEYINFO:
57900 case P4_INTARRAY:
57901 case P4_KEYINFO_HANDOFF: {
57902 sqlite3DbFree(db, p4);
57903 break;
57905 case P4_MPRINTF: {
57906 if( db->pnBytesFreed==0 ) sqlite3_free(p4);
57907 break;
57909 case P4_VDBEFUNC: {
57910 VdbeFunc *pVdbeFunc = (VdbeFunc *)p4;
57911 freeEphemeralFunction(db, pVdbeFunc->pFunc);
57912 if( db->pnBytesFreed==0 ) sqlite3VdbeDeleteAuxData(pVdbeFunc, 0);
57913 sqlite3DbFree(db, pVdbeFunc);
57914 break;
57916 case P4_FUNCDEF: {
57917 freeEphemeralFunction(db, (FuncDef*)p4);
57918 break;
57920 case P4_MEM: {
57921 if( db->pnBytesFreed==0 ){
57922 sqlite3ValueFree((sqlite3_value*)p4);
57923 }else{
57924 Mem *p = (Mem*)p4;
57925 sqlite3DbFree(db, p->zMalloc);
57926 sqlite3DbFree(db, p);
57928 break;
57930 case P4_VTAB : {
57931 if( db->pnBytesFreed==0 ) sqlite3VtabUnlock((VTable *)p4);
57932 break;
57939 ** Free the space allocated for aOp and any p4 values allocated for the
57940 ** opcodes contained within. If aOp is not NULL it is assumed to contain
57941 ** nOp entries.
57943 static void vdbeFreeOpArray(sqlite3 *db, Op *aOp, int nOp){
57944 if( aOp ){
57945 Op *pOp;
57946 for(pOp=aOp; pOp<&aOp[nOp]; pOp++){
57947 freeP4(db, pOp->p4type, pOp->p4.p);
57948 #ifdef SQLITE_DEBUG
57949 sqlite3DbFree(db, pOp->zComment);
57950 #endif
57953 sqlite3DbFree(db, aOp);
57957 ** Link the SubProgram object passed as the second argument into the linked
57958 ** list at Vdbe.pSubProgram. This list is used to delete all sub-program
57959 ** objects when the VM is no longer required.
57961 SQLITE_PRIVATE void sqlite3VdbeLinkSubProgram(Vdbe *pVdbe, SubProgram *p){
57962 p->pNext = pVdbe->pProgram;
57963 pVdbe->pProgram = p;
57967 ** Change N opcodes starting at addr to No-ops.
57969 SQLITE_PRIVATE void sqlite3VdbeChangeToNoop(Vdbe *p, int addr, int N){
57970 if( p->aOp ){
57971 VdbeOp *pOp = &p->aOp[addr];
57972 sqlite3 *db = p->db;
57973 while( N-- ){
57974 freeP4(db, pOp->p4type, pOp->p4.p);
57975 memset(pOp, 0, sizeof(pOp[0]));
57976 pOp->opcode = OP_Noop;
57977 pOp++;
57983 ** Change the value of the P4 operand for a specific instruction.
57984 ** This routine is useful when a large program is loaded from a
57985 ** static array using sqlite3VdbeAddOpList but we want to make a
57986 ** few minor changes to the program.
57988 ** If n>=0 then the P4 operand is dynamic, meaning that a copy of
57989 ** the string is made into memory obtained from sqlite3_malloc().
57990 ** A value of n==0 means copy bytes of zP4 up to and including the
57991 ** first null byte. If n>0 then copy n+1 bytes of zP4.
57993 ** If n==P4_KEYINFO it means that zP4 is a pointer to a KeyInfo structure.
57994 ** A copy is made of the KeyInfo structure into memory obtained from
57995 ** sqlite3_malloc, to be freed when the Vdbe is finalized.
57996 ** n==P4_KEYINFO_HANDOFF indicates that zP4 points to a KeyInfo structure
57997 ** stored in memory that the caller has obtained from sqlite3_malloc. The
57998 ** caller should not free the allocation, it will be freed when the Vdbe is
57999 ** finalized.
58001 ** Other values of n (P4_STATIC, P4_COLLSEQ etc.) indicate that zP4 points
58002 ** to a string or structure that is guaranteed to exist for the lifetime of
58003 ** the Vdbe. In these cases we can just copy the pointer.
58005 ** If addr<0 then change P4 on the most recently inserted instruction.
58007 SQLITE_PRIVATE void sqlite3VdbeChangeP4(Vdbe *p, int addr, const char *zP4, int n){
58008 Op *pOp;
58009 sqlite3 *db;
58010 assert( p!=0 );
58011 db = p->db;
58012 assert( p->magic==VDBE_MAGIC_INIT );
58013 if( p->aOp==0 || db->mallocFailed ){
58014 if ( n!=P4_KEYINFO && n!=P4_VTAB ) {
58015 freeP4(db, n, (void*)*(char**)&zP4);
58017 return;
58019 assert( p->nOp>0 );
58020 assert( addr<p->nOp );
58021 if( addr<0 ){
58022 addr = p->nOp - 1;
58024 pOp = &p->aOp[addr];
58025 freeP4(db, pOp->p4type, pOp->p4.p);
58026 pOp->p4.p = 0;
58027 if( n==P4_INT32 ){
58028 /* Note: this cast is safe, because the origin data point was an int
58029 ** that was cast to a (const char *). */
58030 pOp->p4.i = SQLITE_PTR_TO_INT(zP4);
58031 pOp->p4type = P4_INT32;
58032 }else if( zP4==0 ){
58033 pOp->p4.p = 0;
58034 pOp->p4type = P4_NOTUSED;
58035 }else if( n==P4_KEYINFO ){
58036 KeyInfo *pKeyInfo;
58037 int nField, nByte;
58039 nField = ((KeyInfo*)zP4)->nField;
58040 nByte = sizeof(*pKeyInfo) + (nField-1)*sizeof(pKeyInfo->aColl[0]) + nField;
58041 pKeyInfo = sqlite3DbMallocRaw(0, nByte);
58042 pOp->p4.pKeyInfo = pKeyInfo;
58043 if( pKeyInfo ){
58044 u8 *aSortOrder;
58045 memcpy((char*)pKeyInfo, zP4, nByte - nField);
58046 aSortOrder = pKeyInfo->aSortOrder;
58047 if( aSortOrder ){
58048 pKeyInfo->aSortOrder = (unsigned char*)&pKeyInfo->aColl[nField];
58049 memcpy(pKeyInfo->aSortOrder, aSortOrder, nField);
58051 pOp->p4type = P4_KEYINFO;
58052 }else{
58053 p->db->mallocFailed = 1;
58054 pOp->p4type = P4_NOTUSED;
58056 }else if( n==P4_KEYINFO_HANDOFF ){
58057 pOp->p4.p = (void*)zP4;
58058 pOp->p4type = P4_KEYINFO;
58059 }else if( n==P4_VTAB ){
58060 pOp->p4.p = (void*)zP4;
58061 pOp->p4type = P4_VTAB;
58062 sqlite3VtabLock((VTable *)zP4);
58063 assert( ((VTable *)zP4)->db==p->db );
58064 }else if( n<0 ){
58065 pOp->p4.p = (void*)zP4;
58066 pOp->p4type = (signed char)n;
58067 }else{
58068 if( n==0 ) n = sqlite3Strlen30(zP4);
58069 pOp->p4.z = sqlite3DbStrNDup(p->db, zP4, n);
58070 pOp->p4type = P4_DYNAMIC;
58074 #ifndef NDEBUG
58076 ** Change the comment on the the most recently coded instruction. Or
58077 ** insert a No-op and add the comment to that new instruction. This
58078 ** makes the code easier to read during debugging. None of this happens
58079 ** in a production build.
58081 SQLITE_PRIVATE void sqlite3VdbeComment(Vdbe *p, const char *zFormat, ...){
58082 va_list ap;
58083 if( !p ) return;
58084 assert( p->nOp>0 || p->aOp==0 );
58085 assert( p->aOp==0 || p->aOp[p->nOp-1].zComment==0 || p->db->mallocFailed );
58086 if( p->nOp ){
58087 char **pz = &p->aOp[p->nOp-1].zComment;
58088 va_start(ap, zFormat);
58089 sqlite3DbFree(p->db, *pz);
58090 *pz = sqlite3VMPrintf(p->db, zFormat, ap);
58091 va_end(ap);
58094 SQLITE_PRIVATE void sqlite3VdbeNoopComment(Vdbe *p, const char *zFormat, ...){
58095 va_list ap;
58096 if( !p ) return;
58097 sqlite3VdbeAddOp0(p, OP_Noop);
58098 assert( p->nOp>0 || p->aOp==0 );
58099 assert( p->aOp==0 || p->aOp[p->nOp-1].zComment==0 || p->db->mallocFailed );
58100 if( p->nOp ){
58101 char **pz = &p->aOp[p->nOp-1].zComment;
58102 va_start(ap, zFormat);
58103 sqlite3DbFree(p->db, *pz);
58104 *pz = sqlite3VMPrintf(p->db, zFormat, ap);
58105 va_end(ap);
58108 #endif /* NDEBUG */
58111 ** Return the opcode for a given address. If the address is -1, then
58112 ** return the most recently inserted opcode.
58114 ** If a memory allocation error has occurred prior to the calling of this
58115 ** routine, then a pointer to a dummy VdbeOp will be returned. That opcode
58116 ** is readable but not writable, though it is cast to a writable value.
58117 ** The return of a dummy opcode allows the call to continue functioning
58118 ** after a OOM fault without having to check to see if the return from
58119 ** this routine is a valid pointer. But because the dummy.opcode is 0,
58120 ** dummy will never be written to. This is verified by code inspection and
58121 ** by running with Valgrind.
58123 ** About the #ifdef SQLITE_OMIT_TRACE: Normally, this routine is never called
58124 ** unless p->nOp>0. This is because in the absense of SQLITE_OMIT_TRACE,
58125 ** an OP_Trace instruction is always inserted by sqlite3VdbeGet() as soon as
58126 ** a new VDBE is created. So we are free to set addr to p->nOp-1 without
58127 ** having to double-check to make sure that the result is non-negative. But
58128 ** if SQLITE_OMIT_TRACE is defined, the OP_Trace is omitted and we do need to
58129 ** check the value of p->nOp-1 before continuing.
58131 SQLITE_PRIVATE VdbeOp *sqlite3VdbeGetOp(Vdbe *p, int addr){
58132 /* C89 specifies that the constant "dummy" will be initialized to all
58133 ** zeros, which is correct. MSVC generates a warning, nevertheless. */
58134 static const VdbeOp dummy; /* Ignore the MSVC warning about no initializer */
58135 assert( p->magic==VDBE_MAGIC_INIT );
58136 if( addr<0 ){
58137 #ifdef SQLITE_OMIT_TRACE
58138 if( p->nOp==0 ) return (VdbeOp*)&dummy;
58139 #endif
58140 addr = p->nOp - 1;
58142 assert( (addr>=0 && addr<p->nOp) || p->db->mallocFailed );
58143 if( p->db->mallocFailed ){
58144 return (VdbeOp*)&dummy;
58145 }else{
58146 return &p->aOp[addr];
58150 #if !defined(SQLITE_OMIT_EXPLAIN) || !defined(NDEBUG) \
58151 || defined(VDBE_PROFILE) || defined(SQLITE_DEBUG)
58153 ** Compute a string that describes the P4 parameter for an opcode.
58154 ** Use zTemp for any required temporary buffer space.
58156 static char *displayP4(Op *pOp, char *zTemp, int nTemp){
58157 char *zP4 = zTemp;
58158 assert( nTemp>=20 );
58159 switch( pOp->p4type ){
58160 case P4_KEYINFO_STATIC:
58161 case P4_KEYINFO: {
58162 int i, j;
58163 KeyInfo *pKeyInfo = pOp->p4.pKeyInfo;
58164 sqlite3_snprintf(nTemp, zTemp, "keyinfo(%d", pKeyInfo->nField);
58165 i = sqlite3Strlen30(zTemp);
58166 for(j=0; j<pKeyInfo->nField; j++){
58167 CollSeq *pColl = pKeyInfo->aColl[j];
58168 if( pColl ){
58169 int n = sqlite3Strlen30(pColl->zName);
58170 if( i+n>nTemp-6 ){
58171 memcpy(&zTemp[i],",...",4);
58172 break;
58174 zTemp[i++] = ',';
58175 if( pKeyInfo->aSortOrder && pKeyInfo->aSortOrder[j] ){
58176 zTemp[i++] = '-';
58178 memcpy(&zTemp[i], pColl->zName,n+1);
58179 i += n;
58180 }else if( i+4<nTemp-6 ){
58181 memcpy(&zTemp[i],",nil",4);
58182 i += 4;
58185 zTemp[i++] = ')';
58186 zTemp[i] = 0;
58187 assert( i<nTemp );
58188 break;
58190 case P4_COLLSEQ: {
58191 CollSeq *pColl = pOp->p4.pColl;
58192 sqlite3_snprintf(nTemp, zTemp, "collseq(%.20s)", pColl->zName);
58193 break;
58195 case P4_FUNCDEF: {
58196 FuncDef *pDef = pOp->p4.pFunc;
58197 sqlite3_snprintf(nTemp, zTemp, "%s(%d)", pDef->zName, pDef->nArg);
58198 break;
58200 case P4_INT64: {
58201 sqlite3_snprintf(nTemp, zTemp, "%lld", *pOp->p4.pI64);
58202 break;
58204 case P4_INT32: {
58205 sqlite3_snprintf(nTemp, zTemp, "%d", pOp->p4.i);
58206 break;
58208 case P4_REAL: {
58209 sqlite3_snprintf(nTemp, zTemp, "%.16g", *pOp->p4.pReal);
58210 break;
58212 case P4_MEM: {
58213 Mem *pMem = pOp->p4.pMem;
58214 assert( (pMem->flags & MEM_Null)==0 );
58215 if( pMem->flags & MEM_Str ){
58216 zP4 = pMem->z;
58217 }else if( pMem->flags & MEM_Int ){
58218 sqlite3_snprintf(nTemp, zTemp, "%lld", pMem->u.i);
58219 }else if( pMem->flags & MEM_Real ){
58220 sqlite3_snprintf(nTemp, zTemp, "%.16g", pMem->r);
58221 }else{
58222 assert( pMem->flags & MEM_Blob );
58223 zP4 = "(blob)";
58225 break;
58227 #ifndef SQLITE_OMIT_VIRTUALTABLE
58228 case P4_VTAB: {
58229 sqlite3_vtab *pVtab = pOp->p4.pVtab->pVtab;
58230 sqlite3_snprintf(nTemp, zTemp, "vtab:%p:%p", pVtab, pVtab->pModule);
58231 break;
58233 #endif
58234 case P4_INTARRAY: {
58235 sqlite3_snprintf(nTemp, zTemp, "intarray");
58236 break;
58238 case P4_SUBPROGRAM: {
58239 sqlite3_snprintf(nTemp, zTemp, "program");
58240 break;
58242 default: {
58243 zP4 = pOp->p4.z;
58244 if( zP4==0 ){
58245 zP4 = zTemp;
58246 zTemp[0] = 0;
58250 assert( zP4!=0 );
58251 return zP4;
58253 #endif
58256 ** Declare to the Vdbe that the BTree object at db->aDb[i] is used.
58258 ** The prepared statements need to know in advance the complete set of
58259 ** attached databases that they will be using. A mask of these databases
58260 ** is maintained in p->btreeMask and is used for locking and other purposes.
58262 SQLITE_PRIVATE void sqlite3VdbeUsesBtree(Vdbe *p, int i){
58263 assert( i>=0 && i<p->db->nDb && i<(int)sizeof(yDbMask)*8 );
58264 assert( i<(int)sizeof(p->btreeMask)*8 );
58265 p->btreeMask |= ((yDbMask)1)<<i;
58266 if( i!=1 && sqlite3BtreeSharable(p->db->aDb[i].pBt) ){
58267 p->lockMask |= ((yDbMask)1)<<i;
58271 #if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE>0
58273 ** If SQLite is compiled to support shared-cache mode and to be threadsafe,
58274 ** this routine obtains the mutex associated with each BtShared structure
58275 ** that may be accessed by the VM passed as an argument. In doing so it also
58276 ** sets the BtShared.db member of each of the BtShared structures, ensuring
58277 ** that the correct busy-handler callback is invoked if required.
58279 ** If SQLite is not threadsafe but does support shared-cache mode, then
58280 ** sqlite3BtreeEnter() is invoked to set the BtShared.db variables
58281 ** of all of BtShared structures accessible via the database handle
58282 ** associated with the VM.
58284 ** If SQLite is not threadsafe and does not support shared-cache mode, this
58285 ** function is a no-op.
58287 ** The p->btreeMask field is a bitmask of all btrees that the prepared
58288 ** statement p will ever use. Let N be the number of bits in p->btreeMask
58289 ** corresponding to btrees that use shared cache. Then the runtime of
58290 ** this routine is N*N. But as N is rarely more than 1, this should not
58291 ** be a problem.
58293 SQLITE_PRIVATE void sqlite3VdbeEnter(Vdbe *p){
58294 int i;
58295 yDbMask mask;
58296 sqlite3 *db;
58297 Db *aDb;
58298 int nDb;
58299 if( p->lockMask==0 ) return; /* The common case */
58300 db = p->db;
58301 aDb = db->aDb;
58302 nDb = db->nDb;
58303 for(i=0, mask=1; i<nDb; i++, mask += mask){
58304 if( i!=1 && (mask & p->lockMask)!=0 && ALWAYS(aDb[i].pBt!=0) ){
58305 sqlite3BtreeEnter(aDb[i].pBt);
58309 #endif
58311 #if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE>0
58313 ** Unlock all of the btrees previously locked by a call to sqlite3VdbeEnter().
58315 SQLITE_PRIVATE void sqlite3VdbeLeave(Vdbe *p){
58316 int i;
58317 yDbMask mask;
58318 sqlite3 *db;
58319 Db *aDb;
58320 int nDb;
58321 if( p->lockMask==0 ) return; /* The common case */
58322 db = p->db;
58323 aDb = db->aDb;
58324 nDb = db->nDb;
58325 for(i=0, mask=1; i<nDb; i++, mask += mask){
58326 if( i!=1 && (mask & p->lockMask)!=0 && ALWAYS(aDb[i].pBt!=0) ){
58327 sqlite3BtreeLeave(aDb[i].pBt);
58331 #endif
58333 #if defined(VDBE_PROFILE) || defined(SQLITE_DEBUG)
58335 ** Print a single opcode. This routine is used for debugging only.
58337 SQLITE_PRIVATE void sqlite3VdbePrintOp(FILE *pOut, int pc, Op *pOp){
58338 char *zP4;
58339 char zPtr[50];
58340 static const char *zFormat1 = "%4d %-13s %4d %4d %4d %-4s %.2X %s\n";
58341 if( pOut==0 ) pOut = stdout;
58342 zP4 = displayP4(pOp, zPtr, sizeof(zPtr));
58343 fprintf(pOut, zFormat1, pc,
58344 sqlite3OpcodeName(pOp->opcode), pOp->p1, pOp->p2, pOp->p3, zP4, pOp->p5,
58345 #ifdef SQLITE_DEBUG
58346 pOp->zComment ? pOp->zComment : ""
58347 #else
58349 #endif
58351 fflush(pOut);
58353 #endif
58356 ** Release an array of N Mem elements
58358 static void releaseMemArray(Mem *p, int N){
58359 if( p && N ){
58360 Mem *pEnd;
58361 sqlite3 *db = p->db;
58362 u8 malloc_failed = db->mallocFailed;
58363 if( db->pnBytesFreed ){
58364 for(pEnd=&p[N]; p<pEnd; p++){
58365 sqlite3DbFree(db, p->zMalloc);
58367 return;
58369 for(pEnd=&p[N]; p<pEnd; p++){
58370 assert( (&p[1])==pEnd || p[0].db==p[1].db );
58372 /* This block is really an inlined version of sqlite3VdbeMemRelease()
58373 ** that takes advantage of the fact that the memory cell value is
58374 ** being set to NULL after releasing any dynamic resources.
58376 ** The justification for duplicating code is that according to
58377 ** callgrind, this causes a certain test case to hit the CPU 4.7
58378 ** percent less (x86 linux, gcc version 4.1.2, -O6) than if
58379 ** sqlite3MemRelease() were called from here. With -O2, this jumps
58380 ** to 6.6 percent. The test case is inserting 1000 rows into a table
58381 ** with no indexes using a single prepared INSERT statement, bind()
58382 ** and reset(). Inserts are grouped into a transaction.
58384 if( p->flags&(MEM_Agg|MEM_Dyn|MEM_Frame|MEM_RowSet) ){
58385 sqlite3VdbeMemRelease(p);
58386 }else if( p->zMalloc ){
58387 sqlite3DbFree(db, p->zMalloc);
58388 p->zMalloc = 0;
58391 p->flags = MEM_Null;
58393 db->mallocFailed = malloc_failed;
58398 ** Delete a VdbeFrame object and its contents. VdbeFrame objects are
58399 ** allocated by the OP_Program opcode in sqlite3VdbeExec().
58401 SQLITE_PRIVATE void sqlite3VdbeFrameDelete(VdbeFrame *p){
58402 int i;
58403 Mem *aMem = VdbeFrameMem(p);
58404 VdbeCursor **apCsr = (VdbeCursor **)&aMem[p->nChildMem];
58405 for(i=0; i<p->nChildCsr; i++){
58406 sqlite3VdbeFreeCursor(p->v, apCsr[i]);
58408 releaseMemArray(aMem, p->nChildMem);
58409 sqlite3DbFree(p->v->db, p);
58412 #ifndef SQLITE_OMIT_EXPLAIN
58414 ** Give a listing of the program in the virtual machine.
58416 ** The interface is the same as sqlite3VdbeExec(). But instead of
58417 ** running the code, it invokes the callback once for each instruction.
58418 ** This feature is used to implement "EXPLAIN".
58420 ** When p->explain==1, each instruction is listed. When
58421 ** p->explain==2, only OP_Explain instructions are listed and these
58422 ** are shown in a different format. p->explain==2 is used to implement
58423 ** EXPLAIN QUERY PLAN.
58425 ** When p->explain==1, first the main program is listed, then each of
58426 ** the trigger subprograms are listed one by one.
58428 SQLITE_PRIVATE int sqlite3VdbeList(
58429 Vdbe *p /* The VDBE */
58431 int nRow; /* Stop when row count reaches this */
58432 int nSub = 0; /* Number of sub-vdbes seen so far */
58433 SubProgram **apSub = 0; /* Array of sub-vdbes */
58434 Mem *pSub = 0; /* Memory cell hold array of subprogs */
58435 sqlite3 *db = p->db; /* The database connection */
58436 int i; /* Loop counter */
58437 int rc = SQLITE_OK; /* Return code */
58438 Mem *pMem = p->pResultSet = &p->aMem[1]; /* First Mem of result set */
58440 assert( p->explain );
58441 assert( p->magic==VDBE_MAGIC_RUN );
58442 assert( p->rc==SQLITE_OK || p->rc==SQLITE_BUSY || p->rc==SQLITE_NOMEM );
58444 /* Even though this opcode does not use dynamic strings for
58445 ** the result, result columns may become dynamic if the user calls
58446 ** sqlite3_column_text16(), causing a translation to UTF-16 encoding.
58448 releaseMemArray(pMem, 8);
58450 if( p->rc==SQLITE_NOMEM ){
58451 /* This happens if a malloc() inside a call to sqlite3_column_text() or
58452 ** sqlite3_column_text16() failed. */
58453 db->mallocFailed = 1;
58454 return SQLITE_ERROR;
58457 /* When the number of output rows reaches nRow, that means the
58458 ** listing has finished and sqlite3_step() should return SQLITE_DONE.
58459 ** nRow is the sum of the number of rows in the main program, plus
58460 ** the sum of the number of rows in all trigger subprograms encountered
58461 ** so far. The nRow value will increase as new trigger subprograms are
58462 ** encountered, but p->pc will eventually catch up to nRow.
58464 nRow = p->nOp;
58465 if( p->explain==1 ){
58466 /* The first 8 memory cells are used for the result set. So we will
58467 ** commandeer the 9th cell to use as storage for an array of pointers
58468 ** to trigger subprograms. The VDBE is guaranteed to have at least 9
58469 ** cells. */
58470 assert( p->nMem>9 );
58471 pSub = &p->aMem[9];
58472 if( pSub->flags&MEM_Blob ){
58473 /* On the first call to sqlite3_step(), pSub will hold a NULL. It is
58474 ** initialized to a BLOB by the P4_SUBPROGRAM processing logic below */
58475 nSub = pSub->n/sizeof(Vdbe*);
58476 apSub = (SubProgram **)pSub->z;
58478 for(i=0; i<nSub; i++){
58479 nRow += apSub[i]->nOp;
58484 i = p->pc++;
58485 }while( i<nRow && p->explain==2 && p->aOp[i].opcode!=OP_Explain );
58486 if( i>=nRow ){
58487 p->rc = SQLITE_OK;
58488 rc = SQLITE_DONE;
58489 }else if( db->u1.isInterrupted ){
58490 p->rc = SQLITE_INTERRUPT;
58491 rc = SQLITE_ERROR;
58492 sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3ErrStr(p->rc));
58493 }else{
58494 char *z;
58495 Op *pOp;
58496 if( i<p->nOp ){
58497 /* The output line number is small enough that we are still in the
58498 ** main program. */
58499 pOp = &p->aOp[i];
58500 }else{
58501 /* We are currently listing subprograms. Figure out which one and
58502 ** pick up the appropriate opcode. */
58503 int j;
58504 i -= p->nOp;
58505 for(j=0; i>=apSub[j]->nOp; j++){
58506 i -= apSub[j]->nOp;
58508 pOp = &apSub[j]->aOp[i];
58510 if( p->explain==1 ){
58511 pMem->flags = MEM_Int;
58512 pMem->type = SQLITE_INTEGER;
58513 pMem->u.i = i; /* Program counter */
58514 pMem++;
58516 pMem->flags = MEM_Static|MEM_Str|MEM_Term;
58517 pMem->z = (char*)sqlite3OpcodeName(pOp->opcode); /* Opcode */
58518 assert( pMem->z!=0 );
58519 pMem->n = sqlite3Strlen30(pMem->z);
58520 pMem->type = SQLITE_TEXT;
58521 pMem->enc = SQLITE_UTF8;
58522 pMem++;
58524 /* When an OP_Program opcode is encounter (the only opcode that has
58525 ** a P4_SUBPROGRAM argument), expand the size of the array of subprograms
58526 ** kept in p->aMem[9].z to hold the new program - assuming this subprogram
58527 ** has not already been seen.
58529 if( pOp->p4type==P4_SUBPROGRAM ){
58530 int nByte = (nSub+1)*sizeof(SubProgram*);
58531 int j;
58532 for(j=0; j<nSub; j++){
58533 if( apSub[j]==pOp->p4.pProgram ) break;
58535 if( j==nSub && SQLITE_OK==sqlite3VdbeMemGrow(pSub, nByte, 1) ){
58536 apSub = (SubProgram **)pSub->z;
58537 apSub[nSub++] = pOp->p4.pProgram;
58538 pSub->flags |= MEM_Blob;
58539 pSub->n = nSub*sizeof(SubProgram*);
58544 pMem->flags = MEM_Int;
58545 pMem->u.i = pOp->p1; /* P1 */
58546 pMem->type = SQLITE_INTEGER;
58547 pMem++;
58549 pMem->flags = MEM_Int;
58550 pMem->u.i = pOp->p2; /* P2 */
58551 pMem->type = SQLITE_INTEGER;
58552 pMem++;
58554 pMem->flags = MEM_Int;
58555 pMem->u.i = pOp->p3; /* P3 */
58556 pMem->type = SQLITE_INTEGER;
58557 pMem++;
58559 if( sqlite3VdbeMemGrow(pMem, 32, 0) ){ /* P4 */
58560 assert( p->db->mallocFailed );
58561 return SQLITE_ERROR;
58563 pMem->flags = MEM_Dyn|MEM_Str|MEM_Term;
58564 z = displayP4(pOp, pMem->z, 32);
58565 if( z!=pMem->z ){
58566 sqlite3VdbeMemSetStr(pMem, z, -1, SQLITE_UTF8, 0);
58567 }else{
58568 assert( pMem->z!=0 );
58569 pMem->n = sqlite3Strlen30(pMem->z);
58570 pMem->enc = SQLITE_UTF8;
58572 pMem->type = SQLITE_TEXT;
58573 pMem++;
58575 if( p->explain==1 ){
58576 if( sqlite3VdbeMemGrow(pMem, 4, 0) ){
58577 assert( p->db->mallocFailed );
58578 return SQLITE_ERROR;
58580 pMem->flags = MEM_Dyn|MEM_Str|MEM_Term;
58581 pMem->n = 2;
58582 sqlite3_snprintf(3, pMem->z, "%.2x", pOp->p5); /* P5 */
58583 pMem->type = SQLITE_TEXT;
58584 pMem->enc = SQLITE_UTF8;
58585 pMem++;
58587 #ifdef SQLITE_DEBUG
58588 if( pOp->zComment ){
58589 pMem->flags = MEM_Str|MEM_Term;
58590 pMem->z = pOp->zComment;
58591 pMem->n = sqlite3Strlen30(pMem->z);
58592 pMem->enc = SQLITE_UTF8;
58593 pMem->type = SQLITE_TEXT;
58594 }else
58595 #endif
58597 pMem->flags = MEM_Null; /* Comment */
58598 pMem->type = SQLITE_NULL;
58602 p->nResColumn = 8 - 4*(p->explain-1);
58603 p->rc = SQLITE_OK;
58604 rc = SQLITE_ROW;
58606 return rc;
58608 #endif /* SQLITE_OMIT_EXPLAIN */
58610 #ifdef SQLITE_DEBUG
58612 ** Print the SQL that was used to generate a VDBE program.
58614 SQLITE_PRIVATE void sqlite3VdbePrintSql(Vdbe *p){
58615 int nOp = p->nOp;
58616 VdbeOp *pOp;
58617 if( nOp<1 ) return;
58618 pOp = &p->aOp[0];
58619 if( pOp->opcode==OP_Trace && pOp->p4.z!=0 ){
58620 const char *z = pOp->p4.z;
58621 while( sqlite3Isspace(*z) ) z++;
58622 printf("SQL: [%s]\n", z);
58625 #endif
58627 #if !defined(SQLITE_OMIT_TRACE) && defined(SQLITE_ENABLE_IOTRACE)
58629 ** Print an IOTRACE message showing SQL content.
58631 SQLITE_PRIVATE void sqlite3VdbeIOTraceSql(Vdbe *p){
58632 int nOp = p->nOp;
58633 VdbeOp *pOp;
58634 if( sqlite3IoTrace==0 ) return;
58635 if( nOp<1 ) return;
58636 pOp = &p->aOp[0];
58637 if( pOp->opcode==OP_Trace && pOp->p4.z!=0 ){
58638 int i, j;
58639 char z[1000];
58640 sqlite3_snprintf(sizeof(z), z, "%s", pOp->p4.z);
58641 for(i=0; sqlite3Isspace(z[i]); i++){}
58642 for(j=0; z[i]; i++){
58643 if( sqlite3Isspace(z[i]) ){
58644 if( z[i-1]!=' ' ){
58645 z[j++] = ' ';
58647 }else{
58648 z[j++] = z[i];
58651 z[j] = 0;
58652 sqlite3IoTrace("SQL %s\n", z);
58655 #endif /* !SQLITE_OMIT_TRACE && SQLITE_ENABLE_IOTRACE */
58658 ** Allocate space from a fixed size buffer and return a pointer to
58659 ** that space. If insufficient space is available, return NULL.
58661 ** The pBuf parameter is the initial value of a pointer which will
58662 ** receive the new memory. pBuf is normally NULL. If pBuf is not
58663 ** NULL, it means that memory space has already been allocated and that
58664 ** this routine should not allocate any new memory. When pBuf is not
58665 ** NULL simply return pBuf. Only allocate new memory space when pBuf
58666 ** is NULL.
58668 ** nByte is the number of bytes of space needed.
58670 ** *ppFrom points to available space and pEnd points to the end of the
58671 ** available space. When space is allocated, *ppFrom is advanced past
58672 ** the end of the allocated space.
58674 ** *pnByte is a counter of the number of bytes of space that have failed
58675 ** to allocate. If there is insufficient space in *ppFrom to satisfy the
58676 ** request, then increment *pnByte by the amount of the request.
58678 static void *allocSpace(
58679 void *pBuf, /* Where return pointer will be stored */
58680 int nByte, /* Number of bytes to allocate */
58681 u8 **ppFrom, /* IN/OUT: Allocate from *ppFrom */
58682 u8 *pEnd, /* Pointer to 1 byte past the end of *ppFrom buffer */
58683 int *pnByte /* If allocation cannot be made, increment *pnByte */
58685 assert( EIGHT_BYTE_ALIGNMENT(*ppFrom) );
58686 if( pBuf ) return pBuf;
58687 nByte = ROUND8(nByte);
58688 if( &(*ppFrom)[nByte] <= pEnd ){
58689 pBuf = (void*)*ppFrom;
58690 *ppFrom += nByte;
58691 }else{
58692 *pnByte += nByte;
58694 return pBuf;
58698 ** Prepare a virtual machine for execution. This involves things such
58699 ** as allocating stack space and initializing the program counter.
58700 ** After the VDBE has be prepped, it can be executed by one or more
58701 ** calls to sqlite3VdbeExec().
58703 ** This is the only way to move a VDBE from VDBE_MAGIC_INIT to
58704 ** VDBE_MAGIC_RUN.
58706 ** This function may be called more than once on a single virtual machine.
58707 ** The first call is made while compiling the SQL statement. Subsequent
58708 ** calls are made as part of the process of resetting a statement to be
58709 ** re-executed (from a call to sqlite3_reset()). The nVar, nMem, nCursor
58710 ** and isExplain parameters are only passed correct values the first time
58711 ** the function is called. On subsequent calls, from sqlite3_reset(), nVar
58712 ** is passed -1 and nMem, nCursor and isExplain are all passed zero.
58714 SQLITE_PRIVATE void sqlite3VdbeMakeReady(
58715 Vdbe *p, /* The VDBE */
58716 int nVar, /* Number of '?' see in the SQL statement */
58717 int nMem, /* Number of memory cells to allocate */
58718 int nCursor, /* Number of cursors to allocate */
58719 int nArg, /* Maximum number of args in SubPrograms */
58720 int isExplain, /* True if the EXPLAIN keywords is present */
58721 int usesStmtJournal /* True to set Vdbe.usesStmtJournal */
58723 int n;
58724 sqlite3 *db = p->db;
58726 assert( p!=0 );
58727 assert( p->magic==VDBE_MAGIC_INIT );
58729 /* There should be at least one opcode.
58731 assert( p->nOp>0 );
58733 /* Set the magic to VDBE_MAGIC_RUN sooner rather than later. */
58734 p->magic = VDBE_MAGIC_RUN;
58736 /* For each cursor required, also allocate a memory cell. Memory
58737 ** cells (nMem+1-nCursor)..nMem, inclusive, will never be used by
58738 ** the vdbe program. Instead they are used to allocate space for
58739 ** VdbeCursor/BtCursor structures. The blob of memory associated with
58740 ** cursor 0 is stored in memory cell nMem. Memory cell (nMem-1)
58741 ** stores the blob of memory associated with cursor 1, etc.
58743 ** See also: allocateCursor().
58745 nMem += nCursor;
58747 /* Allocate space for memory registers, SQL variables, VDBE cursors and
58748 ** an array to marshal SQL function arguments in. This is only done the
58749 ** first time this function is called for a given VDBE, not when it is
58750 ** being called from sqlite3_reset() to reset the virtual machine.
58752 if( nVar>=0 && ALWAYS(db->mallocFailed==0) ){
58753 u8 *zCsr = (u8 *)&p->aOp[p->nOp]; /* Memory avaliable for alloation */
58754 u8 *zEnd = (u8 *)&p->aOp[p->nOpAlloc]; /* First byte past available mem */
58755 int nByte; /* How much extra memory needed */
58757 resolveP2Values(p, &nArg);
58758 p->usesStmtJournal = (u8)usesStmtJournal;
58759 if( isExplain && nMem<10 ){
58760 nMem = 10;
58762 memset(zCsr, 0, zEnd-zCsr);
58763 zCsr += (zCsr - (u8*)0)&7;
58764 assert( EIGHT_BYTE_ALIGNMENT(zCsr) );
58766 /* Memory for registers, parameters, cursor, etc, is allocated in two
58767 ** passes. On the first pass, we try to reuse unused space at the
58768 ** end of the opcode array. If we are unable to satisfy all memory
58769 ** requirements by reusing the opcode array tail, then the second
58770 ** pass will fill in the rest using a fresh allocation.
58772 ** This two-pass approach that reuses as much memory as possible from
58773 ** the leftover space at the end of the opcode array can significantly
58774 ** reduce the amount of memory held by a prepared statement.
58776 do {
58777 nByte = 0;
58778 p->aMem = allocSpace(p->aMem, nMem*sizeof(Mem), &zCsr, zEnd, &nByte);
58779 p->aVar = allocSpace(p->aVar, nVar*sizeof(Mem), &zCsr, zEnd, &nByte);
58780 p->apArg = allocSpace(p->apArg, nArg*sizeof(Mem*), &zCsr, zEnd, &nByte);
58781 p->azVar = allocSpace(p->azVar, nVar*sizeof(char*), &zCsr, zEnd, &nByte);
58782 p->apCsr = allocSpace(p->apCsr, nCursor*sizeof(VdbeCursor*),
58783 &zCsr, zEnd, &nByte);
58784 if( nByte ){
58785 p->pFree = sqlite3DbMallocZero(db, nByte);
58787 zCsr = p->pFree;
58788 zEnd = &zCsr[nByte];
58789 }while( nByte && !db->mallocFailed );
58791 p->nCursor = (u16)nCursor;
58792 if( p->aVar ){
58793 p->nVar = (ynVar)nVar;
58794 for(n=0; n<nVar; n++){
58795 p->aVar[n].flags = MEM_Null;
58796 p->aVar[n].db = db;
58799 if( p->aMem ){
58800 p->aMem--; /* aMem[] goes from 1..nMem */
58801 p->nMem = nMem; /* not from 0..nMem-1 */
58802 for(n=1; n<=nMem; n++){
58803 p->aMem[n].flags = MEM_Null;
58804 p->aMem[n].db = db;
58808 #ifdef SQLITE_DEBUG
58809 for(n=1; n<p->nMem; n++){
58810 assert( p->aMem[n].db==db );
58812 #endif
58814 p->pc = -1;
58815 p->rc = SQLITE_OK;
58816 p->errorAction = OE_Abort;
58817 p->explain |= isExplain;
58818 p->magic = VDBE_MAGIC_RUN;
58819 p->nChange = 0;
58820 p->cacheCtr = 1;
58821 p->minWriteFileFormat = 255;
58822 p->iStatement = 0;
58823 p->nFkConstraint = 0;
58824 #ifdef VDBE_PROFILE
58826 int i;
58827 for(i=0; i<p->nOp; i++){
58828 p->aOp[i].cnt = 0;
58829 p->aOp[i].cycles = 0;
58832 #endif
58836 ** Close a VDBE cursor and release all the resources that cursor
58837 ** happens to hold.
58839 SQLITE_PRIVATE void sqlite3VdbeFreeCursor(Vdbe *p, VdbeCursor *pCx){
58840 if( pCx==0 ){
58841 return;
58843 if( pCx->pBt ){
58844 sqlite3BtreeClose(pCx->pBt);
58845 /* The pCx->pCursor will be close automatically, if it exists, by
58846 ** the call above. */
58847 }else if( pCx->pCursor ){
58848 sqlite3BtreeCloseCursor(pCx->pCursor);
58850 #ifndef SQLITE_OMIT_VIRTUALTABLE
58851 if( pCx->pVtabCursor ){
58852 sqlite3_vtab_cursor *pVtabCursor = pCx->pVtabCursor;
58853 const sqlite3_module *pModule = pCx->pModule;
58854 p->inVtabMethod = 1;
58855 pModule->xClose(pVtabCursor);
58856 p->inVtabMethod = 0;
58858 #endif
58862 ** Copy the values stored in the VdbeFrame structure to its Vdbe. This
58863 ** is used, for example, when a trigger sub-program is halted to restore
58864 ** control to the main program.
58866 SQLITE_PRIVATE int sqlite3VdbeFrameRestore(VdbeFrame *pFrame){
58867 Vdbe *v = pFrame->v;
58868 v->aOp = pFrame->aOp;
58869 v->nOp = pFrame->nOp;
58870 v->aMem = pFrame->aMem;
58871 v->nMem = pFrame->nMem;
58872 v->apCsr = pFrame->apCsr;
58873 v->nCursor = pFrame->nCursor;
58874 v->db->lastRowid = pFrame->lastRowid;
58875 v->nChange = pFrame->nChange;
58876 return pFrame->pc;
58880 ** Close all cursors.
58882 ** Also release any dynamic memory held by the VM in the Vdbe.aMem memory
58883 ** cell array. This is necessary as the memory cell array may contain
58884 ** pointers to VdbeFrame objects, which may in turn contain pointers to
58885 ** open cursors.
58887 static void closeAllCursors(Vdbe *p){
58888 if( p->pFrame ){
58889 VdbeFrame *pFrame;
58890 for(pFrame=p->pFrame; pFrame->pParent; pFrame=pFrame->pParent);
58891 sqlite3VdbeFrameRestore(pFrame);
58893 p->pFrame = 0;
58894 p->nFrame = 0;
58896 if( p->apCsr ){
58897 int i;
58898 for(i=0; i<p->nCursor; i++){
58899 VdbeCursor *pC = p->apCsr[i];
58900 if( pC ){
58901 sqlite3VdbeFreeCursor(p, pC);
58902 p->apCsr[i] = 0;
58906 if( p->aMem ){
58907 releaseMemArray(&p->aMem[1], p->nMem);
58909 while( p->pDelFrame ){
58910 VdbeFrame *pDel = p->pDelFrame;
58911 p->pDelFrame = pDel->pParent;
58912 sqlite3VdbeFrameDelete(pDel);
58917 ** Clean up the VM after execution.
58919 ** This routine will automatically close any cursors, lists, and/or
58920 ** sorters that were left open. It also deletes the values of
58921 ** variables in the aVar[] array.
58923 static void Cleanup(Vdbe *p){
58924 sqlite3 *db = p->db;
58926 #ifdef SQLITE_DEBUG
58927 /* Execute assert() statements to ensure that the Vdbe.apCsr[] and
58928 ** Vdbe.aMem[] arrays have already been cleaned up. */
58929 int i;
58930 for(i=0; i<p->nCursor; i++) assert( p->apCsr==0 || p->apCsr[i]==0 );
58931 for(i=1; i<=p->nMem; i++) assert( p->aMem==0 || p->aMem[i].flags==MEM_Null );
58932 #endif
58934 sqlite3DbFree(db, p->zErrMsg);
58935 p->zErrMsg = 0;
58936 p->pResultSet = 0;
58940 ** Set the number of result columns that will be returned by this SQL
58941 ** statement. This is now set at compile time, rather than during
58942 ** execution of the vdbe program so that sqlite3_column_count() can
58943 ** be called on an SQL statement before sqlite3_step().
58945 SQLITE_PRIVATE void sqlite3VdbeSetNumCols(Vdbe *p, int nResColumn){
58946 Mem *pColName;
58947 int n;
58948 sqlite3 *db = p->db;
58950 releaseMemArray(p->aColName, p->nResColumn*COLNAME_N);
58951 sqlite3DbFree(db, p->aColName);
58952 n = nResColumn*COLNAME_N;
58953 p->nResColumn = (u16)nResColumn;
58954 p->aColName = pColName = (Mem*)sqlite3DbMallocZero(db, sizeof(Mem)*n );
58955 if( p->aColName==0 ) return;
58956 while( n-- > 0 ){
58957 pColName->flags = MEM_Null;
58958 pColName->db = p->db;
58959 pColName++;
58964 ** Set the name of the idx'th column to be returned by the SQL statement.
58965 ** zName must be a pointer to a nul terminated string.
58967 ** This call must be made after a call to sqlite3VdbeSetNumCols().
58969 ** The final parameter, xDel, must be one of SQLITE_DYNAMIC, SQLITE_STATIC
58970 ** or SQLITE_TRANSIENT. If it is SQLITE_DYNAMIC, then the buffer pointed
58971 ** to by zName will be freed by sqlite3DbFree() when the vdbe is destroyed.
58973 SQLITE_PRIVATE int sqlite3VdbeSetColName(
58974 Vdbe *p, /* Vdbe being configured */
58975 int idx, /* Index of column zName applies to */
58976 int var, /* One of the COLNAME_* constants */
58977 const char *zName, /* Pointer to buffer containing name */
58978 void (*xDel)(void*) /* Memory management strategy for zName */
58980 int rc;
58981 Mem *pColName;
58982 assert( idx<p->nResColumn );
58983 assert( var<COLNAME_N );
58984 if( p->db->mallocFailed ){
58985 assert( !zName || xDel!=SQLITE_DYNAMIC );
58986 return SQLITE_NOMEM;
58988 assert( p->aColName!=0 );
58989 pColName = &(p->aColName[idx+var*p->nResColumn]);
58990 rc = sqlite3VdbeMemSetStr(pColName, zName, -1, SQLITE_UTF8, xDel);
58991 assert( rc!=0 || !zName || (pColName->flags&MEM_Term)!=0 );
58992 return rc;
58996 ** A read or write transaction may or may not be active on database handle
58997 ** db. If a transaction is active, commit it. If there is a
58998 ** write-transaction spanning more than one database file, this routine
58999 ** takes care of the master journal trickery.
59001 static int vdbeCommit(sqlite3 *db, Vdbe *p){
59002 int i;
59003 int nTrans = 0; /* Number of databases with an active write-transaction */
59004 int rc = SQLITE_OK;
59005 int needXcommit = 0;
59007 #ifdef SQLITE_OMIT_VIRTUALTABLE
59008 /* With this option, sqlite3VtabSync() is defined to be simply
59009 ** SQLITE_OK so p is not used.
59011 UNUSED_PARAMETER(p);
59012 #endif
59014 /* Before doing anything else, call the xSync() callback for any
59015 ** virtual module tables written in this transaction. This has to
59016 ** be done before determining whether a master journal file is
59017 ** required, as an xSync() callback may add an attached database
59018 ** to the transaction.
59020 rc = sqlite3VtabSync(db, &p->zErrMsg);
59022 /* This loop determines (a) if the commit hook should be invoked and
59023 ** (b) how many database files have open write transactions, not
59024 ** including the temp database. (b) is important because if more than
59025 ** one database file has an open write transaction, a master journal
59026 ** file is required for an atomic commit.
59028 for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
59029 Btree *pBt = db->aDb[i].pBt;
59030 if( sqlite3BtreeIsInTrans(pBt) ){
59031 needXcommit = 1;
59032 if( i!=1 ) nTrans++;
59033 rc = sqlite3PagerExclusiveLock(sqlite3BtreePager(pBt));
59036 if( rc!=SQLITE_OK ){
59037 return rc;
59040 /* If there are any write-transactions at all, invoke the commit hook */
59041 if( needXcommit && db->xCommitCallback ){
59042 rc = db->xCommitCallback(db->pCommitArg);
59043 if( rc ){
59044 return SQLITE_CONSTRAINT;
59048 /* The simple case - no more than one database file (not counting the
59049 ** TEMP database) has a transaction active. There is no need for the
59050 ** master-journal.
59052 ** If the return value of sqlite3BtreeGetFilename() is a zero length
59053 ** string, it means the main database is :memory: or a temp file. In
59054 ** that case we do not support atomic multi-file commits, so use the
59055 ** simple case then too.
59057 if( 0==sqlite3Strlen30(sqlite3BtreeGetFilename(db->aDb[0].pBt))
59058 || nTrans<=1
59060 for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
59061 Btree *pBt = db->aDb[i].pBt;
59062 if( pBt ){
59063 rc = sqlite3BtreeCommitPhaseOne(pBt, 0);
59067 /* Do the commit only if all databases successfully complete phase 1.
59068 ** If one of the BtreeCommitPhaseOne() calls fails, this indicates an
59069 ** IO error while deleting or truncating a journal file. It is unlikely,
59070 ** but could happen. In this case abandon processing and return the error.
59072 for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
59073 Btree *pBt = db->aDb[i].pBt;
59074 if( pBt ){
59075 rc = sqlite3BtreeCommitPhaseTwo(pBt, 0);
59078 if( rc==SQLITE_OK ){
59079 sqlite3VtabCommit(db);
59083 /* The complex case - There is a multi-file write-transaction active.
59084 ** This requires a master journal file to ensure the transaction is
59085 ** committed atomicly.
59087 #ifndef SQLITE_OMIT_DISKIO
59088 else{
59089 sqlite3_vfs *pVfs = db->pVfs;
59090 int needSync = 0;
59091 char *zMaster = 0; /* File-name for the master journal */
59092 char const *zMainFile = sqlite3BtreeGetFilename(db->aDb[0].pBt);
59093 sqlite3_file *pMaster = 0;
59094 i64 offset = 0;
59095 int res;
59097 /* Select a master journal file name */
59098 do {
59099 u32 iRandom;
59100 sqlite3DbFree(db, zMaster);
59101 sqlite3_randomness(sizeof(iRandom), &iRandom);
59102 zMaster = sqlite3MPrintf(db, "%s-mj%08X", zMainFile, iRandom&0x7fffffff);
59103 if( !zMaster ){
59104 return SQLITE_NOMEM;
59106 rc = sqlite3OsAccess(pVfs, zMaster, SQLITE_ACCESS_EXISTS, &res);
59107 }while( rc==SQLITE_OK && res );
59108 if( rc==SQLITE_OK ){
59109 /* Open the master journal. */
59110 rc = sqlite3OsOpenMalloc(pVfs, zMaster, &pMaster,
59111 SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|
59112 SQLITE_OPEN_EXCLUSIVE|SQLITE_OPEN_MASTER_JOURNAL, 0
59115 if( rc!=SQLITE_OK ){
59116 sqlite3DbFree(db, zMaster);
59117 return rc;
59120 /* Write the name of each database file in the transaction into the new
59121 ** master journal file. If an error occurs at this point close
59122 ** and delete the master journal file. All the individual journal files
59123 ** still have 'null' as the master journal pointer, so they will roll
59124 ** back independently if a failure occurs.
59126 for(i=0; i<db->nDb; i++){
59127 Btree *pBt = db->aDb[i].pBt;
59128 if( sqlite3BtreeIsInTrans(pBt) ){
59129 char const *zFile = sqlite3BtreeGetJournalname(pBt);
59130 if( zFile==0 ){
59131 continue; /* Ignore TEMP and :memory: databases */
59133 assert( zFile[0]!=0 );
59134 if( !needSync && !sqlite3BtreeSyncDisabled(pBt) ){
59135 needSync = 1;
59137 rc = sqlite3OsWrite(pMaster, zFile, sqlite3Strlen30(zFile)+1, offset);
59138 offset += sqlite3Strlen30(zFile)+1;
59139 if( rc!=SQLITE_OK ){
59140 sqlite3OsCloseFree(pMaster);
59141 sqlite3OsDelete(pVfs, zMaster, 0);
59142 sqlite3DbFree(db, zMaster);
59143 return rc;
59148 /* Sync the master journal file. If the IOCAP_SEQUENTIAL device
59149 ** flag is set this is not required.
59151 if( needSync
59152 && 0==(sqlite3OsDeviceCharacteristics(pMaster)&SQLITE_IOCAP_SEQUENTIAL)
59153 && SQLITE_OK!=(rc = sqlite3OsSync(pMaster, SQLITE_SYNC_NORMAL))
59155 sqlite3OsCloseFree(pMaster);
59156 sqlite3OsDelete(pVfs, zMaster, 0);
59157 sqlite3DbFree(db, zMaster);
59158 return rc;
59161 /* Sync all the db files involved in the transaction. The same call
59162 ** sets the master journal pointer in each individual journal. If
59163 ** an error occurs here, do not delete the master journal file.
59165 ** If the error occurs during the first call to
59166 ** sqlite3BtreeCommitPhaseOne(), then there is a chance that the
59167 ** master journal file will be orphaned. But we cannot delete it,
59168 ** in case the master journal file name was written into the journal
59169 ** file before the failure occurred.
59171 for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
59172 Btree *pBt = db->aDb[i].pBt;
59173 if( pBt ){
59174 rc = sqlite3BtreeCommitPhaseOne(pBt, zMaster);
59177 sqlite3OsCloseFree(pMaster);
59178 assert( rc!=SQLITE_BUSY );
59179 if( rc!=SQLITE_OK ){
59180 sqlite3DbFree(db, zMaster);
59181 return rc;
59184 /* Delete the master journal file. This commits the transaction. After
59185 ** doing this the directory is synced again before any individual
59186 ** transaction files are deleted.
59188 rc = sqlite3OsDelete(pVfs, zMaster, 1);
59189 sqlite3DbFree(db, zMaster);
59190 zMaster = 0;
59191 if( rc ){
59192 return rc;
59195 /* All files and directories have already been synced, so the following
59196 ** calls to sqlite3BtreeCommitPhaseTwo() are only closing files and
59197 ** deleting or truncating journals. If something goes wrong while
59198 ** this is happening we don't really care. The integrity of the
59199 ** transaction is already guaranteed, but some stray 'cold' journals
59200 ** may be lying around. Returning an error code won't help matters.
59202 disable_simulated_io_errors();
59203 sqlite3BeginBenignMalloc();
59204 for(i=0; i<db->nDb; i++){
59205 Btree *pBt = db->aDb[i].pBt;
59206 if( pBt ){
59207 sqlite3BtreeCommitPhaseTwo(pBt, 1);
59210 sqlite3EndBenignMalloc();
59211 enable_simulated_io_errors();
59213 sqlite3VtabCommit(db);
59215 #endif
59217 return rc;
59221 ** This routine checks that the sqlite3.activeVdbeCnt count variable
59222 ** matches the number of vdbe's in the list sqlite3.pVdbe that are
59223 ** currently active. An assertion fails if the two counts do not match.
59224 ** This is an internal self-check only - it is not an essential processing
59225 ** step.
59227 ** This is a no-op if NDEBUG is defined.
59229 #ifndef NDEBUG
59230 static void checkActiveVdbeCnt(sqlite3 *db){
59231 Vdbe *p;
59232 int cnt = 0;
59233 int nWrite = 0;
59234 p = db->pVdbe;
59235 while( p ){
59236 if( p->magic==VDBE_MAGIC_RUN && p->pc>=0 ){
59237 cnt++;
59238 if( p->readOnly==0 ) nWrite++;
59240 p = p->pNext;
59242 assert( cnt==db->activeVdbeCnt );
59243 assert( nWrite==db->writeVdbeCnt );
59245 #else
59246 #define checkActiveVdbeCnt(x)
59247 #endif
59250 ** For every Btree that in database connection db which
59251 ** has been modified, "trip" or invalidate each cursor in
59252 ** that Btree might have been modified so that the cursor
59253 ** can never be used again. This happens when a rollback
59254 *** occurs. We have to trip all the other cursors, even
59255 ** cursor from other VMs in different database connections,
59256 ** so that none of them try to use the data at which they
59257 ** were pointing and which now may have been changed due
59258 ** to the rollback.
59260 ** Remember that a rollback can delete tables complete and
59261 ** reorder rootpages. So it is not sufficient just to save
59262 ** the state of the cursor. We have to invalidate the cursor
59263 ** so that it is never used again.
59265 static void invalidateCursorsOnModifiedBtrees(sqlite3 *db){
59266 int i;
59267 for(i=0; i<db->nDb; i++){
59268 Btree *p = db->aDb[i].pBt;
59269 if( p && sqlite3BtreeIsInTrans(p) ){
59270 sqlite3BtreeTripAllCursors(p, SQLITE_ABORT);
59276 ** If the Vdbe passed as the first argument opened a statement-transaction,
59277 ** close it now. Argument eOp must be either SAVEPOINT_ROLLBACK or
59278 ** SAVEPOINT_RELEASE. If it is SAVEPOINT_ROLLBACK, then the statement
59279 ** transaction is rolled back. If eOp is SAVEPOINT_RELEASE, then the
59280 ** statement transaction is commtted.
59282 ** If an IO error occurs, an SQLITE_IOERR_XXX error code is returned.
59283 ** Otherwise SQLITE_OK.
59285 SQLITE_PRIVATE int sqlite3VdbeCloseStatement(Vdbe *p, int eOp){
59286 sqlite3 *const db = p->db;
59287 int rc = SQLITE_OK;
59289 /* If p->iStatement is greater than zero, then this Vdbe opened a
59290 ** statement transaction that should be closed here. The only exception
59291 ** is that an IO error may have occured, causing an emergency rollback.
59292 ** In this case (db->nStatement==0), and there is nothing to do.
59294 if( db->nStatement && p->iStatement ){
59295 int i;
59296 const int iSavepoint = p->iStatement-1;
59298 assert( eOp==SAVEPOINT_ROLLBACK || eOp==SAVEPOINT_RELEASE);
59299 assert( db->nStatement>0 );
59300 assert( p->iStatement==(db->nStatement+db->nSavepoint) );
59302 for(i=0; i<db->nDb; i++){
59303 int rc2 = SQLITE_OK;
59304 Btree *pBt = db->aDb[i].pBt;
59305 if( pBt ){
59306 if( eOp==SAVEPOINT_ROLLBACK ){
59307 rc2 = sqlite3BtreeSavepoint(pBt, SAVEPOINT_ROLLBACK, iSavepoint);
59309 if( rc2==SQLITE_OK ){
59310 rc2 = sqlite3BtreeSavepoint(pBt, SAVEPOINT_RELEASE, iSavepoint);
59312 if( rc==SQLITE_OK ){
59313 rc = rc2;
59317 db->nStatement--;
59318 p->iStatement = 0;
59320 /* If the statement transaction is being rolled back, also restore the
59321 ** database handles deferred constraint counter to the value it had when
59322 ** the statement transaction was opened. */
59323 if( eOp==SAVEPOINT_ROLLBACK ){
59324 db->nDeferredCons = p->nStmtDefCons;
59327 return rc;
59331 ** This function is called when a transaction opened by the database
59332 ** handle associated with the VM passed as an argument is about to be
59333 ** committed. If there are outstanding deferred foreign key constraint
59334 ** violations, return SQLITE_ERROR. Otherwise, SQLITE_OK.
59336 ** If there are outstanding FK violations and this function returns
59337 ** SQLITE_ERROR, set the result of the VM to SQLITE_CONSTRAINT and write
59338 ** an error message to it. Then return SQLITE_ERROR.
59340 #ifndef SQLITE_OMIT_FOREIGN_KEY
59341 SQLITE_PRIVATE int sqlite3VdbeCheckFk(Vdbe *p, int deferred){
59342 sqlite3 *db = p->db;
59343 if( (deferred && db->nDeferredCons>0) || (!deferred && p->nFkConstraint>0) ){
59344 p->rc = SQLITE_CONSTRAINT;
59345 p->errorAction = OE_Abort;
59346 sqlite3SetString(&p->zErrMsg, db, "foreign key constraint failed");
59347 return SQLITE_ERROR;
59349 return SQLITE_OK;
59351 #endif
59354 ** This routine is called the when a VDBE tries to halt. If the VDBE
59355 ** has made changes and is in autocommit mode, then commit those
59356 ** changes. If a rollback is needed, then do the rollback.
59358 ** This routine is the only way to move the state of a VM from
59359 ** SQLITE_MAGIC_RUN to SQLITE_MAGIC_HALT. It is harmless to
59360 ** call this on a VM that is in the SQLITE_MAGIC_HALT state.
59362 ** Return an error code. If the commit could not complete because of
59363 ** lock contention, return SQLITE_BUSY. If SQLITE_BUSY is returned, it
59364 ** means the close did not happen and needs to be repeated.
59366 SQLITE_PRIVATE int sqlite3VdbeHalt(Vdbe *p){
59367 int rc; /* Used to store transient return codes */
59368 sqlite3 *db = p->db;
59370 /* This function contains the logic that determines if a statement or
59371 ** transaction will be committed or rolled back as a result of the
59372 ** execution of this virtual machine.
59374 ** If any of the following errors occur:
59376 ** SQLITE_NOMEM
59377 ** SQLITE_IOERR
59378 ** SQLITE_FULL
59379 ** SQLITE_INTERRUPT
59381 ** Then the internal cache might have been left in an inconsistent
59382 ** state. We need to rollback the statement transaction, if there is
59383 ** one, or the complete transaction if there is no statement transaction.
59386 if( p->db->mallocFailed ){
59387 p->rc = SQLITE_NOMEM;
59389 closeAllCursors(p);
59390 if( p->magic!=VDBE_MAGIC_RUN ){
59391 return SQLITE_OK;
59393 checkActiveVdbeCnt(db);
59395 /* No commit or rollback needed if the program never started */
59396 if( p->pc>=0 ){
59397 int mrc; /* Primary error code from p->rc */
59398 int eStatementOp = 0;
59399 int isSpecialError; /* Set to true if a 'special' error */
59401 /* Lock all btrees used by the statement */
59402 sqlite3VdbeEnter(p);
59404 /* Check for one of the special errors */
59405 mrc = p->rc & 0xff;
59406 assert( p->rc!=SQLITE_IOERR_BLOCKED ); /* This error no longer exists */
59407 isSpecialError = mrc==SQLITE_NOMEM || mrc==SQLITE_IOERR
59408 || mrc==SQLITE_INTERRUPT || mrc==SQLITE_FULL;
59409 if( isSpecialError ){
59410 /* If the query was read-only and the error code is SQLITE_INTERRUPT,
59411 ** no rollback is necessary. Otherwise, at least a savepoint
59412 ** transaction must be rolled back to restore the database to a
59413 ** consistent state.
59415 ** Even if the statement is read-only, it is important to perform
59416 ** a statement or transaction rollback operation. If the error
59417 ** occured while writing to the journal, sub-journal or database
59418 ** file as part of an effort to free up cache space (see function
59419 ** pagerStress() in pager.c), the rollback is required to restore
59420 ** the pager to a consistent state.
59422 if( !p->readOnly || mrc!=SQLITE_INTERRUPT ){
59423 if( (mrc==SQLITE_NOMEM || mrc==SQLITE_FULL) && p->usesStmtJournal ){
59424 eStatementOp = SAVEPOINT_ROLLBACK;
59425 }else{
59426 /* We are forced to roll back the active transaction. Before doing
59427 ** so, abort any other statements this handle currently has active.
59429 invalidateCursorsOnModifiedBtrees(db);
59430 sqlite3RollbackAll(db);
59431 sqlite3CloseSavepoints(db);
59432 db->autoCommit = 1;
59437 /* Check for immediate foreign key violations. */
59438 if( p->rc==SQLITE_OK ){
59439 sqlite3VdbeCheckFk(p, 0);
59442 /* If the auto-commit flag is set and this is the only active writer
59443 ** VM, then we do either a commit or rollback of the current transaction.
59445 ** Note: This block also runs if one of the special errors handled
59446 ** above has occurred.
59448 if( !sqlite3VtabInSync(db)
59449 && db->autoCommit
59450 && db->writeVdbeCnt==(p->readOnly==0)
59452 if( p->rc==SQLITE_OK || (p->errorAction==OE_Fail && !isSpecialError) ){
59453 rc = sqlite3VdbeCheckFk(p, 1);
59454 if( rc!=SQLITE_OK ){
59455 if( NEVER(p->readOnly) ){
59456 sqlite3VdbeLeave(p);
59457 return SQLITE_ERROR;
59459 rc = SQLITE_CONSTRAINT;
59460 }else{
59461 /* The auto-commit flag is true, the vdbe program was successful
59462 ** or hit an 'OR FAIL' constraint and there are no deferred foreign
59463 ** key constraints to hold up the transaction. This means a commit
59464 ** is required. */
59465 rc = vdbeCommit(db, p);
59467 if( rc==SQLITE_BUSY && p->readOnly ){
59468 sqlite3VdbeLeave(p);
59469 return SQLITE_BUSY;
59470 }else if( rc!=SQLITE_OK ){
59471 p->rc = rc;
59472 sqlite3RollbackAll(db);
59473 }else{
59474 db->nDeferredCons = 0;
59475 sqlite3CommitInternalChanges(db);
59477 }else{
59478 sqlite3RollbackAll(db);
59480 db->nStatement = 0;
59481 }else if( eStatementOp==0 ){
59482 if( p->rc==SQLITE_OK || p->errorAction==OE_Fail ){
59483 eStatementOp = SAVEPOINT_RELEASE;
59484 }else if( p->errorAction==OE_Abort ){
59485 eStatementOp = SAVEPOINT_ROLLBACK;
59486 }else{
59487 invalidateCursorsOnModifiedBtrees(db);
59488 sqlite3RollbackAll(db);
59489 sqlite3CloseSavepoints(db);
59490 db->autoCommit = 1;
59494 /* If eStatementOp is non-zero, then a statement transaction needs to
59495 ** be committed or rolled back. Call sqlite3VdbeCloseStatement() to
59496 ** do so. If this operation returns an error, and the current statement
59497 ** error code is SQLITE_OK or SQLITE_CONSTRAINT, then promote the
59498 ** current statement error code.
59500 ** Note that sqlite3VdbeCloseStatement() can only fail if eStatementOp
59501 ** is SAVEPOINT_ROLLBACK. But if p->rc==SQLITE_OK then eStatementOp
59502 ** must be SAVEPOINT_RELEASE. Hence the NEVER(p->rc==SQLITE_OK) in
59503 ** the following code.
59505 if( eStatementOp ){
59506 rc = sqlite3VdbeCloseStatement(p, eStatementOp);
59507 if( rc ){
59508 assert( eStatementOp==SAVEPOINT_ROLLBACK );
59509 if( NEVER(p->rc==SQLITE_OK) || p->rc==SQLITE_CONSTRAINT ){
59510 p->rc = rc;
59511 sqlite3DbFree(db, p->zErrMsg);
59512 p->zErrMsg = 0;
59514 invalidateCursorsOnModifiedBtrees(db);
59515 sqlite3RollbackAll(db);
59516 sqlite3CloseSavepoints(db);
59517 db->autoCommit = 1;
59521 /* If this was an INSERT, UPDATE or DELETE and no statement transaction
59522 ** has been rolled back, update the database connection change-counter.
59524 if( p->changeCntOn ){
59525 if( eStatementOp!=SAVEPOINT_ROLLBACK ){
59526 sqlite3VdbeSetChanges(db, p->nChange);
59527 }else{
59528 sqlite3VdbeSetChanges(db, 0);
59530 p->nChange = 0;
59533 /* Rollback or commit any schema changes that occurred. */
59534 if( p->rc!=SQLITE_OK && db->flags&SQLITE_InternChanges ){
59535 sqlite3ResetInternalSchema(db, -1);
59536 db->flags = (db->flags | SQLITE_InternChanges);
59539 /* Release the locks */
59540 sqlite3VdbeLeave(p);
59543 /* We have successfully halted and closed the VM. Record this fact. */
59544 if( p->pc>=0 ){
59545 db->activeVdbeCnt--;
59546 if( !p->readOnly ){
59547 db->writeVdbeCnt--;
59549 assert( db->activeVdbeCnt>=db->writeVdbeCnt );
59551 p->magic = VDBE_MAGIC_HALT;
59552 checkActiveVdbeCnt(db);
59553 if( p->db->mallocFailed ){
59554 p->rc = SQLITE_NOMEM;
59557 /* If the auto-commit flag is set to true, then any locks that were held
59558 ** by connection db have now been released. Call sqlite3ConnectionUnlocked()
59559 ** to invoke any required unlock-notify callbacks.
59561 if( db->autoCommit ){
59562 sqlite3ConnectionUnlocked(db);
59565 assert( db->activeVdbeCnt>0 || db->autoCommit==0 || db->nStatement==0 );
59566 return (p->rc==SQLITE_BUSY ? SQLITE_BUSY : SQLITE_OK);
59571 ** Each VDBE holds the result of the most recent sqlite3_step() call
59572 ** in p->rc. This routine sets that result back to SQLITE_OK.
59574 SQLITE_PRIVATE void sqlite3VdbeResetStepResult(Vdbe *p){
59575 p->rc = SQLITE_OK;
59579 ** Clean up a VDBE after execution but do not delete the VDBE just yet.
59580 ** Write any error messages into *pzErrMsg. Return the result code.
59582 ** After this routine is run, the VDBE should be ready to be executed
59583 ** again.
59585 ** To look at it another way, this routine resets the state of the
59586 ** virtual machine from VDBE_MAGIC_RUN or VDBE_MAGIC_HALT back to
59587 ** VDBE_MAGIC_INIT.
59589 SQLITE_PRIVATE int sqlite3VdbeReset(Vdbe *p){
59590 sqlite3 *db;
59591 db = p->db;
59593 /* If the VM did not run to completion or if it encountered an
59594 ** error, then it might not have been halted properly. So halt
59595 ** it now.
59597 sqlite3VdbeHalt(p);
59599 /* If the VDBE has be run even partially, then transfer the error code
59600 ** and error message from the VDBE into the main database structure. But
59601 ** if the VDBE has just been set to run but has not actually executed any
59602 ** instructions yet, leave the main database error information unchanged.
59604 if( p->pc>=0 ){
59605 if( p->zErrMsg ){
59606 sqlite3BeginBenignMalloc();
59607 sqlite3ValueSetStr(db->pErr,-1,p->zErrMsg,SQLITE_UTF8,SQLITE_TRANSIENT);
59608 sqlite3EndBenignMalloc();
59609 db->errCode = p->rc;
59610 sqlite3DbFree(db, p->zErrMsg);
59611 p->zErrMsg = 0;
59612 }else if( p->rc ){
59613 sqlite3Error(db, p->rc, 0);
59614 }else{
59615 sqlite3Error(db, SQLITE_OK, 0);
59617 if( p->runOnlyOnce ) p->expired = 1;
59618 }else if( p->rc && p->expired ){
59619 /* The expired flag was set on the VDBE before the first call
59620 ** to sqlite3_step(). For consistency (since sqlite3_step() was
59621 ** called), set the database error in this case as well.
59623 sqlite3Error(db, p->rc, 0);
59624 sqlite3ValueSetStr(db->pErr, -1, p->zErrMsg, SQLITE_UTF8, SQLITE_TRANSIENT);
59625 sqlite3DbFree(db, p->zErrMsg);
59626 p->zErrMsg = 0;
59629 /* Reclaim all memory used by the VDBE
59631 Cleanup(p);
59633 /* Save profiling information from this VDBE run.
59635 #ifdef VDBE_PROFILE
59637 FILE *out = fopen("vdbe_profile.out", "a");
59638 if( out ){
59639 int i;
59640 fprintf(out, "---- ");
59641 for(i=0; i<p->nOp; i++){
59642 fprintf(out, "%02x", p->aOp[i].opcode);
59644 fprintf(out, "\n");
59645 for(i=0; i<p->nOp; i++){
59646 fprintf(out, "%6d %10lld %8lld ",
59647 p->aOp[i].cnt,
59648 p->aOp[i].cycles,
59649 p->aOp[i].cnt>0 ? p->aOp[i].cycles/p->aOp[i].cnt : 0
59651 sqlite3VdbePrintOp(out, i, &p->aOp[i]);
59653 fclose(out);
59656 #endif
59657 p->magic = VDBE_MAGIC_INIT;
59658 return p->rc & db->errMask;
59662 ** Clean up and delete a VDBE after execution. Return an integer which is
59663 ** the result code. Write any error message text into *pzErrMsg.
59665 SQLITE_PRIVATE int sqlite3VdbeFinalize(Vdbe *p){
59666 int rc = SQLITE_OK;
59667 if( p->magic==VDBE_MAGIC_RUN || p->magic==VDBE_MAGIC_HALT ){
59668 rc = sqlite3VdbeReset(p);
59669 assert( (rc & p->db->errMask)==rc );
59671 sqlite3VdbeDelete(p);
59672 return rc;
59676 ** Call the destructor for each auxdata entry in pVdbeFunc for which
59677 ** the corresponding bit in mask is clear. Auxdata entries beyond 31
59678 ** are always destroyed. To destroy all auxdata entries, call this
59679 ** routine with mask==0.
59681 SQLITE_PRIVATE void sqlite3VdbeDeleteAuxData(VdbeFunc *pVdbeFunc, int mask){
59682 int i;
59683 for(i=0; i<pVdbeFunc->nAux; i++){
59684 struct AuxData *pAux = &pVdbeFunc->apAux[i];
59685 if( (i>31 || !(mask&(((u32)1)<<i))) && pAux->pAux ){
59686 if( pAux->xDelete ){
59687 pAux->xDelete(pAux->pAux);
59689 pAux->pAux = 0;
59695 ** Free all memory associated with the Vdbe passed as the second argument.
59696 ** The difference between this function and sqlite3VdbeDelete() is that
59697 ** VdbeDelete() also unlinks the Vdbe from the list of VMs associated with
59698 ** the database connection.
59700 SQLITE_PRIVATE void sqlite3VdbeDeleteObject(sqlite3 *db, Vdbe *p){
59701 SubProgram *pSub, *pNext;
59702 assert( p->db==0 || p->db==db );
59703 releaseMemArray(p->aVar, p->nVar);
59704 releaseMemArray(p->aColName, p->nResColumn*COLNAME_N);
59705 for(pSub=p->pProgram; pSub; pSub=pNext){
59706 pNext = pSub->pNext;
59707 vdbeFreeOpArray(db, pSub->aOp, pSub->nOp);
59708 sqlite3DbFree(db, pSub);
59710 vdbeFreeOpArray(db, p->aOp, p->nOp);
59711 sqlite3DbFree(db, p->aLabel);
59712 sqlite3DbFree(db, p->aColName);
59713 sqlite3DbFree(db, p->zSql);
59714 sqlite3DbFree(db, p->pFree);
59715 sqlite3DbFree(db, p);
59719 ** Delete an entire VDBE.
59721 SQLITE_PRIVATE void sqlite3VdbeDelete(Vdbe *p){
59722 sqlite3 *db;
59724 if( NEVER(p==0) ) return;
59725 db = p->db;
59726 if( p->pPrev ){
59727 p->pPrev->pNext = p->pNext;
59728 }else{
59729 assert( db->pVdbe==p );
59730 db->pVdbe = p->pNext;
59732 if( p->pNext ){
59733 p->pNext->pPrev = p->pPrev;
59735 p->magic = VDBE_MAGIC_DEAD;
59736 p->db = 0;
59737 sqlite3VdbeDeleteObject(db, p);
59741 ** Make sure the cursor p is ready to read or write the row to which it
59742 ** was last positioned. Return an error code if an OOM fault or I/O error
59743 ** prevents us from positioning the cursor to its correct position.
59745 ** If a MoveTo operation is pending on the given cursor, then do that
59746 ** MoveTo now. If no move is pending, check to see if the row has been
59747 ** deleted out from under the cursor and if it has, mark the row as
59748 ** a NULL row.
59750 ** If the cursor is already pointing to the correct row and that row has
59751 ** not been deleted out from under the cursor, then this routine is a no-op.
59753 SQLITE_PRIVATE int sqlite3VdbeCursorMoveto(VdbeCursor *p){
59754 if( p->deferredMoveto ){
59755 int res, rc;
59756 #ifdef SQLITE_TEST
59757 extern int sqlite3_search_count;
59758 #endif
59759 assert( p->isTable );
59760 rc = sqlite3BtreeMovetoUnpacked(p->pCursor, 0, p->movetoTarget, 0, &res);
59761 if( rc ) return rc;
59762 p->lastRowid = p->movetoTarget;
59763 if( res!=0 ) return SQLITE_CORRUPT_BKPT;
59764 p->rowidIsValid = 1;
59765 #ifdef SQLITE_TEST
59766 sqlite3_search_count++;
59767 #endif
59768 p->deferredMoveto = 0;
59769 p->cacheStatus = CACHE_STALE;
59770 }else if( ALWAYS(p->pCursor) ){
59771 int hasMoved;
59772 int rc = sqlite3BtreeCursorHasMoved(p->pCursor, &hasMoved);
59773 if( rc ) return rc;
59774 if( hasMoved ){
59775 p->cacheStatus = CACHE_STALE;
59776 p->nullRow = 1;
59779 return SQLITE_OK;
59783 ** The following functions:
59785 ** sqlite3VdbeSerialType()
59786 ** sqlite3VdbeSerialTypeLen()
59787 ** sqlite3VdbeSerialLen()
59788 ** sqlite3VdbeSerialPut()
59789 ** sqlite3VdbeSerialGet()
59791 ** encapsulate the code that serializes values for storage in SQLite
59792 ** data and index records. Each serialized value consists of a
59793 ** 'serial-type' and a blob of data. The serial type is an 8-byte unsigned
59794 ** integer, stored as a varint.
59796 ** In an SQLite index record, the serial type is stored directly before
59797 ** the blob of data that it corresponds to. In a table record, all serial
59798 ** types are stored at the start of the record, and the blobs of data at
59799 ** the end. Hence these functions allow the caller to handle the
59800 ** serial-type and data blob seperately.
59802 ** The following table describes the various storage classes for data:
59804 ** serial type bytes of data type
59805 ** -------------- --------------- ---------------
59806 ** 0 0 NULL
59807 ** 1 1 signed integer
59808 ** 2 2 signed integer
59809 ** 3 3 signed integer
59810 ** 4 4 signed integer
59811 ** 5 6 signed integer
59812 ** 6 8 signed integer
59813 ** 7 8 IEEE float
59814 ** 8 0 Integer constant 0
59815 ** 9 0 Integer constant 1
59816 ** 10,11 reserved for expansion
59817 ** N>=12 and even (N-12)/2 BLOB
59818 ** N>=13 and odd (N-13)/2 text
59820 ** The 8 and 9 types were added in 3.3.0, file format 4. Prior versions
59821 ** of SQLite will not understand those serial types.
59825 ** Return the serial-type for the value stored in pMem.
59827 SQLITE_PRIVATE u32 sqlite3VdbeSerialType(Mem *pMem, int file_format){
59828 int flags = pMem->flags;
59829 int n;
59831 if( flags&MEM_Null ){
59832 return 0;
59834 if( flags&MEM_Int ){
59835 /* Figure out whether to use 1, 2, 4, 6 or 8 bytes. */
59836 # define MAX_6BYTE ((((i64)0x00008000)<<32)-1)
59837 i64 i = pMem->u.i;
59838 u64 u;
59839 if( file_format>=4 && (i&1)==i ){
59840 return 8+(u32)i;
59842 if( i<0 ){
59843 if( i<(-MAX_6BYTE) ) return 6;
59844 /* Previous test prevents: u = -(-9223372036854775808) */
59845 u = -i;
59846 }else{
59847 u = i;
59849 if( u<=127 ) return 1;
59850 if( u<=32767 ) return 2;
59851 if( u<=8388607 ) return 3;
59852 if( u<=2147483647 ) return 4;
59853 if( u<=MAX_6BYTE ) return 5;
59854 return 6;
59856 if( flags&MEM_Real ){
59857 return 7;
59859 assert( pMem->db->mallocFailed || flags&(MEM_Str|MEM_Blob) );
59860 n = pMem->n;
59861 if( flags & MEM_Zero ){
59862 n += pMem->u.nZero;
59864 assert( n>=0 );
59865 return ((n*2) + 12 + ((flags&MEM_Str)!=0));
59869 ** Return the length of the data corresponding to the supplied serial-type.
59871 SQLITE_PRIVATE u32 sqlite3VdbeSerialTypeLen(u32 serial_type){
59872 if( serial_type>=12 ){
59873 return (serial_type-12)/2;
59874 }else{
59875 static const u8 aSize[] = { 0, 1, 2, 3, 4, 6, 8, 8, 0, 0, 0, 0 };
59876 return aSize[serial_type];
59881 ** If we are on an architecture with mixed-endian floating
59882 ** points (ex: ARM7) then swap the lower 4 bytes with the
59883 ** upper 4 bytes. Return the result.
59885 ** For most architectures, this is a no-op.
59887 ** (later): It is reported to me that the mixed-endian problem
59888 ** on ARM7 is an issue with GCC, not with the ARM7 chip. It seems
59889 ** that early versions of GCC stored the two words of a 64-bit
59890 ** float in the wrong order. And that error has been propagated
59891 ** ever since. The blame is not necessarily with GCC, though.
59892 ** GCC might have just copying the problem from a prior compiler.
59893 ** I am also told that newer versions of GCC that follow a different
59894 ** ABI get the byte order right.
59896 ** Developers using SQLite on an ARM7 should compile and run their
59897 ** application using -DSQLITE_DEBUG=1 at least once. With DEBUG
59898 ** enabled, some asserts below will ensure that the byte order of
59899 ** floating point values is correct.
59901 ** (2007-08-30) Frank van Vugt has studied this problem closely
59902 ** and has send his findings to the SQLite developers. Frank
59903 ** writes that some Linux kernels offer floating point hardware
59904 ** emulation that uses only 32-bit mantissas instead of a full
59905 ** 48-bits as required by the IEEE standard. (This is the
59906 ** CONFIG_FPE_FASTFPE option.) On such systems, floating point
59907 ** byte swapping becomes very complicated. To avoid problems,
59908 ** the necessary byte swapping is carried out using a 64-bit integer
59909 ** rather than a 64-bit float. Frank assures us that the code here
59910 ** works for him. We, the developers, have no way to independently
59911 ** verify this, but Frank seems to know what he is talking about
59912 ** so we trust him.
59914 #ifdef SQLITE_MIXED_ENDIAN_64BIT_FLOAT
59915 static u64 floatSwap(u64 in){
59916 union {
59917 u64 r;
59918 u32 i[2];
59919 } u;
59920 u32 t;
59922 u.r = in;
59923 t = u.i[0];
59924 u.i[0] = u.i[1];
59925 u.i[1] = t;
59926 return u.r;
59928 # define swapMixedEndianFloat(X) X = floatSwap(X)
59929 #else
59930 # define swapMixedEndianFloat(X)
59931 #endif
59934 ** Write the serialized data blob for the value stored in pMem into
59935 ** buf. It is assumed that the caller has allocated sufficient space.
59936 ** Return the number of bytes written.
59938 ** nBuf is the amount of space left in buf[]. nBuf must always be
59939 ** large enough to hold the entire field. Except, if the field is
59940 ** a blob with a zero-filled tail, then buf[] might be just the right
59941 ** size to hold everything except for the zero-filled tail. If buf[]
59942 ** is only big enough to hold the non-zero prefix, then only write that
59943 ** prefix into buf[]. But if buf[] is large enough to hold both the
59944 ** prefix and the tail then write the prefix and set the tail to all
59945 ** zeros.
59947 ** Return the number of bytes actually written into buf[]. The number
59948 ** of bytes in the zero-filled tail is included in the return value only
59949 ** if those bytes were zeroed in buf[].
59951 SQLITE_PRIVATE u32 sqlite3VdbeSerialPut(u8 *buf, int nBuf, Mem *pMem, int file_format){
59952 u32 serial_type = sqlite3VdbeSerialType(pMem, file_format);
59953 u32 len;
59955 /* Integer and Real */
59956 if( serial_type<=7 && serial_type>0 ){
59957 u64 v;
59958 u32 i;
59959 if( serial_type==7 ){
59960 assert( sizeof(v)==sizeof(pMem->r) );
59961 memcpy(&v, &pMem->r, sizeof(v));
59962 swapMixedEndianFloat(v);
59963 }else{
59964 v = pMem->u.i;
59966 len = i = sqlite3VdbeSerialTypeLen(serial_type);
59967 assert( len<=(u32)nBuf );
59968 while( i-- ){
59969 buf[i] = (u8)(v&0xFF);
59970 v >>= 8;
59972 return len;
59975 /* String or blob */
59976 if( serial_type>=12 ){
59977 assert( pMem->n + ((pMem->flags & MEM_Zero)?pMem->u.nZero:0)
59978 == (int)sqlite3VdbeSerialTypeLen(serial_type) );
59979 assert( pMem->n<=nBuf );
59980 len = pMem->n;
59981 memcpy(buf, pMem->z, len);
59982 if( pMem->flags & MEM_Zero ){
59983 len += pMem->u.nZero;
59984 assert( nBuf>=0 );
59985 if( len > (u32)nBuf ){
59986 len = (u32)nBuf;
59988 memset(&buf[pMem->n], 0, len-pMem->n);
59990 return len;
59993 /* NULL or constants 0 or 1 */
59994 return 0;
59998 ** Deserialize the data blob pointed to by buf as serial type serial_type
59999 ** and store the result in pMem. Return the number of bytes read.
60001 SQLITE_PRIVATE u32 sqlite3VdbeSerialGet(
60002 const unsigned char *buf, /* Buffer to deserialize from */
60003 u32 serial_type, /* Serial type to deserialize */
60004 Mem *pMem /* Memory cell to write value into */
60006 switch( serial_type ){
60007 case 10: /* Reserved for future use */
60008 case 11: /* Reserved for future use */
60009 case 0: { /* NULL */
60010 pMem->flags = MEM_Null;
60011 break;
60013 case 1: { /* 1-byte signed integer */
60014 pMem->u.i = (signed char)buf[0];
60015 pMem->flags = MEM_Int;
60016 return 1;
60018 case 2: { /* 2-byte signed integer */
60019 pMem->u.i = (((signed char)buf[0])<<8) | buf[1];
60020 pMem->flags = MEM_Int;
60021 return 2;
60023 case 3: { /* 3-byte signed integer */
60024 pMem->u.i = (((signed char)buf[0])<<16) | (buf[1]<<8) | buf[2];
60025 pMem->flags = MEM_Int;
60026 return 3;
60028 case 4: { /* 4-byte signed integer */
60029 pMem->u.i = (buf[0]<<24) | (buf[1]<<16) | (buf[2]<<8) | buf[3];
60030 pMem->flags = MEM_Int;
60031 return 4;
60033 case 5: { /* 6-byte signed integer */
60034 u64 x = (((signed char)buf[0])<<8) | buf[1];
60035 u32 y = (buf[2]<<24) | (buf[3]<<16) | (buf[4]<<8) | buf[5];
60036 x = (x<<32) | y;
60037 pMem->u.i = *(i64*)&x;
60038 pMem->flags = MEM_Int;
60039 return 6;
60041 case 6: /* 8-byte signed integer */
60042 case 7: { /* IEEE floating point */
60043 u64 x;
60044 u32 y;
60045 #if !defined(NDEBUG) && !defined(SQLITE_OMIT_FLOATING_POINT)
60046 /* Verify that integers and floating point values use the same
60047 ** byte order. Or, that if SQLITE_MIXED_ENDIAN_64BIT_FLOAT is
60048 ** defined that 64-bit floating point values really are mixed
60049 ** endian.
60051 static const u64 t1 = ((u64)0x3ff00000)<<32;
60052 static const double r1 = 1.0;
60053 u64 t2 = t1;
60054 swapMixedEndianFloat(t2);
60055 assert( sizeof(r1)==sizeof(t2) && memcmp(&r1, &t2, sizeof(r1))==0 );
60056 #endif
60058 x = (buf[0]<<24) | (buf[1]<<16) | (buf[2]<<8) | buf[3];
60059 y = (buf[4]<<24) | (buf[5]<<16) | (buf[6]<<8) | buf[7];
60060 x = (x<<32) | y;
60061 if( serial_type==6 ){
60062 pMem->u.i = *(i64*)&x;
60063 pMem->flags = MEM_Int;
60064 }else{
60065 assert( sizeof(x)==8 && sizeof(pMem->r)==8 );
60066 swapMixedEndianFloat(x);
60067 memcpy(&pMem->r, &x, sizeof(x));
60068 pMem->flags = sqlite3IsNaN(pMem->r) ? MEM_Null : MEM_Real;
60070 return 8;
60072 case 8: /* Integer 0 */
60073 case 9: { /* Integer 1 */
60074 pMem->u.i = serial_type-8;
60075 pMem->flags = MEM_Int;
60076 return 0;
60078 default: {
60079 u32 len = (serial_type-12)/2;
60080 pMem->z = (char *)buf;
60081 pMem->n = len;
60082 pMem->xDel = 0;
60083 if( serial_type&0x01 ){
60084 pMem->flags = MEM_Str | MEM_Ephem;
60085 }else{
60086 pMem->flags = MEM_Blob | MEM_Ephem;
60088 return len;
60091 return 0;
60096 ** Given the nKey-byte encoding of a record in pKey[], parse the
60097 ** record into a UnpackedRecord structure. Return a pointer to
60098 ** that structure.
60100 ** The calling function might provide szSpace bytes of memory
60101 ** space at pSpace. This space can be used to hold the returned
60102 ** VDbeParsedRecord structure if it is large enough. If it is
60103 ** not big enough, space is obtained from sqlite3_malloc().
60105 ** The returned structure should be closed by a call to
60106 ** sqlite3VdbeDeleteUnpackedRecord().
60108 SQLITE_PRIVATE UnpackedRecord *sqlite3VdbeRecordUnpack(
60109 KeyInfo *pKeyInfo, /* Information about the record format */
60110 int nKey, /* Size of the binary record */
60111 const void *pKey, /* The binary record */
60112 char *pSpace, /* Unaligned space available to hold the object */
60113 int szSpace /* Size of pSpace[] in bytes */
60115 const unsigned char *aKey = (const unsigned char *)pKey;
60116 UnpackedRecord *p; /* The unpacked record that we will return */
60117 int nByte; /* Memory space needed to hold p, in bytes */
60118 int d;
60119 u32 idx;
60120 u16 u; /* Unsigned loop counter */
60121 u32 szHdr;
60122 Mem *pMem;
60123 int nOff; /* Increase pSpace by this much to 8-byte align it */
60126 ** We want to shift the pointer pSpace up such that it is 8-byte aligned.
60127 ** Thus, we need to calculate a value, nOff, between 0 and 7, to shift
60128 ** it by. If pSpace is already 8-byte aligned, nOff should be zero.
60130 nOff = (8 - (SQLITE_PTR_TO_INT(pSpace) & 7)) & 7;
60131 pSpace += nOff;
60132 szSpace -= nOff;
60133 nByte = ROUND8(sizeof(UnpackedRecord)) + sizeof(Mem)*(pKeyInfo->nField+1);
60134 if( nByte>szSpace ){
60135 p = sqlite3DbMallocRaw(pKeyInfo->db, nByte);
60136 if( p==0 ) return 0;
60137 p->flags = UNPACKED_NEED_FREE | UNPACKED_NEED_DESTROY;
60138 }else{
60139 p = (UnpackedRecord*)pSpace;
60140 p->flags = UNPACKED_NEED_DESTROY;
60142 p->pKeyInfo = pKeyInfo;
60143 p->nField = pKeyInfo->nField + 1;
60144 p->aMem = pMem = (Mem*)&((char*)p)[ROUND8(sizeof(UnpackedRecord))];
60145 assert( EIGHT_BYTE_ALIGNMENT(pMem) );
60146 idx = getVarint32(aKey, szHdr);
60147 d = szHdr;
60148 u = 0;
60149 while( idx<szHdr && u<p->nField && d<=nKey ){
60150 u32 serial_type;
60152 idx += getVarint32(&aKey[idx], serial_type);
60153 pMem->enc = pKeyInfo->enc;
60154 pMem->db = pKeyInfo->db;
60155 pMem->flags = 0;
60156 pMem->zMalloc = 0;
60157 d += sqlite3VdbeSerialGet(&aKey[d], serial_type, pMem);
60158 pMem++;
60159 u++;
60161 assert( u<=pKeyInfo->nField + 1 );
60162 p->nField = u;
60163 return (void*)p;
60167 ** This routine destroys a UnpackedRecord object.
60169 SQLITE_PRIVATE void sqlite3VdbeDeleteUnpackedRecord(UnpackedRecord *p){
60170 int i;
60171 Mem *pMem;
60173 assert( p!=0 );
60174 assert( p->flags & UNPACKED_NEED_DESTROY );
60175 for(i=0, pMem=p->aMem; i<p->nField; i++, pMem++){
60176 /* The unpacked record is always constructed by the
60177 ** sqlite3VdbeUnpackRecord() function above, which makes all
60178 ** strings and blobs static. And none of the elements are
60179 ** ever transformed, so there is never anything to delete.
60181 if( NEVER(pMem->zMalloc) ) sqlite3VdbeMemRelease(pMem);
60183 if( p->flags & UNPACKED_NEED_FREE ){
60184 sqlite3DbFree(p->pKeyInfo->db, p);
60189 ** This function compares the two table rows or index records
60190 ** specified by {nKey1, pKey1} and pPKey2. It returns a negative, zero
60191 ** or positive integer if key1 is less than, equal to or
60192 ** greater than key2. The {nKey1, pKey1} key must be a blob
60193 ** created by th OP_MakeRecord opcode of the VDBE. The pPKey2
60194 ** key must be a parsed key such as obtained from
60195 ** sqlite3VdbeParseRecord.
60197 ** Key1 and Key2 do not have to contain the same number of fields.
60198 ** The key with fewer fields is usually compares less than the
60199 ** longer key. However if the UNPACKED_INCRKEY flags in pPKey2 is set
60200 ** and the common prefixes are equal, then key1 is less than key2.
60201 ** Or if the UNPACKED_MATCH_PREFIX flag is set and the prefixes are
60202 ** equal, then the keys are considered to be equal and
60203 ** the parts beyond the common prefix are ignored.
60205 ** If the UNPACKED_IGNORE_ROWID flag is set, then the last byte of
60206 ** the header of pKey1 is ignored. It is assumed that pKey1 is
60207 ** an index key, and thus ends with a rowid value. The last byte
60208 ** of the header will therefore be the serial type of the rowid:
60209 ** one of 1, 2, 3, 4, 5, 6, 8, or 9 - the integer serial types.
60210 ** The serial type of the final rowid will always be a single byte.
60211 ** By ignoring this last byte of the header, we force the comparison
60212 ** to ignore the rowid at the end of key1.
60214 SQLITE_PRIVATE int sqlite3VdbeRecordCompare(
60215 int nKey1, const void *pKey1, /* Left key */
60216 UnpackedRecord *pPKey2 /* Right key */
60218 int d1; /* Offset into aKey[] of next data element */
60219 u32 idx1; /* Offset into aKey[] of next header element */
60220 u32 szHdr1; /* Number of bytes in header */
60221 int i = 0;
60222 int nField;
60223 int rc = 0;
60224 const unsigned char *aKey1 = (const unsigned char *)pKey1;
60225 KeyInfo *pKeyInfo;
60226 Mem mem1;
60228 pKeyInfo = pPKey2->pKeyInfo;
60229 mem1.enc = pKeyInfo->enc;
60230 mem1.db = pKeyInfo->db;
60231 /* mem1.flags = 0; // Will be initialized by sqlite3VdbeSerialGet() */
60232 VVA_ONLY( mem1.zMalloc = 0; ) /* Only needed by assert() statements */
60234 /* Compilers may complain that mem1.u.i is potentially uninitialized.
60235 ** We could initialize it, as shown here, to silence those complaints.
60236 ** But in fact, mem1.u.i will never actually be used initialized, and doing
60237 ** the unnecessary initialization has a measurable negative performance
60238 ** impact, since this routine is a very high runner. And so, we choose
60239 ** to ignore the compiler warnings and leave this variable uninitialized.
60241 /* mem1.u.i = 0; // not needed, here to silence compiler warning */
60243 idx1 = getVarint32(aKey1, szHdr1);
60244 d1 = szHdr1;
60245 if( pPKey2->flags & UNPACKED_IGNORE_ROWID ){
60246 szHdr1--;
60248 nField = pKeyInfo->nField;
60249 while( idx1<szHdr1 && i<pPKey2->nField ){
60250 u32 serial_type1;
60252 /* Read the serial types for the next element in each key. */
60253 idx1 += getVarint32( aKey1+idx1, serial_type1 );
60254 if( d1>=nKey1 && sqlite3VdbeSerialTypeLen(serial_type1)>0 ) break;
60256 /* Extract the values to be compared.
60258 d1 += sqlite3VdbeSerialGet(&aKey1[d1], serial_type1, &mem1);
60260 /* Do the comparison
60262 rc = sqlite3MemCompare(&mem1, &pPKey2->aMem[i],
60263 i<nField ? pKeyInfo->aColl[i] : 0);
60264 if( rc!=0 ){
60265 assert( mem1.zMalloc==0 ); /* See comment below */
60267 /* Invert the result if we are using DESC sort order. */
60268 if( pKeyInfo->aSortOrder && i<nField && pKeyInfo->aSortOrder[i] ){
60269 rc = -rc;
60272 /* If the PREFIX_SEARCH flag is set and all fields except the final
60273 ** rowid field were equal, then clear the PREFIX_SEARCH flag and set
60274 ** pPKey2->rowid to the value of the rowid field in (pKey1, nKey1).
60275 ** This is used by the OP_IsUnique opcode.
60277 if( (pPKey2->flags & UNPACKED_PREFIX_SEARCH) && i==(pPKey2->nField-1) ){
60278 assert( idx1==szHdr1 && rc );
60279 assert( mem1.flags & MEM_Int );
60280 pPKey2->flags &= ~UNPACKED_PREFIX_SEARCH;
60281 pPKey2->rowid = mem1.u.i;
60284 return rc;
60286 i++;
60289 /* No memory allocation is ever used on mem1. Prove this using
60290 ** the following assert(). If the assert() fails, it indicates a
60291 ** memory leak and a need to call sqlite3VdbeMemRelease(&mem1).
60293 assert( mem1.zMalloc==0 );
60295 /* rc==0 here means that one of the keys ran out of fields and
60296 ** all the fields up to that point were equal. If the UNPACKED_INCRKEY
60297 ** flag is set, then break the tie by treating key2 as larger.
60298 ** If the UPACKED_PREFIX_MATCH flag is set, then keys with common prefixes
60299 ** are considered to be equal. Otherwise, the longer key is the
60300 ** larger. As it happens, the pPKey2 will always be the longer
60301 ** if there is a difference.
60303 assert( rc==0 );
60304 if( pPKey2->flags & UNPACKED_INCRKEY ){
60305 rc = -1;
60306 }else if( pPKey2->flags & UNPACKED_PREFIX_MATCH ){
60307 /* Leave rc==0 */
60308 }else if( idx1<szHdr1 ){
60309 rc = 1;
60311 return rc;
60316 ** pCur points at an index entry created using the OP_MakeRecord opcode.
60317 ** Read the rowid (the last field in the record) and store it in *rowid.
60318 ** Return SQLITE_OK if everything works, or an error code otherwise.
60320 ** pCur might be pointing to text obtained from a corrupt database file.
60321 ** So the content cannot be trusted. Do appropriate checks on the content.
60323 SQLITE_PRIVATE int sqlite3VdbeIdxRowid(sqlite3 *db, BtCursor *pCur, i64 *rowid){
60324 i64 nCellKey = 0;
60325 int rc;
60326 u32 szHdr; /* Size of the header */
60327 u32 typeRowid; /* Serial type of the rowid */
60328 u32 lenRowid; /* Size of the rowid */
60329 Mem m, v;
60331 UNUSED_PARAMETER(db);
60333 /* Get the size of the index entry. Only indices entries of less
60334 ** than 2GiB are support - anything large must be database corruption.
60335 ** Any corruption is detected in sqlite3BtreeParseCellPtr(), though, so
60336 ** this code can safely assume that nCellKey is 32-bits
60338 assert( sqlite3BtreeCursorIsValid(pCur) );
60339 rc = sqlite3BtreeKeySize(pCur, &nCellKey);
60340 assert( rc==SQLITE_OK ); /* pCur is always valid so KeySize cannot fail */
60341 assert( (nCellKey & SQLITE_MAX_U32)==(u64)nCellKey );
60343 /* Read in the complete content of the index entry */
60344 memset(&m, 0, sizeof(m));
60345 rc = sqlite3VdbeMemFromBtree(pCur, 0, (int)nCellKey, 1, &m);
60346 if( rc ){
60347 return rc;
60350 /* The index entry must begin with a header size */
60351 (void)getVarint32((u8*)m.z, szHdr);
60352 testcase( szHdr==3 );
60353 testcase( szHdr==m.n );
60354 if( unlikely(szHdr<3 || (int)szHdr>m.n) ){
60355 goto idx_rowid_corruption;
60358 /* The last field of the index should be an integer - the ROWID.
60359 ** Verify that the last entry really is an integer. */
60360 (void)getVarint32((u8*)&m.z[szHdr-1], typeRowid);
60361 testcase( typeRowid==1 );
60362 testcase( typeRowid==2 );
60363 testcase( typeRowid==3 );
60364 testcase( typeRowid==4 );
60365 testcase( typeRowid==5 );
60366 testcase( typeRowid==6 );
60367 testcase( typeRowid==8 );
60368 testcase( typeRowid==9 );
60369 if( unlikely(typeRowid<1 || typeRowid>9 || typeRowid==7) ){
60370 goto idx_rowid_corruption;
60372 lenRowid = sqlite3VdbeSerialTypeLen(typeRowid);
60373 testcase( (u32)m.n==szHdr+lenRowid );
60374 if( unlikely((u32)m.n<szHdr+lenRowid) ){
60375 goto idx_rowid_corruption;
60378 /* Fetch the integer off the end of the index record */
60379 sqlite3VdbeSerialGet((u8*)&m.z[m.n-lenRowid], typeRowid, &v);
60380 *rowid = v.u.i;
60381 sqlite3VdbeMemRelease(&m);
60382 return SQLITE_OK;
60384 /* Jump here if database corruption is detected after m has been
60385 ** allocated. Free the m object and return SQLITE_CORRUPT. */
60386 idx_rowid_corruption:
60387 testcase( m.zMalloc!=0 );
60388 sqlite3VdbeMemRelease(&m);
60389 return SQLITE_CORRUPT_BKPT;
60393 ** Compare the key of the index entry that cursor pC is pointing to against
60394 ** the key string in pUnpacked. Write into *pRes a number
60395 ** that is negative, zero, or positive if pC is less than, equal to,
60396 ** or greater than pUnpacked. Return SQLITE_OK on success.
60398 ** pUnpacked is either created without a rowid or is truncated so that it
60399 ** omits the rowid at the end. The rowid at the end of the index entry
60400 ** is ignored as well. Hence, this routine only compares the prefixes
60401 ** of the keys prior to the final rowid, not the entire key.
60403 SQLITE_PRIVATE int sqlite3VdbeIdxKeyCompare(
60404 VdbeCursor *pC, /* The cursor to compare against */
60405 UnpackedRecord *pUnpacked, /* Unpacked version of key to compare against */
60406 int *res /* Write the comparison result here */
60408 i64 nCellKey = 0;
60409 int rc;
60410 BtCursor *pCur = pC->pCursor;
60411 Mem m;
60413 assert( sqlite3BtreeCursorIsValid(pCur) );
60414 rc = sqlite3BtreeKeySize(pCur, &nCellKey);
60415 assert( rc==SQLITE_OK ); /* pCur is always valid so KeySize cannot fail */
60416 /* nCellKey will always be between 0 and 0xffffffff because of the say
60417 ** that btreeParseCellPtr() and sqlite3GetVarint32() are implemented */
60418 if( nCellKey<=0 || nCellKey>0x7fffffff ){
60419 *res = 0;
60420 return SQLITE_CORRUPT_BKPT;
60422 memset(&m, 0, sizeof(m));
60423 rc = sqlite3VdbeMemFromBtree(pC->pCursor, 0, (int)nCellKey, 1, &m);
60424 if( rc ){
60425 return rc;
60427 assert( pUnpacked->flags & UNPACKED_IGNORE_ROWID );
60428 *res = sqlite3VdbeRecordCompare(m.n, m.z, pUnpacked);
60429 sqlite3VdbeMemRelease(&m);
60430 return SQLITE_OK;
60434 ** This routine sets the value to be returned by subsequent calls to
60435 ** sqlite3_changes() on the database handle 'db'.
60437 SQLITE_PRIVATE void sqlite3VdbeSetChanges(sqlite3 *db, int nChange){
60438 assert( sqlite3_mutex_held(db->mutex) );
60439 db->nChange = nChange;
60440 db->nTotalChange += nChange;
60444 ** Set a flag in the vdbe to update the change counter when it is finalised
60445 ** or reset.
60447 SQLITE_PRIVATE void sqlite3VdbeCountChanges(Vdbe *v){
60448 v->changeCntOn = 1;
60452 ** Mark every prepared statement associated with a database connection
60453 ** as expired.
60455 ** An expired statement means that recompilation of the statement is
60456 ** recommend. Statements expire when things happen that make their
60457 ** programs obsolete. Removing user-defined functions or collating
60458 ** sequences, or changing an authorization function are the types of
60459 ** things that make prepared statements obsolete.
60461 SQLITE_PRIVATE void sqlite3ExpirePreparedStatements(sqlite3 *db){
60462 Vdbe *p;
60463 for(p = db->pVdbe; p; p=p->pNext){
60464 p->expired = 1;
60469 ** Return the database associated with the Vdbe.
60471 SQLITE_PRIVATE sqlite3 *sqlite3VdbeDb(Vdbe *v){
60472 return v->db;
60476 ** Return a pointer to an sqlite3_value structure containing the value bound
60477 ** parameter iVar of VM v. Except, if the value is an SQL NULL, return
60478 ** 0 instead. Unless it is NULL, apply affinity aff (one of the SQLITE_AFF_*
60479 ** constants) to the value before returning it.
60481 ** The returned value must be freed by the caller using sqlite3ValueFree().
60483 SQLITE_PRIVATE sqlite3_value *sqlite3VdbeGetValue(Vdbe *v, int iVar, u8 aff){
60484 assert( iVar>0 );
60485 if( v ){
60486 Mem *pMem = &v->aVar[iVar-1];
60487 if( 0==(pMem->flags & MEM_Null) ){
60488 sqlite3_value *pRet = sqlite3ValueNew(v->db);
60489 if( pRet ){
60490 sqlite3VdbeMemCopy((Mem *)pRet, pMem);
60491 sqlite3ValueApplyAffinity(pRet, aff, SQLITE_UTF8);
60492 sqlite3VdbeMemStoreType((Mem *)pRet);
60494 return pRet;
60497 return 0;
60501 ** Configure SQL variable iVar so that binding a new value to it signals
60502 ** to sqlite3_reoptimize() that re-preparing the statement may result
60503 ** in a better query plan.
60505 SQLITE_PRIVATE void sqlite3VdbeSetVarmask(Vdbe *v, int iVar){
60506 assert( iVar>0 );
60507 if( iVar>32 ){
60508 v->expmask = 0xffffffff;
60509 }else{
60510 v->expmask |= ((u32)1 << (iVar-1));
60514 /************** End of vdbeaux.c *********************************************/
60515 /************** Begin file vdbeapi.c *****************************************/
60517 ** 2004 May 26
60519 ** The author disclaims copyright to this source code. In place of
60520 ** a legal notice, here is a blessing:
60522 ** May you do good and not evil.
60523 ** May you find forgiveness for yourself and forgive others.
60524 ** May you share freely, never taking more than you give.
60526 *************************************************************************
60528 ** This file contains code use to implement APIs that are part of the
60529 ** VDBE.
60532 #ifndef SQLITE_OMIT_DEPRECATED
60534 ** Return TRUE (non-zero) of the statement supplied as an argument needs
60535 ** to be recompiled. A statement needs to be recompiled whenever the
60536 ** execution environment changes in a way that would alter the program
60537 ** that sqlite3_prepare() generates. For example, if new functions or
60538 ** collating sequences are registered or if an authorizer function is
60539 ** added or changed.
60541 SQLITE_API int sqlite3_expired(sqlite3_stmt *pStmt){
60542 Vdbe *p = (Vdbe*)pStmt;
60543 return p==0 || p->expired;
60545 #endif
60548 ** Check on a Vdbe to make sure it has not been finalized. Log
60549 ** an error and return true if it has been finalized (or is otherwise
60550 ** invalid). Return false if it is ok.
60552 static int vdbeSafety(Vdbe *p){
60553 if( p->db==0 ){
60554 sqlite3_log(SQLITE_MISUSE, "API called with finalized prepared statement");
60555 return 1;
60556 }else{
60557 return 0;
60560 static int vdbeSafetyNotNull(Vdbe *p){
60561 if( p==0 ){
60562 sqlite3_log(SQLITE_MISUSE, "API called with NULL prepared statement");
60563 return 1;
60564 }else{
60565 return vdbeSafety(p);
60570 ** The following routine destroys a virtual machine that is created by
60571 ** the sqlite3_compile() routine. The integer returned is an SQLITE_
60572 ** success/failure code that describes the result of executing the virtual
60573 ** machine.
60575 ** This routine sets the error code and string returned by
60576 ** sqlite3_errcode(), sqlite3_errmsg() and sqlite3_errmsg16().
60578 SQLITE_API int sqlite3_finalize(sqlite3_stmt *pStmt){
60579 int rc;
60580 if( pStmt==0 ){
60581 /* IMPLEMENTATION-OF: R-57228-12904 Invoking sqlite3_finalize() on a NULL
60582 ** pointer is a harmless no-op. */
60583 rc = SQLITE_OK;
60584 }else{
60585 Vdbe *v = (Vdbe*)pStmt;
60586 sqlite3 *db = v->db;
60587 #if SQLITE_THREADSAFE
60588 sqlite3_mutex *mutex;
60589 #endif
60590 if( vdbeSafety(v) ) return SQLITE_MISUSE_BKPT;
60591 #if SQLITE_THREADSAFE
60592 mutex = v->db->mutex;
60593 #endif
60594 sqlite3_mutex_enter(mutex);
60595 rc = sqlite3VdbeFinalize(v);
60596 rc = sqlite3ApiExit(db, rc);
60597 sqlite3_mutex_leave(mutex);
60599 return rc;
60603 ** Terminate the current execution of an SQL statement and reset it
60604 ** back to its starting state so that it can be reused. A success code from
60605 ** the prior execution is returned.
60607 ** This routine sets the error code and string returned by
60608 ** sqlite3_errcode(), sqlite3_errmsg() and sqlite3_errmsg16().
60610 SQLITE_API int sqlite3_reset(sqlite3_stmt *pStmt){
60611 int rc;
60612 if( pStmt==0 ){
60613 rc = SQLITE_OK;
60614 }else{
60615 Vdbe *v = (Vdbe*)pStmt;
60616 sqlite3_mutex_enter(v->db->mutex);
60617 rc = sqlite3VdbeReset(v);
60618 sqlite3VdbeMakeReady(v, -1, 0, 0, 0, 0, 0);
60619 assert( (rc & (v->db->errMask))==rc );
60620 rc = sqlite3ApiExit(v->db, rc);
60621 sqlite3_mutex_leave(v->db->mutex);
60623 return rc;
60627 ** Set all the parameters in the compiled SQL statement to NULL.
60629 SQLITE_API int sqlite3_clear_bindings(sqlite3_stmt *pStmt){
60630 int i;
60631 int rc = SQLITE_OK;
60632 Vdbe *p = (Vdbe*)pStmt;
60633 #if SQLITE_THREADSAFE
60634 sqlite3_mutex *mutex = ((Vdbe*)pStmt)->db->mutex;
60635 #endif
60636 sqlite3_mutex_enter(mutex);
60637 for(i=0; i<p->nVar; i++){
60638 sqlite3VdbeMemRelease(&p->aVar[i]);
60639 p->aVar[i].flags = MEM_Null;
60641 if( p->isPrepareV2 && p->expmask ){
60642 p->expired = 1;
60644 sqlite3_mutex_leave(mutex);
60645 return rc;
60649 /**************************** sqlite3_value_ *******************************
60650 ** The following routines extract information from a Mem or sqlite3_value
60651 ** structure.
60653 SQLITE_API const void *sqlite3_value_blob(sqlite3_value *pVal){
60654 Mem *p = (Mem*)pVal;
60655 if( p->flags & (MEM_Blob|MEM_Str) ){
60656 sqlite3VdbeMemExpandBlob(p);
60657 p->flags &= ~MEM_Str;
60658 p->flags |= MEM_Blob;
60659 return p->n ? p->z : 0;
60660 }else{
60661 return sqlite3_value_text(pVal);
60664 SQLITE_API int sqlite3_value_bytes(sqlite3_value *pVal){
60665 return sqlite3ValueBytes(pVal, SQLITE_UTF8);
60667 SQLITE_API int sqlite3_value_bytes16(sqlite3_value *pVal){
60668 return sqlite3ValueBytes(pVal, SQLITE_UTF16NATIVE);
60670 SQLITE_API double sqlite3_value_double(sqlite3_value *pVal){
60671 return sqlite3VdbeRealValue((Mem*)pVal);
60673 SQLITE_API int sqlite3_value_int(sqlite3_value *pVal){
60674 return (int)sqlite3VdbeIntValue((Mem*)pVal);
60676 SQLITE_API sqlite_int64 sqlite3_value_int64(sqlite3_value *pVal){
60677 return sqlite3VdbeIntValue((Mem*)pVal);
60679 SQLITE_API const unsigned char *sqlite3_value_text(sqlite3_value *pVal){
60680 return (const unsigned char *)sqlite3ValueText(pVal, SQLITE_UTF8);
60682 #ifndef SQLITE_OMIT_UTF16
60683 SQLITE_API const void *sqlite3_value_text16(sqlite3_value* pVal){
60684 return sqlite3ValueText(pVal, SQLITE_UTF16NATIVE);
60686 SQLITE_API const void *sqlite3_value_text16be(sqlite3_value *pVal){
60687 return sqlite3ValueText(pVal, SQLITE_UTF16BE);
60689 SQLITE_API const void *sqlite3_value_text16le(sqlite3_value *pVal){
60690 return sqlite3ValueText(pVal, SQLITE_UTF16LE);
60692 #endif /* SQLITE_OMIT_UTF16 */
60693 SQLITE_API int sqlite3_value_type(sqlite3_value* pVal){
60694 return pVal->type;
60697 /**************************** sqlite3_result_ *******************************
60698 ** The following routines are used by user-defined functions to specify
60699 ** the function result.
60701 ** The setStrOrError() funtion calls sqlite3VdbeMemSetStr() to store the
60702 ** result as a string or blob but if the string or blob is too large, it
60703 ** then sets the error code to SQLITE_TOOBIG
60705 static void setResultStrOrError(
60706 sqlite3_context *pCtx, /* Function context */
60707 const char *z, /* String pointer */
60708 int n, /* Bytes in string, or negative */
60709 u8 enc, /* Encoding of z. 0 for BLOBs */
60710 void (*xDel)(void*) /* Destructor function */
60712 if( sqlite3VdbeMemSetStr(&pCtx->s, z, n, enc, xDel)==SQLITE_TOOBIG ){
60713 sqlite3_result_error_toobig(pCtx);
60716 SQLITE_API void sqlite3_result_blob(
60717 sqlite3_context *pCtx,
60718 const void *z,
60719 int n,
60720 void (*xDel)(void *)
60722 assert( n>=0 );
60723 assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
60724 setResultStrOrError(pCtx, z, n, 0, xDel);
60726 SQLITE_API void sqlite3_result_double(sqlite3_context *pCtx, double rVal){
60727 assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
60728 sqlite3VdbeMemSetDouble(&pCtx->s, rVal);
60730 SQLITE_API void sqlite3_result_error(sqlite3_context *pCtx, const char *z, int n){
60731 assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
60732 pCtx->isError = SQLITE_ERROR;
60733 sqlite3VdbeMemSetStr(&pCtx->s, z, n, SQLITE_UTF8, SQLITE_TRANSIENT);
60735 #ifndef SQLITE_OMIT_UTF16
60736 SQLITE_API void sqlite3_result_error16(sqlite3_context *pCtx, const void *z, int n){
60737 assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
60738 pCtx->isError = SQLITE_ERROR;
60739 sqlite3VdbeMemSetStr(&pCtx->s, z, n, SQLITE_UTF16NATIVE, SQLITE_TRANSIENT);
60741 #endif
60742 SQLITE_API void sqlite3_result_int(sqlite3_context *pCtx, int iVal){
60743 assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
60744 sqlite3VdbeMemSetInt64(&pCtx->s, (i64)iVal);
60746 SQLITE_API void sqlite3_result_int64(sqlite3_context *pCtx, i64 iVal){
60747 assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
60748 sqlite3VdbeMemSetInt64(&pCtx->s, iVal);
60750 SQLITE_API void sqlite3_result_null(sqlite3_context *pCtx){
60751 assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
60752 sqlite3VdbeMemSetNull(&pCtx->s);
60754 SQLITE_API void sqlite3_result_text(
60755 sqlite3_context *pCtx,
60756 const char *z,
60757 int n,
60758 void (*xDel)(void *)
60760 assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
60761 setResultStrOrError(pCtx, z, n, SQLITE_UTF8, xDel);
60763 #ifndef SQLITE_OMIT_UTF16
60764 SQLITE_API void sqlite3_result_text16(
60765 sqlite3_context *pCtx,
60766 const void *z,
60767 int n,
60768 void (*xDel)(void *)
60770 assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
60771 setResultStrOrError(pCtx, z, n, SQLITE_UTF16NATIVE, xDel);
60773 SQLITE_API void sqlite3_result_text16be(
60774 sqlite3_context *pCtx,
60775 const void *z,
60776 int n,
60777 void (*xDel)(void *)
60779 assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
60780 setResultStrOrError(pCtx, z, n, SQLITE_UTF16BE, xDel);
60782 SQLITE_API void sqlite3_result_text16le(
60783 sqlite3_context *pCtx,
60784 const void *z,
60785 int n,
60786 void (*xDel)(void *)
60788 assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
60789 setResultStrOrError(pCtx, z, n, SQLITE_UTF16LE, xDel);
60791 #endif /* SQLITE_OMIT_UTF16 */
60792 SQLITE_API void sqlite3_result_value(sqlite3_context *pCtx, sqlite3_value *pValue){
60793 assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
60794 sqlite3VdbeMemCopy(&pCtx->s, pValue);
60796 SQLITE_API void sqlite3_result_zeroblob(sqlite3_context *pCtx, int n){
60797 assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
60798 sqlite3VdbeMemSetZeroBlob(&pCtx->s, n);
60800 SQLITE_API void sqlite3_result_error_code(sqlite3_context *pCtx, int errCode){
60801 pCtx->isError = errCode;
60802 if( pCtx->s.flags & MEM_Null ){
60803 sqlite3VdbeMemSetStr(&pCtx->s, sqlite3ErrStr(errCode), -1,
60804 SQLITE_UTF8, SQLITE_STATIC);
60808 /* Force an SQLITE_TOOBIG error. */
60809 SQLITE_API void sqlite3_result_error_toobig(sqlite3_context *pCtx){
60810 assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
60811 pCtx->isError = SQLITE_TOOBIG;
60812 sqlite3VdbeMemSetStr(&pCtx->s, "string or blob too big", -1,
60813 SQLITE_UTF8, SQLITE_STATIC);
60816 /* An SQLITE_NOMEM error. */
60817 SQLITE_API void sqlite3_result_error_nomem(sqlite3_context *pCtx){
60818 assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
60819 sqlite3VdbeMemSetNull(&pCtx->s);
60820 pCtx->isError = SQLITE_NOMEM;
60821 pCtx->s.db->mallocFailed = 1;
60825 ** This function is called after a transaction has been committed. It
60826 ** invokes callbacks registered with sqlite3_wal_hook() as required.
60828 static int doWalCallbacks(sqlite3 *db){
60829 int rc = SQLITE_OK;
60830 #ifndef SQLITE_OMIT_WAL
60831 int i;
60832 for(i=0; i<db->nDb; i++){
60833 Btree *pBt = db->aDb[i].pBt;
60834 if( pBt ){
60835 int nEntry = sqlite3PagerWalCallback(sqlite3BtreePager(pBt));
60836 if( db->xWalCallback && nEntry>0 && rc==SQLITE_OK ){
60837 rc = db->xWalCallback(db->pWalArg, db, db->aDb[i].zName, nEntry);
60841 #endif
60842 return rc;
60846 ** Execute the statement pStmt, either until a row of data is ready, the
60847 ** statement is completely executed or an error occurs.
60849 ** This routine implements the bulk of the logic behind the sqlite_step()
60850 ** API. The only thing omitted is the automatic recompile if a
60851 ** schema change has occurred. That detail is handled by the
60852 ** outer sqlite3_step() wrapper procedure.
60854 static int sqlite3Step(Vdbe *p){
60855 sqlite3 *db;
60856 int rc;
60858 assert(p);
60859 if( p->magic!=VDBE_MAGIC_RUN ){
60860 /* We used to require that sqlite3_reset() be called before retrying
60861 ** sqlite3_step() after any error or after SQLITE_DONE. But beginning
60862 ** with version 3.7.0, we changed this so that sqlite3_reset() would
60863 ** be called automatically instead of throwing the SQLITE_MISUSE error.
60864 ** This "automatic-reset" change is not technically an incompatibility,
60865 ** since any application that receives an SQLITE_MISUSE is broken by
60866 ** definition.
60868 ** Nevertheless, some published applications that were originally written
60869 ** for version 3.6.23 or earlier do in fact depend on SQLITE_MISUSE
60870 ** returns, and the so were broken by the automatic-reset change. As a
60871 ** a work-around, the SQLITE_OMIT_AUTORESET compile-time restores the
60872 ** legacy behavior of returning SQLITE_MISUSE for cases where the
60873 ** previous sqlite3_step() returned something other than a SQLITE_LOCKED
60874 ** or SQLITE_BUSY error.
60876 #ifdef SQLITE_OMIT_AUTORESET
60877 if( p->rc==SQLITE_BUSY || p->rc==SQLITE_LOCKED ){
60878 sqlite3_reset((sqlite3_stmt*)p);
60879 }else{
60880 return SQLITE_MISUSE_BKPT;
60882 #else
60883 sqlite3_reset((sqlite3_stmt*)p);
60884 #endif
60887 /* Check that malloc() has not failed. If it has, return early. */
60888 db = p->db;
60889 if( db->mallocFailed ){
60890 p->rc = SQLITE_NOMEM;
60891 return SQLITE_NOMEM;
60894 if( p->pc<=0 && p->expired ){
60895 p->rc = SQLITE_SCHEMA;
60896 rc = SQLITE_ERROR;
60897 goto end_of_step;
60899 if( p->pc<0 ){
60900 /* If there are no other statements currently running, then
60901 ** reset the interrupt flag. This prevents a call to sqlite3_interrupt
60902 ** from interrupting a statement that has not yet started.
60904 if( db->activeVdbeCnt==0 ){
60905 db->u1.isInterrupted = 0;
60908 assert( db->writeVdbeCnt>0 || db->autoCommit==0 || db->nDeferredCons==0 );
60910 #ifndef SQLITE_OMIT_TRACE
60911 if( db->xProfile && !db->init.busy ){
60912 sqlite3OsCurrentTimeInt64(db->pVfs, &p->startTime);
60914 #endif
60916 db->activeVdbeCnt++;
60917 if( p->readOnly==0 ) db->writeVdbeCnt++;
60918 p->pc = 0;
60920 #ifndef SQLITE_OMIT_EXPLAIN
60921 if( p->explain ){
60922 rc = sqlite3VdbeList(p);
60923 }else
60924 #endif /* SQLITE_OMIT_EXPLAIN */
60926 db->vdbeExecCnt++;
60927 rc = sqlite3VdbeExec(p);
60928 db->vdbeExecCnt--;
60931 #ifndef SQLITE_OMIT_TRACE
60932 /* Invoke the profile callback if there is one
60934 if( rc!=SQLITE_ROW && db->xProfile && !db->init.busy && p->zSql ){
60935 sqlite3_int64 iNow;
60936 sqlite3OsCurrentTimeInt64(db->pVfs, &iNow);
60937 db->xProfile(db->pProfileArg, p->zSql, (iNow - p->startTime)*1000000);
60939 #endif
60941 if( rc==SQLITE_DONE ){
60942 assert( p->rc==SQLITE_OK );
60943 p->rc = doWalCallbacks(db);
60944 if( p->rc!=SQLITE_OK ){
60945 rc = SQLITE_ERROR;
60949 db->errCode = rc;
60950 if( SQLITE_NOMEM==sqlite3ApiExit(p->db, p->rc) ){
60951 p->rc = SQLITE_NOMEM;
60953 end_of_step:
60954 /* At this point local variable rc holds the value that should be
60955 ** returned if this statement was compiled using the legacy
60956 ** sqlite3_prepare() interface. According to the docs, this can only
60957 ** be one of the values in the first assert() below. Variable p->rc
60958 ** contains the value that would be returned if sqlite3_finalize()
60959 ** were called on statement p.
60961 assert( rc==SQLITE_ROW || rc==SQLITE_DONE || rc==SQLITE_ERROR
60962 || rc==SQLITE_BUSY || rc==SQLITE_MISUSE
60964 assert( p->rc!=SQLITE_ROW && p->rc!=SQLITE_DONE );
60965 if( p->isPrepareV2 && rc!=SQLITE_ROW && rc!=SQLITE_DONE ){
60966 /* If this statement was prepared using sqlite3_prepare_v2(), and an
60967 ** error has occured, then return the error code in p->rc to the
60968 ** caller. Set the error code in the database handle to the same value.
60970 rc = db->errCode = p->rc;
60972 return (rc&db->errMask);
60976 ** This is the top-level implementation of sqlite3_step(). Call
60977 ** sqlite3Step() to do most of the work. If a schema error occurs,
60978 ** call sqlite3Reprepare() and try again.
60980 SQLITE_API int sqlite3_step(sqlite3_stmt *pStmt){
60981 int rc = SQLITE_OK; /* Result from sqlite3Step() */
60982 int rc2 = SQLITE_OK; /* Result from sqlite3Reprepare() */
60983 Vdbe *v = (Vdbe*)pStmt; /* the prepared statement */
60984 int cnt = 0; /* Counter to prevent infinite loop of reprepares */
60985 sqlite3 *db; /* The database connection */
60987 if( vdbeSafetyNotNull(v) ){
60988 return SQLITE_MISUSE_BKPT;
60990 db = v->db;
60991 sqlite3_mutex_enter(db->mutex);
60992 while( (rc = sqlite3Step(v))==SQLITE_SCHEMA
60993 && cnt++ < 5
60994 && (rc2 = rc = sqlite3Reprepare(v))==SQLITE_OK ){
60995 sqlite3_reset(pStmt);
60996 v->expired = 0;
60998 if( rc2!=SQLITE_OK && ALWAYS(v->isPrepareV2) && ALWAYS(db->pErr) ){
60999 /* This case occurs after failing to recompile an sql statement.
61000 ** The error message from the SQL compiler has already been loaded
61001 ** into the database handle. This block copies the error message
61002 ** from the database handle into the statement and sets the statement
61003 ** program counter to 0 to ensure that when the statement is
61004 ** finalized or reset the parser error message is available via
61005 ** sqlite3_errmsg() and sqlite3_errcode().
61007 const char *zErr = (const char *)sqlite3_value_text(db->pErr);
61008 sqlite3DbFree(db, v->zErrMsg);
61009 if( !db->mallocFailed ){
61010 v->zErrMsg = sqlite3DbStrDup(db, zErr);
61011 v->rc = rc2;
61012 } else {
61013 v->zErrMsg = 0;
61014 v->rc = rc = SQLITE_NOMEM;
61017 rc = sqlite3ApiExit(db, rc);
61018 sqlite3_mutex_leave(db->mutex);
61019 return rc;
61023 ** Extract the user data from a sqlite3_context structure and return a
61024 ** pointer to it.
61026 SQLITE_API void *sqlite3_user_data(sqlite3_context *p){
61027 assert( p && p->pFunc );
61028 return p->pFunc->pUserData;
61032 ** Extract the user data from a sqlite3_context structure and return a
61033 ** pointer to it.
61035 ** IMPLEMENTATION-OF: R-46798-50301 The sqlite3_context_db_handle() interface
61036 ** returns a copy of the pointer to the database connection (the 1st
61037 ** parameter) of the sqlite3_create_function() and
61038 ** sqlite3_create_function16() routines that originally registered the
61039 ** application defined function.
61041 SQLITE_API sqlite3 *sqlite3_context_db_handle(sqlite3_context *p){
61042 assert( p && p->pFunc );
61043 return p->s.db;
61047 ** The following is the implementation of an SQL function that always
61048 ** fails with an error message stating that the function is used in the
61049 ** wrong context. The sqlite3_overload_function() API might construct
61050 ** SQL function that use this routine so that the functions will exist
61051 ** for name resolution but are actually overloaded by the xFindFunction
61052 ** method of virtual tables.
61054 SQLITE_PRIVATE void sqlite3InvalidFunction(
61055 sqlite3_context *context, /* The function calling context */
61056 int NotUsed, /* Number of arguments to the function */
61057 sqlite3_value **NotUsed2 /* Value of each argument */
61059 const char *zName = context->pFunc->zName;
61060 char *zErr;
61061 UNUSED_PARAMETER2(NotUsed, NotUsed2);
61062 zErr = sqlite3_mprintf(
61063 "unable to use function %s in the requested context", zName);
61064 sqlite3_result_error(context, zErr, -1);
61065 sqlite3_free(zErr);
61069 ** Allocate or return the aggregate context for a user function. A new
61070 ** context is allocated on the first call. Subsequent calls return the
61071 ** same context that was returned on prior calls.
61073 SQLITE_API void *sqlite3_aggregate_context(sqlite3_context *p, int nByte){
61074 Mem *pMem;
61075 assert( p && p->pFunc && p->pFunc->xStep );
61076 assert( sqlite3_mutex_held(p->s.db->mutex) );
61077 pMem = p->pMem;
61078 testcase( nByte<0 );
61079 if( (pMem->flags & MEM_Agg)==0 ){
61080 if( nByte<=0 ){
61081 sqlite3VdbeMemReleaseExternal(pMem);
61082 pMem->flags = MEM_Null;
61083 pMem->z = 0;
61084 }else{
61085 sqlite3VdbeMemGrow(pMem, nByte, 0);
61086 pMem->flags = MEM_Agg;
61087 pMem->u.pDef = p->pFunc;
61088 if( pMem->z ){
61089 memset(pMem->z, 0, nByte);
61093 return (void*)pMem->z;
61097 ** Return the auxilary data pointer, if any, for the iArg'th argument to
61098 ** the user-function defined by pCtx.
61100 SQLITE_API void *sqlite3_get_auxdata(sqlite3_context *pCtx, int iArg){
61101 VdbeFunc *pVdbeFunc;
61103 assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
61104 pVdbeFunc = pCtx->pVdbeFunc;
61105 if( !pVdbeFunc || iArg>=pVdbeFunc->nAux || iArg<0 ){
61106 return 0;
61108 return pVdbeFunc->apAux[iArg].pAux;
61112 ** Set the auxilary data pointer and delete function, for the iArg'th
61113 ** argument to the user-function defined by pCtx. Any previous value is
61114 ** deleted by calling the delete function specified when it was set.
61116 SQLITE_API void sqlite3_set_auxdata(
61117 sqlite3_context *pCtx,
61118 int iArg,
61119 void *pAux,
61120 void (*xDelete)(void*)
61122 struct AuxData *pAuxData;
61123 VdbeFunc *pVdbeFunc;
61124 if( iArg<0 ) goto failed;
61126 assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
61127 pVdbeFunc = pCtx->pVdbeFunc;
61128 if( !pVdbeFunc || pVdbeFunc->nAux<=iArg ){
61129 int nAux = (pVdbeFunc ? pVdbeFunc->nAux : 0);
61130 int nMalloc = sizeof(VdbeFunc) + sizeof(struct AuxData)*iArg;
61131 pVdbeFunc = sqlite3DbRealloc(pCtx->s.db, pVdbeFunc, nMalloc);
61132 if( !pVdbeFunc ){
61133 goto failed;
61135 pCtx->pVdbeFunc = pVdbeFunc;
61136 memset(&pVdbeFunc->apAux[nAux], 0, sizeof(struct AuxData)*(iArg+1-nAux));
61137 pVdbeFunc->nAux = iArg+1;
61138 pVdbeFunc->pFunc = pCtx->pFunc;
61141 pAuxData = &pVdbeFunc->apAux[iArg];
61142 if( pAuxData->pAux && pAuxData->xDelete ){
61143 pAuxData->xDelete(pAuxData->pAux);
61145 pAuxData->pAux = pAux;
61146 pAuxData->xDelete = xDelete;
61147 return;
61149 failed:
61150 if( xDelete ){
61151 xDelete(pAux);
61155 #ifndef SQLITE_OMIT_DEPRECATED
61157 ** Return the number of times the Step function of a aggregate has been
61158 ** called.
61160 ** This function is deprecated. Do not use it for new code. It is
61161 ** provide only to avoid breaking legacy code. New aggregate function
61162 ** implementations should keep their own counts within their aggregate
61163 ** context.
61165 SQLITE_API int sqlite3_aggregate_count(sqlite3_context *p){
61166 assert( p && p->pMem && p->pFunc && p->pFunc->xStep );
61167 return p->pMem->n;
61169 #endif
61172 ** Return the number of columns in the result set for the statement pStmt.
61174 SQLITE_API int sqlite3_column_count(sqlite3_stmt *pStmt){
61175 Vdbe *pVm = (Vdbe *)pStmt;
61176 return pVm ? pVm->nResColumn : 0;
61180 ** Return the number of values available from the current row of the
61181 ** currently executing statement pStmt.
61183 SQLITE_API int sqlite3_data_count(sqlite3_stmt *pStmt){
61184 Vdbe *pVm = (Vdbe *)pStmt;
61185 if( pVm==0 || pVm->pResultSet==0 ) return 0;
61186 return pVm->nResColumn;
61191 ** Check to see if column iCol of the given statement is valid. If
61192 ** it is, return a pointer to the Mem for the value of that column.
61193 ** If iCol is not valid, return a pointer to a Mem which has a value
61194 ** of NULL.
61196 static Mem *columnMem(sqlite3_stmt *pStmt, int i){
61197 Vdbe *pVm;
61198 Mem *pOut;
61200 pVm = (Vdbe *)pStmt;
61201 if( pVm && pVm->pResultSet!=0 && i<pVm->nResColumn && i>=0 ){
61202 sqlite3_mutex_enter(pVm->db->mutex);
61203 pOut = &pVm->pResultSet[i];
61204 }else{
61205 /* If the value passed as the second argument is out of range, return
61206 ** a pointer to the following static Mem object which contains the
61207 ** value SQL NULL. Even though the Mem structure contains an element
61208 ** of type i64, on certain architecture (x86) with certain compiler
61209 ** switches (-Os), gcc may align this Mem object on a 4-byte boundary
61210 ** instead of an 8-byte one. This all works fine, except that when
61211 ** running with SQLITE_DEBUG defined the SQLite code sometimes assert()s
61212 ** that a Mem structure is located on an 8-byte boundary. To prevent
61213 ** this assert() from failing, when building with SQLITE_DEBUG defined
61214 ** using gcc, force nullMem to be 8-byte aligned using the magical
61215 ** __attribute__((aligned(8))) macro. */
61216 static const Mem nullMem
61217 #if defined(SQLITE_DEBUG) && defined(__GNUC__)
61218 __attribute__((aligned(8)))
61219 #endif
61220 = {0, "", (double)0, {0}, 0, MEM_Null, SQLITE_NULL, 0,
61221 #ifdef SQLITE_DEBUG
61222 0, 0, /* pScopyFrom, pFiller */
61223 #endif
61224 0, 0 };
61226 if( pVm && ALWAYS(pVm->db) ){
61227 sqlite3_mutex_enter(pVm->db->mutex);
61228 sqlite3Error(pVm->db, SQLITE_RANGE, 0);
61230 pOut = (Mem*)&nullMem;
61232 return pOut;
61236 ** This function is called after invoking an sqlite3_value_XXX function on a
61237 ** column value (i.e. a value returned by evaluating an SQL expression in the
61238 ** select list of a SELECT statement) that may cause a malloc() failure. If
61239 ** malloc() has failed, the threads mallocFailed flag is cleared and the result
61240 ** code of statement pStmt set to SQLITE_NOMEM.
61242 ** Specifically, this is called from within:
61244 ** sqlite3_column_int()
61245 ** sqlite3_column_int64()
61246 ** sqlite3_column_text()
61247 ** sqlite3_column_text16()
61248 ** sqlite3_column_real()
61249 ** sqlite3_column_bytes()
61250 ** sqlite3_column_bytes16()
61251 ** sqiite3_column_blob()
61253 static void columnMallocFailure(sqlite3_stmt *pStmt)
61255 /* If malloc() failed during an encoding conversion within an
61256 ** sqlite3_column_XXX API, then set the return code of the statement to
61257 ** SQLITE_NOMEM. The next call to _step() (if any) will return SQLITE_ERROR
61258 ** and _finalize() will return NOMEM.
61260 Vdbe *p = (Vdbe *)pStmt;
61261 if( p ){
61262 p->rc = sqlite3ApiExit(p->db, p->rc);
61263 sqlite3_mutex_leave(p->db->mutex);
61267 /**************************** sqlite3_column_ *******************************
61268 ** The following routines are used to access elements of the current row
61269 ** in the result set.
61271 SQLITE_API const void *sqlite3_column_blob(sqlite3_stmt *pStmt, int i){
61272 const void *val;
61273 val = sqlite3_value_blob( columnMem(pStmt,i) );
61274 /* Even though there is no encoding conversion, value_blob() might
61275 ** need to call malloc() to expand the result of a zeroblob()
61276 ** expression.
61278 columnMallocFailure(pStmt);
61279 return val;
61281 SQLITE_API int sqlite3_column_bytes(sqlite3_stmt *pStmt, int i){
61282 int val = sqlite3_value_bytes( columnMem(pStmt,i) );
61283 columnMallocFailure(pStmt);
61284 return val;
61286 SQLITE_API int sqlite3_column_bytes16(sqlite3_stmt *pStmt, int i){
61287 int val = sqlite3_value_bytes16( columnMem(pStmt,i) );
61288 columnMallocFailure(pStmt);
61289 return val;
61291 SQLITE_API double sqlite3_column_double(sqlite3_stmt *pStmt, int i){
61292 double val = sqlite3_value_double( columnMem(pStmt,i) );
61293 columnMallocFailure(pStmt);
61294 return val;
61296 SQLITE_API int sqlite3_column_int(sqlite3_stmt *pStmt, int i){
61297 int val = sqlite3_value_int( columnMem(pStmt,i) );
61298 columnMallocFailure(pStmt);
61299 return val;
61301 SQLITE_API sqlite_int64 sqlite3_column_int64(sqlite3_stmt *pStmt, int i){
61302 sqlite_int64 val = sqlite3_value_int64( columnMem(pStmt,i) );
61303 columnMallocFailure(pStmt);
61304 return val;
61306 SQLITE_API const unsigned char *sqlite3_column_text(sqlite3_stmt *pStmt, int i){
61307 const unsigned char *val = sqlite3_value_text( columnMem(pStmt,i) );
61308 columnMallocFailure(pStmt);
61309 return val;
61311 SQLITE_API sqlite3_value *sqlite3_column_value(sqlite3_stmt *pStmt, int i){
61312 Mem *pOut = columnMem(pStmt, i);
61313 if( pOut->flags&MEM_Static ){
61314 pOut->flags &= ~MEM_Static;
61315 pOut->flags |= MEM_Ephem;
61317 columnMallocFailure(pStmt);
61318 return (sqlite3_value *)pOut;
61320 #ifndef SQLITE_OMIT_UTF16
61321 SQLITE_API const void *sqlite3_column_text16(sqlite3_stmt *pStmt, int i){
61322 const void *val = sqlite3_value_text16( columnMem(pStmt,i) );
61323 columnMallocFailure(pStmt);
61324 return val;
61326 #endif /* SQLITE_OMIT_UTF16 */
61327 SQLITE_API int sqlite3_column_type(sqlite3_stmt *pStmt, int i){
61328 int iType = sqlite3_value_type( columnMem(pStmt,i) );
61329 columnMallocFailure(pStmt);
61330 return iType;
61333 /* The following function is experimental and subject to change or
61334 ** removal */
61335 /*int sqlite3_column_numeric_type(sqlite3_stmt *pStmt, int i){
61336 ** return sqlite3_value_numeric_type( columnMem(pStmt,i) );
61341 ** Convert the N-th element of pStmt->pColName[] into a string using
61342 ** xFunc() then return that string. If N is out of range, return 0.
61344 ** There are up to 5 names for each column. useType determines which
61345 ** name is returned. Here are the names:
61347 ** 0 The column name as it should be displayed for output
61348 ** 1 The datatype name for the column
61349 ** 2 The name of the database that the column derives from
61350 ** 3 The name of the table that the column derives from
61351 ** 4 The name of the table column that the result column derives from
61353 ** If the result is not a simple column reference (if it is an expression
61354 ** or a constant) then useTypes 2, 3, and 4 return NULL.
61356 static const void *columnName(
61357 sqlite3_stmt *pStmt,
61358 int N,
61359 const void *(*xFunc)(Mem*),
61360 int useType
61362 const void *ret = 0;
61363 Vdbe *p = (Vdbe *)pStmt;
61364 int n;
61365 sqlite3 *db = p->db;
61367 assert( db!=0 );
61368 n = sqlite3_column_count(pStmt);
61369 if( N<n && N>=0 ){
61370 N += useType*n;
61371 sqlite3_mutex_enter(db->mutex);
61372 assert( db->mallocFailed==0 );
61373 ret = xFunc(&p->aColName[N]);
61374 /* A malloc may have failed inside of the xFunc() call. If this
61375 ** is the case, clear the mallocFailed flag and return NULL.
61377 if( db->mallocFailed ){
61378 db->mallocFailed = 0;
61379 ret = 0;
61381 sqlite3_mutex_leave(db->mutex);
61383 return ret;
61387 ** Return the name of the Nth column of the result set returned by SQL
61388 ** statement pStmt.
61390 SQLITE_API const char *sqlite3_column_name(sqlite3_stmt *pStmt, int N){
61391 return columnName(
61392 pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_NAME);
61394 #ifndef SQLITE_OMIT_UTF16
61395 SQLITE_API const void *sqlite3_column_name16(sqlite3_stmt *pStmt, int N){
61396 return columnName(
61397 pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_NAME);
61399 #endif
61402 ** Constraint: If you have ENABLE_COLUMN_METADATA then you must
61403 ** not define OMIT_DECLTYPE.
61405 #if defined(SQLITE_OMIT_DECLTYPE) && defined(SQLITE_ENABLE_COLUMN_METADATA)
61406 # error "Must not define both SQLITE_OMIT_DECLTYPE \
61407 and SQLITE_ENABLE_COLUMN_METADATA"
61408 #endif
61410 #ifndef SQLITE_OMIT_DECLTYPE
61412 ** Return the column declaration type (if applicable) of the 'i'th column
61413 ** of the result set of SQL statement pStmt.
61415 SQLITE_API const char *sqlite3_column_decltype(sqlite3_stmt *pStmt, int N){
61416 return columnName(
61417 pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_DECLTYPE);
61419 #ifndef SQLITE_OMIT_UTF16
61420 SQLITE_API const void *sqlite3_column_decltype16(sqlite3_stmt *pStmt, int N){
61421 return columnName(
61422 pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_DECLTYPE);
61424 #endif /* SQLITE_OMIT_UTF16 */
61425 #endif /* SQLITE_OMIT_DECLTYPE */
61427 #ifdef SQLITE_ENABLE_COLUMN_METADATA
61429 ** Return the name of the database from which a result column derives.
61430 ** NULL is returned if the result column is an expression or constant or
61431 ** anything else which is not an unabiguous reference to a database column.
61433 SQLITE_API const char *sqlite3_column_database_name(sqlite3_stmt *pStmt, int N){
61434 return columnName(
61435 pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_DATABASE);
61437 #ifndef SQLITE_OMIT_UTF16
61438 SQLITE_API const void *sqlite3_column_database_name16(sqlite3_stmt *pStmt, int N){
61439 return columnName(
61440 pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_DATABASE);
61442 #endif /* SQLITE_OMIT_UTF16 */
61445 ** Return the name of the table from which a result column derives.
61446 ** NULL is returned if the result column is an expression or constant or
61447 ** anything else which is not an unabiguous reference to a database column.
61449 SQLITE_API const char *sqlite3_column_table_name(sqlite3_stmt *pStmt, int N){
61450 return columnName(
61451 pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_TABLE);
61453 #ifndef SQLITE_OMIT_UTF16
61454 SQLITE_API const void *sqlite3_column_table_name16(sqlite3_stmt *pStmt, int N){
61455 return columnName(
61456 pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_TABLE);
61458 #endif /* SQLITE_OMIT_UTF16 */
61461 ** Return the name of the table column from which a result column derives.
61462 ** NULL is returned if the result column is an expression or constant or
61463 ** anything else which is not an unabiguous reference to a database column.
61465 SQLITE_API const char *sqlite3_column_origin_name(sqlite3_stmt *pStmt, int N){
61466 return columnName(
61467 pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_COLUMN);
61469 #ifndef SQLITE_OMIT_UTF16
61470 SQLITE_API const void *sqlite3_column_origin_name16(sqlite3_stmt *pStmt, int N){
61471 return columnName(
61472 pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_COLUMN);
61474 #endif /* SQLITE_OMIT_UTF16 */
61475 #endif /* SQLITE_ENABLE_COLUMN_METADATA */
61478 /******************************* sqlite3_bind_ ***************************
61480 ** Routines used to attach values to wildcards in a compiled SQL statement.
61483 ** Unbind the value bound to variable i in virtual machine p. This is the
61484 ** the same as binding a NULL value to the column. If the "i" parameter is
61485 ** out of range, then SQLITE_RANGE is returned. Othewise SQLITE_OK.
61487 ** A successful evaluation of this routine acquires the mutex on p.
61488 ** the mutex is released if any kind of error occurs.
61490 ** The error code stored in database p->db is overwritten with the return
61491 ** value in any case.
61493 static int vdbeUnbind(Vdbe *p, int i){
61494 Mem *pVar;
61495 if( vdbeSafetyNotNull(p) ){
61496 return SQLITE_MISUSE_BKPT;
61498 sqlite3_mutex_enter(p->db->mutex);
61499 if( p->magic!=VDBE_MAGIC_RUN || p->pc>=0 ){
61500 sqlite3Error(p->db, SQLITE_MISUSE, 0);
61501 sqlite3_mutex_leave(p->db->mutex);
61502 sqlite3_log(SQLITE_MISUSE,
61503 "bind on a busy prepared statement: [%s]", p->zSql);
61504 return SQLITE_MISUSE_BKPT;
61506 if( i<1 || i>p->nVar ){
61507 sqlite3Error(p->db, SQLITE_RANGE, 0);
61508 sqlite3_mutex_leave(p->db->mutex);
61509 return SQLITE_RANGE;
61511 i--;
61512 pVar = &p->aVar[i];
61513 sqlite3VdbeMemRelease(pVar);
61514 pVar->flags = MEM_Null;
61515 sqlite3Error(p->db, SQLITE_OK, 0);
61517 /* If the bit corresponding to this variable in Vdbe.expmask is set, then
61518 ** binding a new value to this variable invalidates the current query plan.
61520 ** IMPLEMENTATION-OF: R-48440-37595 If the specific value bound to host
61521 ** parameter in the WHERE clause might influence the choice of query plan
61522 ** for a statement, then the statement will be automatically recompiled,
61523 ** as if there had been a schema change, on the first sqlite3_step() call
61524 ** following any change to the bindings of that parameter.
61526 if( p->isPrepareV2 &&
61527 ((i<32 && p->expmask & ((u32)1 << i)) || p->expmask==0xffffffff)
61529 p->expired = 1;
61531 return SQLITE_OK;
61535 ** Bind a text or BLOB value.
61537 static int bindText(
61538 sqlite3_stmt *pStmt, /* The statement to bind against */
61539 int i, /* Index of the parameter to bind */
61540 const void *zData, /* Pointer to the data to be bound */
61541 int nData, /* Number of bytes of data to be bound */
61542 void (*xDel)(void*), /* Destructor for the data */
61543 u8 encoding /* Encoding for the data */
61545 Vdbe *p = (Vdbe *)pStmt;
61546 Mem *pVar;
61547 int rc;
61549 rc = vdbeUnbind(p, i);
61550 if( rc==SQLITE_OK ){
61551 if( zData!=0 ){
61552 pVar = &p->aVar[i-1];
61553 rc = sqlite3VdbeMemSetStr(pVar, zData, nData, encoding, xDel);
61554 if( rc==SQLITE_OK && encoding!=0 ){
61555 rc = sqlite3VdbeChangeEncoding(pVar, ENC(p->db));
61557 sqlite3Error(p->db, rc, 0);
61558 rc = sqlite3ApiExit(p->db, rc);
61560 sqlite3_mutex_leave(p->db->mutex);
61561 }else if( xDel!=SQLITE_STATIC && xDel!=SQLITE_TRANSIENT ){
61562 xDel((void*)zData);
61564 return rc;
61569 ** Bind a blob value to an SQL statement variable.
61571 SQLITE_API int sqlite3_bind_blob(
61572 sqlite3_stmt *pStmt,
61573 int i,
61574 const void *zData,
61575 int nData,
61576 void (*xDel)(void*)
61578 return bindText(pStmt, i, zData, nData, xDel, 0);
61580 SQLITE_API int sqlite3_bind_double(sqlite3_stmt *pStmt, int i, double rValue){
61581 int rc;
61582 Vdbe *p = (Vdbe *)pStmt;
61583 rc = vdbeUnbind(p, i);
61584 if( rc==SQLITE_OK ){
61585 sqlite3VdbeMemSetDouble(&p->aVar[i-1], rValue);
61586 sqlite3_mutex_leave(p->db->mutex);
61588 return rc;
61590 SQLITE_API int sqlite3_bind_int(sqlite3_stmt *p, int i, int iValue){
61591 return sqlite3_bind_int64(p, i, (i64)iValue);
61593 SQLITE_API int sqlite3_bind_int64(sqlite3_stmt *pStmt, int i, sqlite_int64 iValue){
61594 int rc;
61595 Vdbe *p = (Vdbe *)pStmt;
61596 rc = vdbeUnbind(p, i);
61597 if( rc==SQLITE_OK ){
61598 sqlite3VdbeMemSetInt64(&p->aVar[i-1], iValue);
61599 sqlite3_mutex_leave(p->db->mutex);
61601 return rc;
61603 SQLITE_API int sqlite3_bind_null(sqlite3_stmt *pStmt, int i){
61604 int rc;
61605 Vdbe *p = (Vdbe*)pStmt;
61606 rc = vdbeUnbind(p, i);
61607 if( rc==SQLITE_OK ){
61608 sqlite3_mutex_leave(p->db->mutex);
61610 return rc;
61612 SQLITE_API int sqlite3_bind_text(
61613 sqlite3_stmt *pStmt,
61614 int i,
61615 const char *zData,
61616 int nData,
61617 void (*xDel)(void*)
61619 return bindText(pStmt, i, zData, nData, xDel, SQLITE_UTF8);
61621 #ifndef SQLITE_OMIT_UTF16
61622 SQLITE_API int sqlite3_bind_text16(
61623 sqlite3_stmt *pStmt,
61624 int i,
61625 const void *zData,
61626 int nData,
61627 void (*xDel)(void*)
61629 return bindText(pStmt, i, zData, nData, xDel, SQLITE_UTF16NATIVE);
61631 #endif /* SQLITE_OMIT_UTF16 */
61632 SQLITE_API int sqlite3_bind_value(sqlite3_stmt *pStmt, int i, const sqlite3_value *pValue){
61633 int rc;
61634 switch( pValue->type ){
61635 case SQLITE_INTEGER: {
61636 rc = sqlite3_bind_int64(pStmt, i, pValue->u.i);
61637 break;
61639 case SQLITE_FLOAT: {
61640 rc = sqlite3_bind_double(pStmt, i, pValue->r);
61641 break;
61643 case SQLITE_BLOB: {
61644 if( pValue->flags & MEM_Zero ){
61645 rc = sqlite3_bind_zeroblob(pStmt, i, pValue->u.nZero);
61646 }else{
61647 rc = sqlite3_bind_blob(pStmt, i, pValue->z, pValue->n,SQLITE_TRANSIENT);
61649 break;
61651 case SQLITE_TEXT: {
61652 rc = bindText(pStmt,i, pValue->z, pValue->n, SQLITE_TRANSIENT,
61653 pValue->enc);
61654 break;
61656 default: {
61657 rc = sqlite3_bind_null(pStmt, i);
61658 break;
61661 return rc;
61663 SQLITE_API int sqlite3_bind_zeroblob(sqlite3_stmt *pStmt, int i, int n){
61664 int rc;
61665 Vdbe *p = (Vdbe *)pStmt;
61666 rc = vdbeUnbind(p, i);
61667 if( rc==SQLITE_OK ){
61668 sqlite3VdbeMemSetZeroBlob(&p->aVar[i-1], n);
61669 sqlite3_mutex_leave(p->db->mutex);
61671 return rc;
61675 ** Return the number of wildcards that can be potentially bound to.
61676 ** This routine is added to support DBD::SQLite.
61678 SQLITE_API int sqlite3_bind_parameter_count(sqlite3_stmt *pStmt){
61679 Vdbe *p = (Vdbe*)pStmt;
61680 return p ? p->nVar : 0;
61684 ** Create a mapping from variable numbers to variable names
61685 ** in the Vdbe.azVar[] array, if such a mapping does not already
61686 ** exist.
61688 static void createVarMap(Vdbe *p){
61689 if( !p->okVar ){
61690 int j;
61691 Op *pOp;
61692 sqlite3_mutex_enter(p->db->mutex);
61693 /* The race condition here is harmless. If two threads call this
61694 ** routine on the same Vdbe at the same time, they both might end
61695 ** up initializing the Vdbe.azVar[] array. That is a little extra
61696 ** work but it results in the same answer.
61698 for(j=0, pOp=p->aOp; j<p->nOp; j++, pOp++){
61699 if( pOp->opcode==OP_Variable ){
61700 assert( pOp->p1>0 && pOp->p1<=p->nVar );
61701 p->azVar[pOp->p1-1] = pOp->p4.z;
61704 p->okVar = 1;
61705 sqlite3_mutex_leave(p->db->mutex);
61710 ** Return the name of a wildcard parameter. Return NULL if the index
61711 ** is out of range or if the wildcard is unnamed.
61713 ** The result is always UTF-8.
61715 SQLITE_API const char *sqlite3_bind_parameter_name(sqlite3_stmt *pStmt, int i){
61716 Vdbe *p = (Vdbe*)pStmt;
61717 if( p==0 || i<1 || i>p->nVar ){
61718 return 0;
61720 createVarMap(p);
61721 return p->azVar[i-1];
61725 ** Given a wildcard parameter name, return the index of the variable
61726 ** with that name. If there is no variable with the given name,
61727 ** return 0.
61729 SQLITE_PRIVATE int sqlite3VdbeParameterIndex(Vdbe *p, const char *zName, int nName){
61730 int i;
61731 if( p==0 ){
61732 return 0;
61734 createVarMap(p);
61735 if( zName ){
61736 for(i=0; i<p->nVar; i++){
61737 const char *z = p->azVar[i];
61738 if( z && strncmp(z,zName,nName)==0 && z[nName]==0 ){
61739 return i+1;
61743 return 0;
61745 SQLITE_API int sqlite3_bind_parameter_index(sqlite3_stmt *pStmt, const char *zName){
61746 return sqlite3VdbeParameterIndex((Vdbe*)pStmt, zName, sqlite3Strlen30(zName));
61750 ** Transfer all bindings from the first statement over to the second.
61752 SQLITE_PRIVATE int sqlite3TransferBindings(sqlite3_stmt *pFromStmt, sqlite3_stmt *pToStmt){
61753 Vdbe *pFrom = (Vdbe*)pFromStmt;
61754 Vdbe *pTo = (Vdbe*)pToStmt;
61755 int i;
61756 assert( pTo->db==pFrom->db );
61757 assert( pTo->nVar==pFrom->nVar );
61758 sqlite3_mutex_enter(pTo->db->mutex);
61759 for(i=0; i<pFrom->nVar; i++){
61760 sqlite3VdbeMemMove(&pTo->aVar[i], &pFrom->aVar[i]);
61762 sqlite3_mutex_leave(pTo->db->mutex);
61763 return SQLITE_OK;
61766 #ifndef SQLITE_OMIT_DEPRECATED
61768 ** Deprecated external interface. Internal/core SQLite code
61769 ** should call sqlite3TransferBindings.
61771 ** Is is misuse to call this routine with statements from different
61772 ** database connections. But as this is a deprecated interface, we
61773 ** will not bother to check for that condition.
61775 ** If the two statements contain a different number of bindings, then
61776 ** an SQLITE_ERROR is returned. Nothing else can go wrong, so otherwise
61777 ** SQLITE_OK is returned.
61779 SQLITE_API int sqlite3_transfer_bindings(sqlite3_stmt *pFromStmt, sqlite3_stmt *pToStmt){
61780 Vdbe *pFrom = (Vdbe*)pFromStmt;
61781 Vdbe *pTo = (Vdbe*)pToStmt;
61782 if( pFrom->nVar!=pTo->nVar ){
61783 return SQLITE_ERROR;
61785 if( pTo->isPrepareV2 && pTo->expmask ){
61786 pTo->expired = 1;
61788 if( pFrom->isPrepareV2 && pFrom->expmask ){
61789 pFrom->expired = 1;
61791 return sqlite3TransferBindings(pFromStmt, pToStmt);
61793 #endif
61796 ** Return the sqlite3* database handle to which the prepared statement given
61797 ** in the argument belongs. This is the same database handle that was
61798 ** the first argument to the sqlite3_prepare() that was used to create
61799 ** the statement in the first place.
61801 SQLITE_API sqlite3 *sqlite3_db_handle(sqlite3_stmt *pStmt){
61802 return pStmt ? ((Vdbe*)pStmt)->db : 0;
61806 ** Return true if the prepared statement is guaranteed to not modify the
61807 ** database.
61809 SQLITE_API int sqlite3_stmt_readonly(sqlite3_stmt *pStmt){
61810 return pStmt ? ((Vdbe*)pStmt)->readOnly : 1;
61814 ** Return a pointer to the next prepared statement after pStmt associated
61815 ** with database connection pDb. If pStmt is NULL, return the first
61816 ** prepared statement for the database connection. Return NULL if there
61817 ** are no more.
61819 SQLITE_API sqlite3_stmt *sqlite3_next_stmt(sqlite3 *pDb, sqlite3_stmt *pStmt){
61820 sqlite3_stmt *pNext;
61821 sqlite3_mutex_enter(pDb->mutex);
61822 if( pStmt==0 ){
61823 pNext = (sqlite3_stmt*)pDb->pVdbe;
61824 }else{
61825 pNext = (sqlite3_stmt*)((Vdbe*)pStmt)->pNext;
61827 sqlite3_mutex_leave(pDb->mutex);
61828 return pNext;
61832 ** Return the value of a status counter for a prepared statement
61834 SQLITE_API int sqlite3_stmt_status(sqlite3_stmt *pStmt, int op, int resetFlag){
61835 Vdbe *pVdbe = (Vdbe*)pStmt;
61836 int v = pVdbe->aCounter[op-1];
61837 if( resetFlag ) pVdbe->aCounter[op-1] = 0;
61838 return v;
61841 /************** End of vdbeapi.c *********************************************/
61842 /************** Begin file vdbetrace.c ***************************************/
61844 ** 2009 November 25
61846 ** The author disclaims copyright to this source code. In place of
61847 ** a legal notice, here is a blessing:
61849 ** May you do good and not evil.
61850 ** May you find forgiveness for yourself and forgive others.
61851 ** May you share freely, never taking more than you give.
61853 *************************************************************************
61855 ** This file contains code used to insert the values of host parameters
61856 ** (aka "wildcards") into the SQL text output by sqlite3_trace().
61859 #ifndef SQLITE_OMIT_TRACE
61862 ** zSql is a zero-terminated string of UTF-8 SQL text. Return the number of
61863 ** bytes in this text up to but excluding the first character in
61864 ** a host parameter. If the text contains no host parameters, return
61865 ** the total number of bytes in the text.
61867 static int findNextHostParameter(const char *zSql, int *pnToken){
61868 int tokenType;
61869 int nTotal = 0;
61870 int n;
61872 *pnToken = 0;
61873 while( zSql[0] ){
61874 n = sqlite3GetToken((u8*)zSql, &tokenType);
61875 assert( n>0 && tokenType!=TK_ILLEGAL );
61876 if( tokenType==TK_VARIABLE ){
61877 *pnToken = n;
61878 break;
61880 nTotal += n;
61881 zSql += n;
61883 return nTotal;
61887 ** This function returns a pointer to a nul-terminated string in memory
61888 ** obtained from sqlite3DbMalloc(). If sqlite3.vdbeExecCnt is 1, then the
61889 ** string contains a copy of zRawSql but with host parameters expanded to
61890 ** their current bindings. Or, if sqlite3.vdbeExecCnt is greater than 1,
61891 ** then the returned string holds a copy of zRawSql with "-- " prepended
61892 ** to each line of text.
61894 ** The calling function is responsible for making sure the memory returned
61895 ** is eventually freed.
61897 ** ALGORITHM: Scan the input string looking for host parameters in any of
61898 ** these forms: ?, ?N, $A, @A, :A. Take care to avoid text within
61899 ** string literals, quoted identifier names, and comments. For text forms,
61900 ** the host parameter index is found by scanning the perpared
61901 ** statement for the corresponding OP_Variable opcode. Once the host
61902 ** parameter index is known, locate the value in p->aVar[]. Then render
61903 ** the value as a literal in place of the host parameter name.
61905 SQLITE_PRIVATE char *sqlite3VdbeExpandSql(
61906 Vdbe *p, /* The prepared statement being evaluated */
61907 const char *zRawSql /* Raw text of the SQL statement */
61909 sqlite3 *db; /* The database connection */
61910 int idx = 0; /* Index of a host parameter */
61911 int nextIndex = 1; /* Index of next ? host parameter */
61912 int n; /* Length of a token prefix */
61913 int nToken; /* Length of the parameter token */
61914 int i; /* Loop counter */
61915 Mem *pVar; /* Value of a host parameter */
61916 StrAccum out; /* Accumulate the output here */
61917 char zBase[100]; /* Initial working space */
61919 db = p->db;
61920 sqlite3StrAccumInit(&out, zBase, sizeof(zBase),
61921 db->aLimit[SQLITE_LIMIT_LENGTH]);
61922 out.db = db;
61923 if( db->vdbeExecCnt>1 ){
61924 while( *zRawSql ){
61925 const char *zStart = zRawSql;
61926 while( *(zRawSql++)!='\n' && *zRawSql );
61927 sqlite3StrAccumAppend(&out, "-- ", 3);
61928 sqlite3StrAccumAppend(&out, zStart, (int)(zRawSql-zStart));
61930 }else{
61931 while( zRawSql[0] ){
61932 n = findNextHostParameter(zRawSql, &nToken);
61933 assert( n>0 );
61934 sqlite3StrAccumAppend(&out, zRawSql, n);
61935 zRawSql += n;
61936 assert( zRawSql[0] || nToken==0 );
61937 if( nToken==0 ) break;
61938 if( zRawSql[0]=='?' ){
61939 if( nToken>1 ){
61940 assert( sqlite3Isdigit(zRawSql[1]) );
61941 sqlite3GetInt32(&zRawSql[1], &idx);
61942 }else{
61943 idx = nextIndex;
61945 }else{
61946 assert( zRawSql[0]==':' || zRawSql[0]=='$' || zRawSql[0]=='@' );
61947 testcase( zRawSql[0]==':' );
61948 testcase( zRawSql[0]=='$' );
61949 testcase( zRawSql[0]=='@' );
61950 idx = sqlite3VdbeParameterIndex(p, zRawSql, nToken);
61951 assert( idx>0 );
61953 zRawSql += nToken;
61954 nextIndex = idx + 1;
61955 assert( idx>0 && idx<=p->nVar );
61956 pVar = &p->aVar[idx-1];
61957 if( pVar->flags & MEM_Null ){
61958 sqlite3StrAccumAppend(&out, "NULL", 4);
61959 }else if( pVar->flags & MEM_Int ){
61960 sqlite3XPrintf(&out, "%lld", pVar->u.i);
61961 }else if( pVar->flags & MEM_Real ){
61962 sqlite3XPrintf(&out, "%!.15g", pVar->r);
61963 }else if( pVar->flags & MEM_Str ){
61964 #ifndef SQLITE_OMIT_UTF16
61965 u8 enc = ENC(db);
61966 if( enc!=SQLITE_UTF8 ){
61967 Mem utf8;
61968 memset(&utf8, 0, sizeof(utf8));
61969 utf8.db = db;
61970 sqlite3VdbeMemSetStr(&utf8, pVar->z, pVar->n, enc, SQLITE_STATIC);
61971 sqlite3VdbeChangeEncoding(&utf8, SQLITE_UTF8);
61972 sqlite3XPrintf(&out, "'%.*q'", utf8.n, utf8.z);
61973 sqlite3VdbeMemRelease(&utf8);
61974 }else
61975 #endif
61977 sqlite3XPrintf(&out, "'%.*q'", pVar->n, pVar->z);
61979 }else if( pVar->flags & MEM_Zero ){
61980 sqlite3XPrintf(&out, "zeroblob(%d)", pVar->u.nZero);
61981 }else{
61982 assert( pVar->flags & MEM_Blob );
61983 sqlite3StrAccumAppend(&out, "x'", 2);
61984 for(i=0; i<pVar->n; i++){
61985 sqlite3XPrintf(&out, "%02x", pVar->z[i]&0xff);
61987 sqlite3StrAccumAppend(&out, "'", 1);
61991 return sqlite3StrAccumFinish(&out);
61994 #endif /* #ifndef SQLITE_OMIT_TRACE */
61996 /************** End of vdbetrace.c *******************************************/
61997 /************** Begin file vdbe.c ********************************************/
61999 ** 2001 September 15
62001 ** The author disclaims copyright to this source code. In place of
62002 ** a legal notice, here is a blessing:
62004 ** May you do good and not evil.
62005 ** May you find forgiveness for yourself and forgive others.
62006 ** May you share freely, never taking more than you give.
62008 *************************************************************************
62009 ** The code in this file implements execution method of the
62010 ** Virtual Database Engine (VDBE). A separate file ("vdbeaux.c")
62011 ** handles housekeeping details such as creating and deleting
62012 ** VDBE instances. This file is solely interested in executing
62013 ** the VDBE program.
62015 ** In the external interface, an "sqlite3_stmt*" is an opaque pointer
62016 ** to a VDBE.
62018 ** The SQL parser generates a program which is then executed by
62019 ** the VDBE to do the work of the SQL statement. VDBE programs are
62020 ** similar in form to assembly language. The program consists of
62021 ** a linear sequence of operations. Each operation has an opcode
62022 ** and 5 operands. Operands P1, P2, and P3 are integers. Operand P4
62023 ** is a null-terminated string. Operand P5 is an unsigned character.
62024 ** Few opcodes use all 5 operands.
62026 ** Computation results are stored on a set of registers numbered beginning
62027 ** with 1 and going up to Vdbe.nMem. Each register can store
62028 ** either an integer, a null-terminated string, a floating point
62029 ** number, or the SQL "NULL" value. An implicit conversion from one
62030 ** type to the other occurs as necessary.
62032 ** Most of the code in this file is taken up by the sqlite3VdbeExec()
62033 ** function which does the work of interpreting a VDBE program.
62034 ** But other routines are also provided to help in building up
62035 ** a program instruction by instruction.
62037 ** Various scripts scan this source file in order to generate HTML
62038 ** documentation, headers files, or other derived files. The formatting
62039 ** of the code in this file is, therefore, important. See other comments
62040 ** in this file for details. If in doubt, do not deviate from existing
62041 ** commenting and indentation practices when changing or adding code.
62045 ** Invoke this macro on memory cells just prior to changing the
62046 ** value of the cell. This macro verifies that shallow copies are
62047 ** not misused.
62049 #ifdef SQLITE_DEBUG
62050 # define memAboutToChange(P,M) sqlite3VdbeMemPrepareToChange(P,M)
62051 #else
62052 # define memAboutToChange(P,M)
62053 #endif
62056 ** The following global variable is incremented every time a cursor
62057 ** moves, either by the OP_SeekXX, OP_Next, or OP_Prev opcodes. The test
62058 ** procedures use this information to make sure that indices are
62059 ** working correctly. This variable has no function other than to
62060 ** help verify the correct operation of the library.
62062 #ifdef SQLITE_TEST
62063 SQLITE_API int sqlite3_search_count = 0;
62064 #endif
62067 ** When this global variable is positive, it gets decremented once before
62068 ** each instruction in the VDBE. When reaches zero, the u1.isInterrupted
62069 ** field of the sqlite3 structure is set in order to simulate and interrupt.
62071 ** This facility is used for testing purposes only. It does not function
62072 ** in an ordinary build.
62074 #ifdef SQLITE_TEST
62075 SQLITE_API int sqlite3_interrupt_count = 0;
62076 #endif
62079 ** The next global variable is incremented each type the OP_Sort opcode
62080 ** is executed. The test procedures use this information to make sure that
62081 ** sorting is occurring or not occurring at appropriate times. This variable
62082 ** has no function other than to help verify the correct operation of the
62083 ** library.
62085 #ifdef SQLITE_TEST
62086 SQLITE_API int sqlite3_sort_count = 0;
62087 #endif
62090 ** The next global variable records the size of the largest MEM_Blob
62091 ** or MEM_Str that has been used by a VDBE opcode. The test procedures
62092 ** use this information to make sure that the zero-blob functionality
62093 ** is working correctly. This variable has no function other than to
62094 ** help verify the correct operation of the library.
62096 #ifdef SQLITE_TEST
62097 SQLITE_API int sqlite3_max_blobsize = 0;
62098 static void updateMaxBlobsize(Mem *p){
62099 if( (p->flags & (MEM_Str|MEM_Blob))!=0 && p->n>sqlite3_max_blobsize ){
62100 sqlite3_max_blobsize = p->n;
62103 #endif
62106 ** The next global variable is incremented each type the OP_Found opcode
62107 ** is executed. This is used to test whether or not the foreign key
62108 ** operation implemented using OP_FkIsZero is working. This variable
62109 ** has no function other than to help verify the correct operation of the
62110 ** library.
62112 #ifdef SQLITE_TEST
62113 SQLITE_API int sqlite3_found_count = 0;
62114 #endif
62117 ** Test a register to see if it exceeds the current maximum blob size.
62118 ** If it does, record the new maximum blob size.
62120 #if defined(SQLITE_TEST) && !defined(SQLITE_OMIT_BUILTIN_TEST)
62121 # define UPDATE_MAX_BLOBSIZE(P) updateMaxBlobsize(P)
62122 #else
62123 # define UPDATE_MAX_BLOBSIZE(P)
62124 #endif
62127 ** Convert the given register into a string if it isn't one
62128 ** already. Return non-zero if a malloc() fails.
62130 #define Stringify(P, enc) \
62131 if(((P)->flags&(MEM_Str|MEM_Blob))==0 && sqlite3VdbeMemStringify(P,enc)) \
62132 { goto no_mem; }
62135 ** An ephemeral string value (signified by the MEM_Ephem flag) contains
62136 ** a pointer to a dynamically allocated string where some other entity
62137 ** is responsible for deallocating that string. Because the register
62138 ** does not control the string, it might be deleted without the register
62139 ** knowing it.
62141 ** This routine converts an ephemeral string into a dynamically allocated
62142 ** string that the register itself controls. In other words, it
62143 ** converts an MEM_Ephem string into an MEM_Dyn string.
62145 #define Deephemeralize(P) \
62146 if( ((P)->flags&MEM_Ephem)!=0 \
62147 && sqlite3VdbeMemMakeWriteable(P) ){ goto no_mem;}
62150 ** Call sqlite3VdbeMemExpandBlob() on the supplied value (type Mem*)
62151 ** P if required.
62153 #define ExpandBlob(P) (((P)->flags&MEM_Zero)?sqlite3VdbeMemExpandBlob(P):0)
62156 ** Argument pMem points at a register that will be passed to a
62157 ** user-defined function or returned to the user as the result of a query.
62158 ** This routine sets the pMem->type variable used by the sqlite3_value_*()
62159 ** routines.
62161 SQLITE_PRIVATE void sqlite3VdbeMemStoreType(Mem *pMem){
62162 int flags = pMem->flags;
62163 if( flags & MEM_Null ){
62164 pMem->type = SQLITE_NULL;
62166 else if( flags & MEM_Int ){
62167 pMem->type = SQLITE_INTEGER;
62169 else if( flags & MEM_Real ){
62170 pMem->type = SQLITE_FLOAT;
62172 else if( flags & MEM_Str ){
62173 pMem->type = SQLITE_TEXT;
62174 }else{
62175 pMem->type = SQLITE_BLOB;
62180 ** Allocate VdbeCursor number iCur. Return a pointer to it. Return NULL
62181 ** if we run out of memory.
62183 static VdbeCursor *allocateCursor(
62184 Vdbe *p, /* The virtual machine */
62185 int iCur, /* Index of the new VdbeCursor */
62186 int nField, /* Number of fields in the table or index */
62187 int iDb, /* When database the cursor belongs to, or -1 */
62188 int isBtreeCursor /* True for B-Tree. False for pseudo-table or vtab */
62190 /* Find the memory cell that will be used to store the blob of memory
62191 ** required for this VdbeCursor structure. It is convenient to use a
62192 ** vdbe memory cell to manage the memory allocation required for a
62193 ** VdbeCursor structure for the following reasons:
62195 ** * Sometimes cursor numbers are used for a couple of different
62196 ** purposes in a vdbe program. The different uses might require
62197 ** different sized allocations. Memory cells provide growable
62198 ** allocations.
62200 ** * When using ENABLE_MEMORY_MANAGEMENT, memory cell buffers can
62201 ** be freed lazily via the sqlite3_release_memory() API. This
62202 ** minimizes the number of malloc calls made by the system.
62204 ** Memory cells for cursors are allocated at the top of the address
62205 ** space. Memory cell (p->nMem) corresponds to cursor 0. Space for
62206 ** cursor 1 is managed by memory cell (p->nMem-1), etc.
62208 Mem *pMem = &p->aMem[p->nMem-iCur];
62210 int nByte;
62211 VdbeCursor *pCx = 0;
62212 nByte =
62213 ROUND8(sizeof(VdbeCursor)) +
62214 (isBtreeCursor?sqlite3BtreeCursorSize():0) +
62215 2*nField*sizeof(u32);
62217 assert( iCur<p->nCursor );
62218 if( p->apCsr[iCur] ){
62219 sqlite3VdbeFreeCursor(p, p->apCsr[iCur]);
62220 p->apCsr[iCur] = 0;
62222 if( SQLITE_OK==sqlite3VdbeMemGrow(pMem, nByte, 0) ){
62223 p->apCsr[iCur] = pCx = (VdbeCursor*)pMem->z;
62224 memset(pCx, 0, sizeof(VdbeCursor));
62225 pCx->iDb = iDb;
62226 pCx->nField = nField;
62227 if( nField ){
62228 pCx->aType = (u32 *)&pMem->z[ROUND8(sizeof(VdbeCursor))];
62230 if( isBtreeCursor ){
62231 pCx->pCursor = (BtCursor*)
62232 &pMem->z[ROUND8(sizeof(VdbeCursor))+2*nField*sizeof(u32)];
62233 sqlite3BtreeCursorZero(pCx->pCursor);
62236 return pCx;
62240 ** Try to convert a value into a numeric representation if we can
62241 ** do so without loss of information. In other words, if the string
62242 ** looks like a number, convert it into a number. If it does not
62243 ** look like a number, leave it alone.
62245 static void applyNumericAffinity(Mem *pRec){
62246 if( (pRec->flags & (MEM_Real|MEM_Int))==0 ){
62247 double rValue;
62248 i64 iValue;
62249 u8 enc = pRec->enc;
62250 if( (pRec->flags&MEM_Str)==0 ) return;
62251 if( sqlite3AtoF(pRec->z, &rValue, pRec->n, enc)==0 ) return;
62252 if( 0==sqlite3Atoi64(pRec->z, &iValue, pRec->n, enc) ){
62253 pRec->u.i = iValue;
62254 pRec->flags |= MEM_Int;
62255 }else{
62256 pRec->r = rValue;
62257 pRec->flags |= MEM_Real;
62263 ** Processing is determine by the affinity parameter:
62265 ** SQLITE_AFF_INTEGER:
62266 ** SQLITE_AFF_REAL:
62267 ** SQLITE_AFF_NUMERIC:
62268 ** Try to convert pRec to an integer representation or a
62269 ** floating-point representation if an integer representation
62270 ** is not possible. Note that the integer representation is
62271 ** always preferred, even if the affinity is REAL, because
62272 ** an integer representation is more space efficient on disk.
62274 ** SQLITE_AFF_TEXT:
62275 ** Convert pRec to a text representation.
62277 ** SQLITE_AFF_NONE:
62278 ** No-op. pRec is unchanged.
62280 static void applyAffinity(
62281 Mem *pRec, /* The value to apply affinity to */
62282 char affinity, /* The affinity to be applied */
62283 u8 enc /* Use this text encoding */
62285 if( affinity==SQLITE_AFF_TEXT ){
62286 /* Only attempt the conversion to TEXT if there is an integer or real
62287 ** representation (blob and NULL do not get converted) but no string
62288 ** representation.
62290 if( 0==(pRec->flags&MEM_Str) && (pRec->flags&(MEM_Real|MEM_Int)) ){
62291 sqlite3VdbeMemStringify(pRec, enc);
62293 pRec->flags &= ~(MEM_Real|MEM_Int);
62294 }else if( affinity!=SQLITE_AFF_NONE ){
62295 assert( affinity==SQLITE_AFF_INTEGER || affinity==SQLITE_AFF_REAL
62296 || affinity==SQLITE_AFF_NUMERIC );
62297 applyNumericAffinity(pRec);
62298 if( pRec->flags & MEM_Real ){
62299 sqlite3VdbeIntegerAffinity(pRec);
62305 ** Try to convert the type of a function argument or a result column
62306 ** into a numeric representation. Use either INTEGER or REAL whichever
62307 ** is appropriate. But only do the conversion if it is possible without
62308 ** loss of information and return the revised type of the argument.
62310 SQLITE_API int sqlite3_value_numeric_type(sqlite3_value *pVal){
62311 Mem *pMem = (Mem*)pVal;
62312 if( pMem->type==SQLITE_TEXT ){
62313 applyNumericAffinity(pMem);
62314 sqlite3VdbeMemStoreType(pMem);
62316 return pMem->type;
62320 ** Exported version of applyAffinity(). This one works on sqlite3_value*,
62321 ** not the internal Mem* type.
62323 SQLITE_PRIVATE void sqlite3ValueApplyAffinity(
62324 sqlite3_value *pVal,
62325 u8 affinity,
62326 u8 enc
62328 applyAffinity((Mem *)pVal, affinity, enc);
62331 #ifdef SQLITE_DEBUG
62333 ** Write a nice string representation of the contents of cell pMem
62334 ** into buffer zBuf, length nBuf.
62336 SQLITE_PRIVATE void sqlite3VdbeMemPrettyPrint(Mem *pMem, char *zBuf){
62337 char *zCsr = zBuf;
62338 int f = pMem->flags;
62340 static const char *const encnames[] = {"(X)", "(8)", "(16LE)", "(16BE)"};
62342 if( f&MEM_Blob ){
62343 int i;
62344 char c;
62345 if( f & MEM_Dyn ){
62346 c = 'z';
62347 assert( (f & (MEM_Static|MEM_Ephem))==0 );
62348 }else if( f & MEM_Static ){
62349 c = 't';
62350 assert( (f & (MEM_Dyn|MEM_Ephem))==0 );
62351 }else if( f & MEM_Ephem ){
62352 c = 'e';
62353 assert( (f & (MEM_Static|MEM_Dyn))==0 );
62354 }else{
62355 c = 's';
62358 sqlite3_snprintf(100, zCsr, "%c", c);
62359 zCsr += sqlite3Strlen30(zCsr);
62360 sqlite3_snprintf(100, zCsr, "%d[", pMem->n);
62361 zCsr += sqlite3Strlen30(zCsr);
62362 for(i=0; i<16 && i<pMem->n; i++){
62363 sqlite3_snprintf(100, zCsr, "%02X", ((int)pMem->z[i] & 0xFF));
62364 zCsr += sqlite3Strlen30(zCsr);
62366 for(i=0; i<16 && i<pMem->n; i++){
62367 char z = pMem->z[i];
62368 if( z<32 || z>126 ) *zCsr++ = '.';
62369 else *zCsr++ = z;
62372 sqlite3_snprintf(100, zCsr, "]%s", encnames[pMem->enc]);
62373 zCsr += sqlite3Strlen30(zCsr);
62374 if( f & MEM_Zero ){
62375 sqlite3_snprintf(100, zCsr,"+%dz",pMem->u.nZero);
62376 zCsr += sqlite3Strlen30(zCsr);
62378 *zCsr = '\0';
62379 }else if( f & MEM_Str ){
62380 int j, k;
62381 zBuf[0] = ' ';
62382 if( f & MEM_Dyn ){
62383 zBuf[1] = 'z';
62384 assert( (f & (MEM_Static|MEM_Ephem))==0 );
62385 }else if( f & MEM_Static ){
62386 zBuf[1] = 't';
62387 assert( (f & (MEM_Dyn|MEM_Ephem))==0 );
62388 }else if( f & MEM_Ephem ){
62389 zBuf[1] = 'e';
62390 assert( (f & (MEM_Static|MEM_Dyn))==0 );
62391 }else{
62392 zBuf[1] = 's';
62394 k = 2;
62395 sqlite3_snprintf(100, &zBuf[k], "%d", pMem->n);
62396 k += sqlite3Strlen30(&zBuf[k]);
62397 zBuf[k++] = '[';
62398 for(j=0; j<15 && j<pMem->n; j++){
62399 u8 c = pMem->z[j];
62400 if( c>=0x20 && c<0x7f ){
62401 zBuf[k++] = c;
62402 }else{
62403 zBuf[k++] = '.';
62406 zBuf[k++] = ']';
62407 sqlite3_snprintf(100,&zBuf[k], encnames[pMem->enc]);
62408 k += sqlite3Strlen30(&zBuf[k]);
62409 zBuf[k++] = 0;
62412 #endif
62414 #ifdef SQLITE_DEBUG
62416 ** Print the value of a register for tracing purposes:
62418 static void memTracePrint(FILE *out, Mem *p){
62419 if( p->flags & MEM_Null ){
62420 fprintf(out, " NULL");
62421 }else if( (p->flags & (MEM_Int|MEM_Str))==(MEM_Int|MEM_Str) ){
62422 fprintf(out, " si:%lld", p->u.i);
62423 }else if( p->flags & MEM_Int ){
62424 fprintf(out, " i:%lld", p->u.i);
62425 #ifndef SQLITE_OMIT_FLOATING_POINT
62426 }else if( p->flags & MEM_Real ){
62427 fprintf(out, " r:%g", p->r);
62428 #endif
62429 }else if( p->flags & MEM_RowSet ){
62430 fprintf(out, " (rowset)");
62431 }else{
62432 char zBuf[200];
62433 sqlite3VdbeMemPrettyPrint(p, zBuf);
62434 fprintf(out, " ");
62435 fprintf(out, "%s", zBuf);
62438 static void registerTrace(FILE *out, int iReg, Mem *p){
62439 fprintf(out, "REG[%d] = ", iReg);
62440 memTracePrint(out, p);
62441 fprintf(out, "\n");
62443 #endif
62445 #ifdef SQLITE_DEBUG
62446 # define REGISTER_TRACE(R,M) if(p->trace)registerTrace(p->trace,R,M)
62447 #else
62448 # define REGISTER_TRACE(R,M)
62449 #endif
62452 #ifdef VDBE_PROFILE
62455 ** hwtime.h contains inline assembler code for implementing
62456 ** high-performance timing routines.
62458 /************** Include hwtime.h in the middle of vdbe.c *********************/
62459 /************** Begin file hwtime.h ******************************************/
62461 ** 2008 May 27
62463 ** The author disclaims copyright to this source code. In place of
62464 ** a legal notice, here is a blessing:
62466 ** May you do good and not evil.
62467 ** May you find forgiveness for yourself and forgive others.
62468 ** May you share freely, never taking more than you give.
62470 ******************************************************************************
62472 ** This file contains inline asm code for retrieving "high-performance"
62473 ** counters for x86 class CPUs.
62475 #ifndef _HWTIME_H_
62476 #define _HWTIME_H_
62479 ** The following routine only works on pentium-class (or newer) processors.
62480 ** It uses the RDTSC opcode to read the cycle count value out of the
62481 ** processor and returns that value. This can be used for high-res
62482 ** profiling.
62484 #if (defined(__GNUC__) || defined(_MSC_VER)) && \
62485 (defined(i386) || defined(__i386__) || defined(_M_IX86))
62487 #if defined(__GNUC__)
62489 __inline__ sqlite_uint64 sqlite3Hwtime(void){
62490 unsigned int lo, hi;
62491 __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
62492 return (sqlite_uint64)hi << 32 | lo;
62495 #elif defined(_MSC_VER)
62497 __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
62498 __asm {
62499 rdtsc
62500 ret ; return value at EDX:EAX
62504 #endif
62506 #elif (defined(__GNUC__) && defined(__x86_64__))
62508 __inline__ sqlite_uint64 sqlite3Hwtime(void){
62509 unsigned long val;
62510 __asm__ __volatile__ ("rdtsc" : "=A" (val));
62511 return val;
62514 #elif (defined(__GNUC__) && defined(__ppc__))
62516 __inline__ sqlite_uint64 sqlite3Hwtime(void){
62517 unsigned long long retval;
62518 unsigned long junk;
62519 __asm__ __volatile__ ("\n\
62520 1: mftbu %1\n\
62521 mftb %L0\n\
62522 mftbu %0\n\
62523 cmpw %0,%1\n\
62524 bne 1b"
62525 : "=r" (retval), "=r" (junk));
62526 return retval;
62529 #else
62531 #error Need implementation of sqlite3Hwtime() for your platform.
62534 ** To compile without implementing sqlite3Hwtime() for your platform,
62535 ** you can remove the above #error and use the following
62536 ** stub function. You will lose timing support for many
62537 ** of the debugging and testing utilities, but it should at
62538 ** least compile and run.
62540 SQLITE_PRIVATE sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
62542 #endif
62544 #endif /* !defined(_HWTIME_H_) */
62546 /************** End of hwtime.h **********************************************/
62547 /************** Continuing where we left off in vdbe.c ***********************/
62549 #endif
62552 ** The CHECK_FOR_INTERRUPT macro defined here looks to see if the
62553 ** sqlite3_interrupt() routine has been called. If it has been, then
62554 ** processing of the VDBE program is interrupted.
62556 ** This macro added to every instruction that does a jump in order to
62557 ** implement a loop. This test used to be on every single instruction,
62558 ** but that meant we more testing that we needed. By only testing the
62559 ** flag on jump instructions, we get a (small) speed improvement.
62561 #define CHECK_FOR_INTERRUPT \
62562 if( db->u1.isInterrupted ) goto abort_due_to_interrupt;
62565 #ifndef NDEBUG
62567 ** This function is only called from within an assert() expression. It
62568 ** checks that the sqlite3.nTransaction variable is correctly set to
62569 ** the number of non-transaction savepoints currently in the
62570 ** linked list starting at sqlite3.pSavepoint.
62572 ** Usage:
62574 ** assert( checkSavepointCount(db) );
62576 static int checkSavepointCount(sqlite3 *db){
62577 int n = 0;
62578 Savepoint *p;
62579 for(p=db->pSavepoint; p; p=p->pNext) n++;
62580 assert( n==(db->nSavepoint + db->isTransactionSavepoint) );
62581 return 1;
62583 #endif
62586 ** Transfer error message text from an sqlite3_vtab.zErrMsg (text stored
62587 ** in memory obtained from sqlite3_malloc) into a Vdbe.zErrMsg (text stored
62588 ** in memory obtained from sqlite3DbMalloc).
62590 static void importVtabErrMsg(Vdbe *p, sqlite3_vtab *pVtab){
62591 sqlite3 *db = p->db;
62592 sqlite3DbFree(db, p->zErrMsg);
62593 p->zErrMsg = sqlite3DbStrDup(db, pVtab->zErrMsg);
62594 sqlite3_free(pVtab->zErrMsg);
62595 pVtab->zErrMsg = 0;
62600 ** Execute as much of a VDBE program as we can then return.
62602 ** sqlite3VdbeMakeReady() must be called before this routine in order to
62603 ** close the program with a final OP_Halt and to set up the callbacks
62604 ** and the error message pointer.
62606 ** Whenever a row or result data is available, this routine will either
62607 ** invoke the result callback (if there is one) or return with
62608 ** SQLITE_ROW.
62610 ** If an attempt is made to open a locked database, then this routine
62611 ** will either invoke the busy callback (if there is one) or it will
62612 ** return SQLITE_BUSY.
62614 ** If an error occurs, an error message is written to memory obtained
62615 ** from sqlite3_malloc() and p->zErrMsg is made to point to that memory.
62616 ** The error code is stored in p->rc and this routine returns SQLITE_ERROR.
62618 ** If the callback ever returns non-zero, then the program exits
62619 ** immediately. There will be no error message but the p->rc field is
62620 ** set to SQLITE_ABORT and this routine will return SQLITE_ERROR.
62622 ** A memory allocation error causes p->rc to be set to SQLITE_NOMEM and this
62623 ** routine to return SQLITE_ERROR.
62625 ** Other fatal errors return SQLITE_ERROR.
62627 ** After this routine has finished, sqlite3VdbeFinalize() should be
62628 ** used to clean up the mess that was left behind.
62630 SQLITE_PRIVATE int sqlite3VdbeExec(
62631 Vdbe *p /* The VDBE */
62633 int pc=0; /* The program counter */
62634 Op *aOp = p->aOp; /* Copy of p->aOp */
62635 Op *pOp; /* Current operation */
62636 int rc = SQLITE_OK; /* Value to return */
62637 sqlite3 *db = p->db; /* The database */
62638 u8 resetSchemaOnFault = 0; /* Reset schema after an error if positive */
62639 u8 encoding = ENC(db); /* The database encoding */
62640 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
62641 int checkProgress; /* True if progress callbacks are enabled */
62642 int nProgressOps = 0; /* Opcodes executed since progress callback. */
62643 #endif
62644 Mem *aMem = p->aMem; /* Copy of p->aMem */
62645 Mem *pIn1 = 0; /* 1st input operand */
62646 Mem *pIn2 = 0; /* 2nd input operand */
62647 Mem *pIn3 = 0; /* 3rd input operand */
62648 Mem *pOut = 0; /* Output operand */
62649 int iCompare = 0; /* Result of last OP_Compare operation */
62650 int *aPermute = 0; /* Permutation of columns for OP_Compare */
62651 #ifdef VDBE_PROFILE
62652 u64 start; /* CPU clock count at start of opcode */
62653 int origPc; /* Program counter at start of opcode */
62654 #endif
62655 /********************************************************************
62656 ** Automatically generated code
62658 ** The following union is automatically generated by the
62659 ** vdbe-compress.tcl script. The purpose of this union is to
62660 ** reduce the amount of stack space required by this function.
62661 ** See comments in the vdbe-compress.tcl script for details.
62663 union vdbeExecUnion {
62664 struct OP_Yield_stack_vars {
62665 int pcDest;
62666 } aa;
62667 struct OP_Variable_stack_vars {
62668 Mem *pVar; /* Value being transferred */
62669 } ab;
62670 struct OP_Move_stack_vars {
62671 char *zMalloc; /* Holding variable for allocated memory */
62672 int n; /* Number of registers left to copy */
62673 int p1; /* Register to copy from */
62674 int p2; /* Register to copy to */
62675 } ac;
62676 struct OP_ResultRow_stack_vars {
62677 Mem *pMem;
62678 int i;
62679 } ad;
62680 struct OP_Concat_stack_vars {
62681 i64 nByte;
62682 } ae;
62683 struct OP_Remainder_stack_vars {
62684 int flags; /* Combined MEM_* flags from both inputs */
62685 i64 iA; /* Integer value of left operand */
62686 i64 iB; /* Integer value of right operand */
62687 double rA; /* Real value of left operand */
62688 double rB; /* Real value of right operand */
62689 } af;
62690 struct OP_Function_stack_vars {
62691 int i;
62692 Mem *pArg;
62693 sqlite3_context ctx;
62694 sqlite3_value **apVal;
62695 int n;
62696 } ag;
62697 struct OP_ShiftRight_stack_vars {
62698 i64 iA;
62699 u64 uA;
62700 i64 iB;
62701 u8 op;
62702 } ah;
62703 struct OP_Ge_stack_vars {
62704 int res; /* Result of the comparison of pIn1 against pIn3 */
62705 char affinity; /* Affinity to use for comparison */
62706 u16 flags1; /* Copy of initial value of pIn1->flags */
62707 u16 flags3; /* Copy of initial value of pIn3->flags */
62708 } ai;
62709 struct OP_Compare_stack_vars {
62710 int n;
62711 int i;
62712 int p1;
62713 int p2;
62714 const KeyInfo *pKeyInfo;
62715 int idx;
62716 CollSeq *pColl; /* Collating sequence to use on this term */
62717 int bRev; /* True for DESCENDING sort order */
62718 } aj;
62719 struct OP_Or_stack_vars {
62720 int v1; /* Left operand: 0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */
62721 int v2; /* Right operand: 0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */
62722 } ak;
62723 struct OP_IfNot_stack_vars {
62724 int c;
62725 } al;
62726 struct OP_Column_stack_vars {
62727 u32 payloadSize; /* Number of bytes in the record */
62728 i64 payloadSize64; /* Number of bytes in the record */
62729 int p1; /* P1 value of the opcode */
62730 int p2; /* column number to retrieve */
62731 VdbeCursor *pC; /* The VDBE cursor */
62732 char *zRec; /* Pointer to complete record-data */
62733 BtCursor *pCrsr; /* The BTree cursor */
62734 u32 *aType; /* aType[i] holds the numeric type of the i-th column */
62735 u32 *aOffset; /* aOffset[i] is offset to start of data for i-th column */
62736 int nField; /* number of fields in the record */
62737 int len; /* The length of the serialized data for the column */
62738 int i; /* Loop counter */
62739 char *zData; /* Part of the record being decoded */
62740 Mem *pDest; /* Where to write the extracted value */
62741 Mem sMem; /* For storing the record being decoded */
62742 u8 *zIdx; /* Index into header */
62743 u8 *zEndHdr; /* Pointer to first byte after the header */
62744 u32 offset; /* Offset into the data */
62745 u32 szField; /* Number of bytes in the content of a field */
62746 int szHdr; /* Size of the header size field at start of record */
62747 int avail; /* Number of bytes of available data */
62748 Mem *pReg; /* PseudoTable input register */
62749 } am;
62750 struct OP_Affinity_stack_vars {
62751 const char *zAffinity; /* The affinity to be applied */
62752 char cAff; /* A single character of affinity */
62753 } an;
62754 struct OP_MakeRecord_stack_vars {
62755 u8 *zNewRecord; /* A buffer to hold the data for the new record */
62756 Mem *pRec; /* The new record */
62757 u64 nData; /* Number of bytes of data space */
62758 int nHdr; /* Number of bytes of header space */
62759 i64 nByte; /* Data space required for this record */
62760 int nZero; /* Number of zero bytes at the end of the record */
62761 int nVarint; /* Number of bytes in a varint */
62762 u32 serial_type; /* Type field */
62763 Mem *pData0; /* First field to be combined into the record */
62764 Mem *pLast; /* Last field of the record */
62765 int nField; /* Number of fields in the record */
62766 char *zAffinity; /* The affinity string for the record */
62767 int file_format; /* File format to use for encoding */
62768 int i; /* Space used in zNewRecord[] */
62769 int len; /* Length of a field */
62770 } ao;
62771 struct OP_Count_stack_vars {
62772 i64 nEntry;
62773 BtCursor *pCrsr;
62774 } ap;
62775 struct OP_Savepoint_stack_vars {
62776 int p1; /* Value of P1 operand */
62777 char *zName; /* Name of savepoint */
62778 int nName;
62779 Savepoint *pNew;
62780 Savepoint *pSavepoint;
62781 Savepoint *pTmp;
62782 int iSavepoint;
62783 int ii;
62784 } aq;
62785 struct OP_AutoCommit_stack_vars {
62786 int desiredAutoCommit;
62787 int iRollback;
62788 int turnOnAC;
62789 } ar;
62790 struct OP_Transaction_stack_vars {
62791 Btree *pBt;
62792 } as;
62793 struct OP_ReadCookie_stack_vars {
62794 int iMeta;
62795 int iDb;
62796 int iCookie;
62797 } at;
62798 struct OP_SetCookie_stack_vars {
62799 Db *pDb;
62800 } au;
62801 struct OP_VerifyCookie_stack_vars {
62802 int iMeta;
62803 int iGen;
62804 Btree *pBt;
62805 } av;
62806 struct OP_OpenWrite_stack_vars {
62807 int nField;
62808 KeyInfo *pKeyInfo;
62809 int p2;
62810 int iDb;
62811 int wrFlag;
62812 Btree *pX;
62813 VdbeCursor *pCur;
62814 Db *pDb;
62815 } aw;
62816 struct OP_OpenEphemeral_stack_vars {
62817 VdbeCursor *pCx;
62818 } ax;
62819 struct OP_OpenPseudo_stack_vars {
62820 VdbeCursor *pCx;
62821 } ay;
62822 struct OP_SeekGt_stack_vars {
62823 int res;
62824 int oc;
62825 VdbeCursor *pC;
62826 UnpackedRecord r;
62827 int nField;
62828 i64 iKey; /* The rowid we are to seek to */
62829 } az;
62830 struct OP_Seek_stack_vars {
62831 VdbeCursor *pC;
62832 } ba;
62833 struct OP_Found_stack_vars {
62834 int alreadyExists;
62835 VdbeCursor *pC;
62836 int res;
62837 UnpackedRecord *pIdxKey;
62838 UnpackedRecord r;
62839 char aTempRec[ROUND8(sizeof(UnpackedRecord)) + sizeof(Mem)*3 + 7];
62840 } bb;
62841 struct OP_IsUnique_stack_vars {
62842 u16 ii;
62843 VdbeCursor *pCx;
62844 BtCursor *pCrsr;
62845 u16 nField;
62846 Mem *aMx;
62847 UnpackedRecord r; /* B-Tree index search key */
62848 i64 R; /* Rowid stored in register P3 */
62849 } bc;
62850 struct OP_NotExists_stack_vars {
62851 VdbeCursor *pC;
62852 BtCursor *pCrsr;
62853 int res;
62854 u64 iKey;
62855 } bd;
62856 struct OP_NewRowid_stack_vars {
62857 i64 v; /* The new rowid */
62858 VdbeCursor *pC; /* Cursor of table to get the new rowid */
62859 int res; /* Result of an sqlite3BtreeLast() */
62860 int cnt; /* Counter to limit the number of searches */
62861 Mem *pMem; /* Register holding largest rowid for AUTOINCREMENT */
62862 VdbeFrame *pFrame; /* Root frame of VDBE */
62863 } be;
62864 struct OP_InsertInt_stack_vars {
62865 Mem *pData; /* MEM cell holding data for the record to be inserted */
62866 Mem *pKey; /* MEM cell holding key for the record */
62867 i64 iKey; /* The integer ROWID or key for the record to be inserted */
62868 VdbeCursor *pC; /* Cursor to table into which insert is written */
62869 int nZero; /* Number of zero-bytes to append */
62870 int seekResult; /* Result of prior seek or 0 if no USESEEKRESULT flag */
62871 const char *zDb; /* database name - used by the update hook */
62872 const char *zTbl; /* Table name - used by the opdate hook */
62873 int op; /* Opcode for update hook: SQLITE_UPDATE or SQLITE_INSERT */
62874 } bf;
62875 struct OP_Delete_stack_vars {
62876 i64 iKey;
62877 VdbeCursor *pC;
62878 } bg;
62879 struct OP_RowData_stack_vars {
62880 VdbeCursor *pC;
62881 BtCursor *pCrsr;
62882 u32 n;
62883 i64 n64;
62884 } bh;
62885 struct OP_Rowid_stack_vars {
62886 VdbeCursor *pC;
62887 i64 v;
62888 sqlite3_vtab *pVtab;
62889 const sqlite3_module *pModule;
62890 } bi;
62891 struct OP_NullRow_stack_vars {
62892 VdbeCursor *pC;
62893 } bj;
62894 struct OP_Last_stack_vars {
62895 VdbeCursor *pC;
62896 BtCursor *pCrsr;
62897 int res;
62898 } bk;
62899 struct OP_Rewind_stack_vars {
62900 VdbeCursor *pC;
62901 BtCursor *pCrsr;
62902 int res;
62903 } bl;
62904 struct OP_Next_stack_vars {
62905 VdbeCursor *pC;
62906 BtCursor *pCrsr;
62907 int res;
62908 } bm;
62909 struct OP_IdxInsert_stack_vars {
62910 VdbeCursor *pC;
62911 BtCursor *pCrsr;
62912 int nKey;
62913 const char *zKey;
62914 } bn;
62915 struct OP_IdxDelete_stack_vars {
62916 VdbeCursor *pC;
62917 BtCursor *pCrsr;
62918 int res;
62919 UnpackedRecord r;
62920 } bo;
62921 struct OP_IdxRowid_stack_vars {
62922 BtCursor *pCrsr;
62923 VdbeCursor *pC;
62924 i64 rowid;
62925 } bp;
62926 struct OP_IdxGE_stack_vars {
62927 VdbeCursor *pC;
62928 int res;
62929 UnpackedRecord r;
62930 } bq;
62931 struct OP_Destroy_stack_vars {
62932 int iMoved;
62933 int iCnt;
62934 Vdbe *pVdbe;
62935 int iDb;
62936 } br;
62937 struct OP_Clear_stack_vars {
62938 int nChange;
62939 } bs;
62940 struct OP_CreateTable_stack_vars {
62941 int pgno;
62942 int flags;
62943 Db *pDb;
62944 } bt;
62945 struct OP_ParseSchema_stack_vars {
62946 int iDb;
62947 const char *zMaster;
62948 char *zSql;
62949 InitData initData;
62950 } bu;
62951 struct OP_IntegrityCk_stack_vars {
62952 int nRoot; /* Number of tables to check. (Number of root pages.) */
62953 int *aRoot; /* Array of rootpage numbers for tables to be checked */
62954 int j; /* Loop counter */
62955 int nErr; /* Number of errors reported */
62956 char *z; /* Text of the error report */
62957 Mem *pnErr; /* Register keeping track of errors remaining */
62958 } bv;
62959 struct OP_RowSetRead_stack_vars {
62960 i64 val;
62961 } bw;
62962 struct OP_RowSetTest_stack_vars {
62963 int iSet;
62964 int exists;
62965 } bx;
62966 struct OP_Program_stack_vars {
62967 int nMem; /* Number of memory registers for sub-program */
62968 int nByte; /* Bytes of runtime space required for sub-program */
62969 Mem *pRt; /* Register to allocate runtime space */
62970 Mem *pMem; /* Used to iterate through memory cells */
62971 Mem *pEnd; /* Last memory cell in new array */
62972 VdbeFrame *pFrame; /* New vdbe frame to execute in */
62973 SubProgram *pProgram; /* Sub-program to execute */
62974 void *t; /* Token identifying trigger */
62975 } by;
62976 struct OP_Param_stack_vars {
62977 VdbeFrame *pFrame;
62978 Mem *pIn;
62979 } bz;
62980 struct OP_MemMax_stack_vars {
62981 Mem *pIn1;
62982 VdbeFrame *pFrame;
62983 } ca;
62984 struct OP_AggStep_stack_vars {
62985 int n;
62986 int i;
62987 Mem *pMem;
62988 Mem *pRec;
62989 sqlite3_context ctx;
62990 sqlite3_value **apVal;
62991 } cb;
62992 struct OP_AggFinal_stack_vars {
62993 Mem *pMem;
62994 } cc;
62995 struct OP_Checkpoint_stack_vars {
62996 int i; /* Loop counter */
62997 int aRes[3]; /* Results */
62998 Mem *pMem; /* Write results here */
62999 } cd;
63000 struct OP_JournalMode_stack_vars {
63001 Btree *pBt; /* Btree to change journal mode of */
63002 Pager *pPager; /* Pager associated with pBt */
63003 int eNew; /* New journal mode */
63004 int eOld; /* The old journal mode */
63005 const char *zFilename; /* Name of database file for pPager */
63006 } ce;
63007 struct OP_IncrVacuum_stack_vars {
63008 Btree *pBt;
63009 } cf;
63010 struct OP_VBegin_stack_vars {
63011 VTable *pVTab;
63012 } cg;
63013 struct OP_VOpen_stack_vars {
63014 VdbeCursor *pCur;
63015 sqlite3_vtab_cursor *pVtabCursor;
63016 sqlite3_vtab *pVtab;
63017 sqlite3_module *pModule;
63018 } ch;
63019 struct OP_VFilter_stack_vars {
63020 int nArg;
63021 int iQuery;
63022 const sqlite3_module *pModule;
63023 Mem *pQuery;
63024 Mem *pArgc;
63025 sqlite3_vtab_cursor *pVtabCursor;
63026 sqlite3_vtab *pVtab;
63027 VdbeCursor *pCur;
63028 int res;
63029 int i;
63030 Mem **apArg;
63031 } ci;
63032 struct OP_VColumn_stack_vars {
63033 sqlite3_vtab *pVtab;
63034 const sqlite3_module *pModule;
63035 Mem *pDest;
63036 sqlite3_context sContext;
63037 } cj;
63038 struct OP_VNext_stack_vars {
63039 sqlite3_vtab *pVtab;
63040 const sqlite3_module *pModule;
63041 int res;
63042 VdbeCursor *pCur;
63043 } ck;
63044 struct OP_VRename_stack_vars {
63045 sqlite3_vtab *pVtab;
63046 Mem *pName;
63047 } cl;
63048 struct OP_VUpdate_stack_vars {
63049 sqlite3_vtab *pVtab;
63050 sqlite3_module *pModule;
63051 int nArg;
63052 int i;
63053 sqlite_int64 rowid;
63054 Mem **apArg;
63055 Mem *pX;
63056 } cm;
63057 struct OP_Trace_stack_vars {
63058 char *zTrace;
63059 } cn;
63060 } u;
63061 /* End automatically generated code
63062 ********************************************************************/
63064 assert( p->magic==VDBE_MAGIC_RUN ); /* sqlite3_step() verifies this */
63065 sqlite3VdbeEnter(p);
63066 if( p->rc==SQLITE_NOMEM ){
63067 /* This happens if a malloc() inside a call to sqlite3_column_text() or
63068 ** sqlite3_column_text16() failed. */
63069 goto no_mem;
63071 assert( p->rc==SQLITE_OK || p->rc==SQLITE_BUSY );
63072 p->rc = SQLITE_OK;
63073 assert( p->explain==0 );
63074 p->pResultSet = 0;
63075 db->busyHandler.nBusy = 0;
63076 CHECK_FOR_INTERRUPT;
63077 sqlite3VdbeIOTraceSql(p);
63078 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
63079 checkProgress = db->xProgress!=0;
63080 #endif
63081 #ifdef SQLITE_DEBUG
63082 sqlite3BeginBenignMalloc();
63083 if( p->pc==0 && (p->db->flags & SQLITE_VdbeListing)!=0 ){
63084 int i;
63085 printf("VDBE Program Listing:\n");
63086 sqlite3VdbePrintSql(p);
63087 for(i=0; i<p->nOp; i++){
63088 sqlite3VdbePrintOp(stdout, i, &aOp[i]);
63091 sqlite3EndBenignMalloc();
63092 #endif
63093 for(pc=p->pc; rc==SQLITE_OK; pc++){
63094 assert( pc>=0 && pc<p->nOp );
63095 if( db->mallocFailed ) goto no_mem;
63096 #ifdef VDBE_PROFILE
63097 origPc = pc;
63098 start = sqlite3Hwtime();
63099 #endif
63100 pOp = &aOp[pc];
63102 /* Only allow tracing if SQLITE_DEBUG is defined.
63104 #ifdef SQLITE_DEBUG
63105 if( p->trace ){
63106 if( pc==0 ){
63107 printf("VDBE Execution Trace:\n");
63108 sqlite3VdbePrintSql(p);
63110 sqlite3VdbePrintOp(p->trace, pc, pOp);
63112 #endif
63115 /* Check to see if we need to simulate an interrupt. This only happens
63116 ** if we have a special test build.
63118 #ifdef SQLITE_TEST
63119 if( sqlite3_interrupt_count>0 ){
63120 sqlite3_interrupt_count--;
63121 if( sqlite3_interrupt_count==0 ){
63122 sqlite3_interrupt(db);
63125 #endif
63127 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
63128 /* Call the progress callback if it is configured and the required number
63129 ** of VDBE ops have been executed (either since this invocation of
63130 ** sqlite3VdbeExec() or since last time the progress callback was called).
63131 ** If the progress callback returns non-zero, exit the virtual machine with
63132 ** a return code SQLITE_ABORT.
63134 if( checkProgress ){
63135 if( db->nProgressOps==nProgressOps ){
63136 int prc;
63137 prc = db->xProgress(db->pProgressArg);
63138 if( prc!=0 ){
63139 rc = SQLITE_INTERRUPT;
63140 goto vdbe_error_halt;
63142 nProgressOps = 0;
63144 nProgressOps++;
63146 #endif
63148 /* On any opcode with the "out2-prerelase" tag, free any
63149 ** external allocations out of mem[p2] and set mem[p2] to be
63150 ** an undefined integer. Opcodes will either fill in the integer
63151 ** value or convert mem[p2] to a different type.
63153 assert( pOp->opflags==sqlite3OpcodeProperty[pOp->opcode] );
63154 if( pOp->opflags & OPFLG_OUT2_PRERELEASE ){
63155 assert( pOp->p2>0 );
63156 assert( pOp->p2<=p->nMem );
63157 pOut = &aMem[pOp->p2];
63158 memAboutToChange(p, pOut);
63159 sqlite3VdbeMemReleaseExternal(pOut);
63160 pOut->flags = MEM_Int;
63163 /* Sanity checking on other operands */
63164 #ifdef SQLITE_DEBUG
63165 if( (pOp->opflags & OPFLG_IN1)!=0 ){
63166 assert( pOp->p1>0 );
63167 assert( pOp->p1<=p->nMem );
63168 assert( memIsValid(&aMem[pOp->p1]) );
63169 REGISTER_TRACE(pOp->p1, &aMem[pOp->p1]);
63171 if( (pOp->opflags & OPFLG_IN2)!=0 ){
63172 assert( pOp->p2>0 );
63173 assert( pOp->p2<=p->nMem );
63174 assert( memIsValid(&aMem[pOp->p2]) );
63175 REGISTER_TRACE(pOp->p2, &aMem[pOp->p2]);
63177 if( (pOp->opflags & OPFLG_IN3)!=0 ){
63178 assert( pOp->p3>0 );
63179 assert( pOp->p3<=p->nMem );
63180 assert( memIsValid(&aMem[pOp->p3]) );
63181 REGISTER_TRACE(pOp->p3, &aMem[pOp->p3]);
63183 if( (pOp->opflags & OPFLG_OUT2)!=0 ){
63184 assert( pOp->p2>0 );
63185 assert( pOp->p2<=p->nMem );
63186 memAboutToChange(p, &aMem[pOp->p2]);
63188 if( (pOp->opflags & OPFLG_OUT3)!=0 ){
63189 assert( pOp->p3>0 );
63190 assert( pOp->p3<=p->nMem );
63191 memAboutToChange(p, &aMem[pOp->p3]);
63193 #endif
63195 switch( pOp->opcode ){
63197 /*****************************************************************************
63198 ** What follows is a massive switch statement where each case implements a
63199 ** separate instruction in the virtual machine. If we follow the usual
63200 ** indentation conventions, each case should be indented by 6 spaces. But
63201 ** that is a lot of wasted space on the left margin. So the code within
63202 ** the switch statement will break with convention and be flush-left. Another
63203 ** big comment (similar to this one) will mark the point in the code where
63204 ** we transition back to normal indentation.
63206 ** The formatting of each case is important. The makefile for SQLite
63207 ** generates two C files "opcodes.h" and "opcodes.c" by scanning this
63208 ** file looking for lines that begin with "case OP_". The opcodes.h files
63209 ** will be filled with #defines that give unique integer values to each
63210 ** opcode and the opcodes.c file is filled with an array of strings where
63211 ** each string is the symbolic name for the corresponding opcode. If the
63212 ** case statement is followed by a comment of the form "/# same as ... #/"
63213 ** that comment is used to determine the particular value of the opcode.
63215 ** Other keywords in the comment that follows each case are used to
63216 ** construct the OPFLG_INITIALIZER value that initializes opcodeProperty[].
63217 ** Keywords include: in1, in2, in3, out2_prerelease, out2, out3. See
63218 ** the mkopcodeh.awk script for additional information.
63220 ** Documentation about VDBE opcodes is generated by scanning this file
63221 ** for lines of that contain "Opcode:". That line and all subsequent
63222 ** comment lines are used in the generation of the opcode.html documentation
63223 ** file.
63225 ** SUMMARY:
63227 ** Formatting is important to scripts that scan this file.
63228 ** Do not deviate from the formatting style currently in use.
63230 *****************************************************************************/
63232 /* Opcode: Goto * P2 * * *
63234 ** An unconditional jump to address P2.
63235 ** The next instruction executed will be
63236 ** the one at index P2 from the beginning of
63237 ** the program.
63239 case OP_Goto: { /* jump */
63240 CHECK_FOR_INTERRUPT;
63241 pc = pOp->p2 - 1;
63242 break;
63245 /* Opcode: Gosub P1 P2 * * *
63247 ** Write the current address onto register P1
63248 ** and then jump to address P2.
63250 case OP_Gosub: { /* jump, in1 */
63251 pIn1 = &aMem[pOp->p1];
63252 assert( (pIn1->flags & MEM_Dyn)==0 );
63253 memAboutToChange(p, pIn1);
63254 pIn1->flags = MEM_Int;
63255 pIn1->u.i = pc;
63256 REGISTER_TRACE(pOp->p1, pIn1);
63257 pc = pOp->p2 - 1;
63258 break;
63261 /* Opcode: Return P1 * * * *
63263 ** Jump to the next instruction after the address in register P1.
63265 case OP_Return: { /* in1 */
63266 pIn1 = &aMem[pOp->p1];
63267 assert( pIn1->flags & MEM_Int );
63268 pc = (int)pIn1->u.i;
63269 break;
63272 /* Opcode: Yield P1 * * * *
63274 ** Swap the program counter with the value in register P1.
63276 case OP_Yield: { /* in1 */
63277 #if 0 /* local variables moved into u.aa */
63278 int pcDest;
63279 #endif /* local variables moved into u.aa */
63280 pIn1 = &aMem[pOp->p1];
63281 assert( (pIn1->flags & MEM_Dyn)==0 );
63282 pIn1->flags = MEM_Int;
63283 u.aa.pcDest = (int)pIn1->u.i;
63284 pIn1->u.i = pc;
63285 REGISTER_TRACE(pOp->p1, pIn1);
63286 pc = u.aa.pcDest;
63287 break;
63290 /* Opcode: HaltIfNull P1 P2 P3 P4 *
63292 ** Check the value in register P3. If is is NULL then Halt using
63293 ** parameter P1, P2, and P4 as if this were a Halt instruction. If the
63294 ** value in register P3 is not NULL, then this routine is a no-op.
63296 case OP_HaltIfNull: { /* in3 */
63297 pIn3 = &aMem[pOp->p3];
63298 if( (pIn3->flags & MEM_Null)==0 ) break;
63299 /* Fall through into OP_Halt */
63302 /* Opcode: Halt P1 P2 * P4 *
63304 ** Exit immediately. All open cursors, etc are closed
63305 ** automatically.
63307 ** P1 is the result code returned by sqlite3_exec(), sqlite3_reset(),
63308 ** or sqlite3_finalize(). For a normal halt, this should be SQLITE_OK (0).
63309 ** For errors, it can be some other value. If P1!=0 then P2 will determine
63310 ** whether or not to rollback the current transaction. Do not rollback
63311 ** if P2==OE_Fail. Do the rollback if P2==OE_Rollback. If P2==OE_Abort,
63312 ** then back out all changes that have occurred during this execution of the
63313 ** VDBE, but do not rollback the transaction.
63315 ** If P4 is not null then it is an error message string.
63317 ** There is an implied "Halt 0 0 0" instruction inserted at the very end of
63318 ** every program. So a jump past the last instruction of the program
63319 ** is the same as executing Halt.
63321 case OP_Halt: {
63322 if( pOp->p1==SQLITE_OK && p->pFrame ){
63323 /* Halt the sub-program. Return control to the parent frame. */
63324 VdbeFrame *pFrame = p->pFrame;
63325 p->pFrame = pFrame->pParent;
63326 p->nFrame--;
63327 sqlite3VdbeSetChanges(db, p->nChange);
63328 pc = sqlite3VdbeFrameRestore(pFrame);
63329 if( pOp->p2==OE_Ignore ){
63330 /* Instruction pc is the OP_Program that invoked the sub-program
63331 ** currently being halted. If the p2 instruction of this OP_Halt
63332 ** instruction is set to OE_Ignore, then the sub-program is throwing
63333 ** an IGNORE exception. In this case jump to the address specified
63334 ** as the p2 of the calling OP_Program. */
63335 pc = p->aOp[pc].p2-1;
63337 aOp = p->aOp;
63338 aMem = p->aMem;
63339 break;
63342 p->rc = pOp->p1;
63343 p->errorAction = (u8)pOp->p2;
63344 p->pc = pc;
63345 if( pOp->p4.z ){
63346 assert( p->rc!=SQLITE_OK );
63347 sqlite3SetString(&p->zErrMsg, db, "%s", pOp->p4.z);
63348 testcase( sqlite3GlobalConfig.xLog!=0 );
63349 sqlite3_log(pOp->p1, "abort at %d in [%s]: %s", pc, p->zSql, pOp->p4.z);
63350 }else if( p->rc ){
63351 testcase( sqlite3GlobalConfig.xLog!=0 );
63352 sqlite3_log(pOp->p1, "constraint failed at %d in [%s]", pc, p->zSql);
63354 rc = sqlite3VdbeHalt(p);
63355 assert( rc==SQLITE_BUSY || rc==SQLITE_OK || rc==SQLITE_ERROR );
63356 if( rc==SQLITE_BUSY ){
63357 p->rc = rc = SQLITE_BUSY;
63358 }else{
63359 assert( rc==SQLITE_OK || p->rc==SQLITE_CONSTRAINT );
63360 assert( rc==SQLITE_OK || db->nDeferredCons>0 );
63361 rc = p->rc ? SQLITE_ERROR : SQLITE_DONE;
63363 goto vdbe_return;
63366 /* Opcode: Integer P1 P2 * * *
63368 ** The 32-bit integer value P1 is written into register P2.
63370 case OP_Integer: { /* out2-prerelease */
63371 pOut->u.i = pOp->p1;
63372 break;
63375 /* Opcode: Int64 * P2 * P4 *
63377 ** P4 is a pointer to a 64-bit integer value.
63378 ** Write that value into register P2.
63380 case OP_Int64: { /* out2-prerelease */
63381 assert( pOp->p4.pI64!=0 );
63382 pOut->u.i = *pOp->p4.pI64;
63383 break;
63386 #ifndef SQLITE_OMIT_FLOATING_POINT
63387 /* Opcode: Real * P2 * P4 *
63389 ** P4 is a pointer to a 64-bit floating point value.
63390 ** Write that value into register P2.
63392 case OP_Real: { /* same as TK_FLOAT, out2-prerelease */
63393 pOut->flags = MEM_Real;
63394 assert( !sqlite3IsNaN(*pOp->p4.pReal) );
63395 pOut->r = *pOp->p4.pReal;
63396 break;
63398 #endif
63400 /* Opcode: String8 * P2 * P4 *
63402 ** P4 points to a nul terminated UTF-8 string. This opcode is transformed
63403 ** into an OP_String before it is executed for the first time.
63405 case OP_String8: { /* same as TK_STRING, out2-prerelease */
63406 assert( pOp->p4.z!=0 );
63407 pOp->opcode = OP_String;
63408 pOp->p1 = sqlite3Strlen30(pOp->p4.z);
63410 #ifndef SQLITE_OMIT_UTF16
63411 if( encoding!=SQLITE_UTF8 ){
63412 rc = sqlite3VdbeMemSetStr(pOut, pOp->p4.z, -1, SQLITE_UTF8, SQLITE_STATIC);
63413 if( rc==SQLITE_TOOBIG ) goto too_big;
63414 if( SQLITE_OK!=sqlite3VdbeChangeEncoding(pOut, encoding) ) goto no_mem;
63415 assert( pOut->zMalloc==pOut->z );
63416 assert( pOut->flags & MEM_Dyn );
63417 pOut->zMalloc = 0;
63418 pOut->flags |= MEM_Static;
63419 pOut->flags &= ~MEM_Dyn;
63420 if( pOp->p4type==P4_DYNAMIC ){
63421 sqlite3DbFree(db, pOp->p4.z);
63423 pOp->p4type = P4_DYNAMIC;
63424 pOp->p4.z = pOut->z;
63425 pOp->p1 = pOut->n;
63427 #endif
63428 if( pOp->p1>db->aLimit[SQLITE_LIMIT_LENGTH] ){
63429 goto too_big;
63431 /* Fall through to the next case, OP_String */
63434 /* Opcode: String P1 P2 * P4 *
63436 ** The string value P4 of length P1 (bytes) is stored in register P2.
63438 case OP_String: { /* out2-prerelease */
63439 assert( pOp->p4.z!=0 );
63440 pOut->flags = MEM_Str|MEM_Static|MEM_Term;
63441 pOut->z = pOp->p4.z;
63442 pOut->n = pOp->p1;
63443 pOut->enc = encoding;
63444 UPDATE_MAX_BLOBSIZE(pOut);
63445 break;
63448 /* Opcode: Null * P2 * * *
63450 ** Write a NULL into register P2.
63452 case OP_Null: { /* out2-prerelease */
63453 pOut->flags = MEM_Null;
63454 break;
63458 /* Opcode: Blob P1 P2 * P4
63460 ** P4 points to a blob of data P1 bytes long. Store this
63461 ** blob in register P2.
63463 case OP_Blob: { /* out2-prerelease */
63464 assert( pOp->p1 <= SQLITE_MAX_LENGTH );
63465 sqlite3VdbeMemSetStr(pOut, pOp->p4.z, pOp->p1, 0, 0);
63466 pOut->enc = encoding;
63467 UPDATE_MAX_BLOBSIZE(pOut);
63468 break;
63471 /* Opcode: Variable P1 P2 * P4 *
63473 ** Transfer the values of bound parameter P1 into register P2
63475 ** If the parameter is named, then its name appears in P4 and P3==1.
63476 ** The P4 value is used by sqlite3_bind_parameter_name().
63478 case OP_Variable: { /* out2-prerelease */
63479 #if 0 /* local variables moved into u.ab */
63480 Mem *pVar; /* Value being transferred */
63481 #endif /* local variables moved into u.ab */
63483 assert( pOp->p1>0 && pOp->p1<=p->nVar );
63484 u.ab.pVar = &p->aVar[pOp->p1 - 1];
63485 if( sqlite3VdbeMemTooBig(u.ab.pVar) ){
63486 goto too_big;
63488 sqlite3VdbeMemShallowCopy(pOut, u.ab.pVar, MEM_Static);
63489 UPDATE_MAX_BLOBSIZE(pOut);
63490 break;
63493 /* Opcode: Move P1 P2 P3 * *
63495 ** Move the values in register P1..P1+P3-1 over into
63496 ** registers P2..P2+P3-1. Registers P1..P1+P1-1 are
63497 ** left holding a NULL. It is an error for register ranges
63498 ** P1..P1+P3-1 and P2..P2+P3-1 to overlap.
63500 case OP_Move: {
63501 #if 0 /* local variables moved into u.ac */
63502 char *zMalloc; /* Holding variable for allocated memory */
63503 int n; /* Number of registers left to copy */
63504 int p1; /* Register to copy from */
63505 int p2; /* Register to copy to */
63506 #endif /* local variables moved into u.ac */
63508 u.ac.n = pOp->p3;
63509 u.ac.p1 = pOp->p1;
63510 u.ac.p2 = pOp->p2;
63511 assert( u.ac.n>0 && u.ac.p1>0 && u.ac.p2>0 );
63512 assert( u.ac.p1+u.ac.n<=u.ac.p2 || u.ac.p2+u.ac.n<=u.ac.p1 );
63514 pIn1 = &aMem[u.ac.p1];
63515 pOut = &aMem[u.ac.p2];
63516 while( u.ac.n-- ){
63517 assert( pOut<=&aMem[p->nMem] );
63518 assert( pIn1<=&aMem[p->nMem] );
63519 assert( memIsValid(pIn1) );
63520 memAboutToChange(p, pOut);
63521 u.ac.zMalloc = pOut->zMalloc;
63522 pOut->zMalloc = 0;
63523 sqlite3VdbeMemMove(pOut, pIn1);
63524 pIn1->zMalloc = u.ac.zMalloc;
63525 REGISTER_TRACE(u.ac.p2++, pOut);
63526 pIn1++;
63527 pOut++;
63529 break;
63532 /* Opcode: Copy P1 P2 * * *
63534 ** Make a copy of register P1 into register P2.
63536 ** This instruction makes a deep copy of the value. A duplicate
63537 ** is made of any string or blob constant. See also OP_SCopy.
63539 case OP_Copy: { /* in1, out2 */
63540 pIn1 = &aMem[pOp->p1];
63541 pOut = &aMem[pOp->p2];
63542 assert( pOut!=pIn1 );
63543 sqlite3VdbeMemShallowCopy(pOut, pIn1, MEM_Ephem);
63544 Deephemeralize(pOut);
63545 REGISTER_TRACE(pOp->p2, pOut);
63546 break;
63549 /* Opcode: SCopy P1 P2 * * *
63551 ** Make a shallow copy of register P1 into register P2.
63553 ** This instruction makes a shallow copy of the value. If the value
63554 ** is a string or blob, then the copy is only a pointer to the
63555 ** original and hence if the original changes so will the copy.
63556 ** Worse, if the original is deallocated, the copy becomes invalid.
63557 ** Thus the program must guarantee that the original will not change
63558 ** during the lifetime of the copy. Use OP_Copy to make a complete
63559 ** copy.
63561 case OP_SCopy: { /* in1, out2 */
63562 pIn1 = &aMem[pOp->p1];
63563 pOut = &aMem[pOp->p2];
63564 assert( pOut!=pIn1 );
63565 sqlite3VdbeMemShallowCopy(pOut, pIn1, MEM_Ephem);
63566 #ifdef SQLITE_DEBUG
63567 if( pOut->pScopyFrom==0 ) pOut->pScopyFrom = pIn1;
63568 #endif
63569 REGISTER_TRACE(pOp->p2, pOut);
63570 break;
63573 /* Opcode: ResultRow P1 P2 * * *
63575 ** The registers P1 through P1+P2-1 contain a single row of
63576 ** results. This opcode causes the sqlite3_step() call to terminate
63577 ** with an SQLITE_ROW return code and it sets up the sqlite3_stmt
63578 ** structure to provide access to the top P1 values as the result
63579 ** row.
63581 case OP_ResultRow: {
63582 #if 0 /* local variables moved into u.ad */
63583 Mem *pMem;
63584 int i;
63585 #endif /* local variables moved into u.ad */
63586 assert( p->nResColumn==pOp->p2 );
63587 assert( pOp->p1>0 );
63588 assert( pOp->p1+pOp->p2<=p->nMem+1 );
63590 /* If this statement has violated immediate foreign key constraints, do
63591 ** not return the number of rows modified. And do not RELEASE the statement
63592 ** transaction. It needs to be rolled back. */
63593 if( SQLITE_OK!=(rc = sqlite3VdbeCheckFk(p, 0)) ){
63594 assert( db->flags&SQLITE_CountRows );
63595 assert( p->usesStmtJournal );
63596 break;
63599 /* If the SQLITE_CountRows flag is set in sqlite3.flags mask, then
63600 ** DML statements invoke this opcode to return the number of rows
63601 ** modified to the user. This is the only way that a VM that
63602 ** opens a statement transaction may invoke this opcode.
63604 ** In case this is such a statement, close any statement transaction
63605 ** opened by this VM before returning control to the user. This is to
63606 ** ensure that statement-transactions are always nested, not overlapping.
63607 ** If the open statement-transaction is not closed here, then the user
63608 ** may step another VM that opens its own statement transaction. This
63609 ** may lead to overlapping statement transactions.
63611 ** The statement transaction is never a top-level transaction. Hence
63612 ** the RELEASE call below can never fail.
63614 assert( p->iStatement==0 || db->flags&SQLITE_CountRows );
63615 rc = sqlite3VdbeCloseStatement(p, SAVEPOINT_RELEASE);
63616 if( NEVER(rc!=SQLITE_OK) ){
63617 break;
63620 /* Invalidate all ephemeral cursor row caches */
63621 p->cacheCtr = (p->cacheCtr + 2)|1;
63623 /* Make sure the results of the current row are \000 terminated
63624 ** and have an assigned type. The results are de-ephemeralized as
63625 ** as side effect.
63627 u.ad.pMem = p->pResultSet = &aMem[pOp->p1];
63628 for(u.ad.i=0; u.ad.i<pOp->p2; u.ad.i++){
63629 assert( memIsValid(&u.ad.pMem[u.ad.i]) );
63630 Deephemeralize(&u.ad.pMem[u.ad.i]);
63631 assert( (u.ad.pMem[u.ad.i].flags & MEM_Ephem)==0
63632 || (u.ad.pMem[u.ad.i].flags & (MEM_Str|MEM_Blob))==0 );
63633 sqlite3VdbeMemNulTerminate(&u.ad.pMem[u.ad.i]);
63634 sqlite3VdbeMemStoreType(&u.ad.pMem[u.ad.i]);
63635 REGISTER_TRACE(pOp->p1+u.ad.i, &u.ad.pMem[u.ad.i]);
63637 if( db->mallocFailed ) goto no_mem;
63639 /* Return SQLITE_ROW
63641 p->pc = pc + 1;
63642 rc = SQLITE_ROW;
63643 goto vdbe_return;
63646 /* Opcode: Concat P1 P2 P3 * *
63648 ** Add the text in register P1 onto the end of the text in
63649 ** register P2 and store the result in register P3.
63650 ** If either the P1 or P2 text are NULL then store NULL in P3.
63652 ** P3 = P2 || P1
63654 ** It is illegal for P1 and P3 to be the same register. Sometimes,
63655 ** if P3 is the same register as P2, the implementation is able
63656 ** to avoid a memcpy().
63658 case OP_Concat: { /* same as TK_CONCAT, in1, in2, out3 */
63659 #if 0 /* local variables moved into u.ae */
63660 i64 nByte;
63661 #endif /* local variables moved into u.ae */
63663 pIn1 = &aMem[pOp->p1];
63664 pIn2 = &aMem[pOp->p2];
63665 pOut = &aMem[pOp->p3];
63666 assert( pIn1!=pOut );
63667 if( (pIn1->flags | pIn2->flags) & MEM_Null ){
63668 sqlite3VdbeMemSetNull(pOut);
63669 break;
63671 if( ExpandBlob(pIn1) || ExpandBlob(pIn2) ) goto no_mem;
63672 Stringify(pIn1, encoding);
63673 Stringify(pIn2, encoding);
63674 u.ae.nByte = pIn1->n + pIn2->n;
63675 if( u.ae.nByte>db->aLimit[SQLITE_LIMIT_LENGTH] ){
63676 goto too_big;
63678 MemSetTypeFlag(pOut, MEM_Str);
63679 if( sqlite3VdbeMemGrow(pOut, (int)u.ae.nByte+2, pOut==pIn2) ){
63680 goto no_mem;
63682 if( pOut!=pIn2 ){
63683 memcpy(pOut->z, pIn2->z, pIn2->n);
63685 memcpy(&pOut->z[pIn2->n], pIn1->z, pIn1->n);
63686 pOut->z[u.ae.nByte] = 0;
63687 pOut->z[u.ae.nByte+1] = 0;
63688 pOut->flags |= MEM_Term;
63689 pOut->n = (int)u.ae.nByte;
63690 pOut->enc = encoding;
63691 UPDATE_MAX_BLOBSIZE(pOut);
63692 break;
63695 /* Opcode: Add P1 P2 P3 * *
63697 ** Add the value in register P1 to the value in register P2
63698 ** and store the result in register P3.
63699 ** If either input is NULL, the result is NULL.
63701 /* Opcode: Multiply P1 P2 P3 * *
63704 ** Multiply the value in register P1 by the value in register P2
63705 ** and store the result in register P3.
63706 ** If either input is NULL, the result is NULL.
63708 /* Opcode: Subtract P1 P2 P3 * *
63710 ** Subtract the value in register P1 from the value in register P2
63711 ** and store the result in register P3.
63712 ** If either input is NULL, the result is NULL.
63714 /* Opcode: Divide P1 P2 P3 * *
63716 ** Divide the value in register P1 by the value in register P2
63717 ** and store the result in register P3 (P3=P2/P1). If the value in
63718 ** register P1 is zero, then the result is NULL. If either input is
63719 ** NULL, the result is NULL.
63721 /* Opcode: Remainder P1 P2 P3 * *
63723 ** Compute the remainder after integer division of the value in
63724 ** register P1 by the value in register P2 and store the result in P3.
63725 ** If the value in register P2 is zero the result is NULL.
63726 ** If either operand is NULL, the result is NULL.
63728 case OP_Add: /* same as TK_PLUS, in1, in2, out3 */
63729 case OP_Subtract: /* same as TK_MINUS, in1, in2, out3 */
63730 case OP_Multiply: /* same as TK_STAR, in1, in2, out3 */
63731 case OP_Divide: /* same as TK_SLASH, in1, in2, out3 */
63732 case OP_Remainder: { /* same as TK_REM, in1, in2, out3 */
63733 #if 0 /* local variables moved into u.af */
63734 int flags; /* Combined MEM_* flags from both inputs */
63735 i64 iA; /* Integer value of left operand */
63736 i64 iB; /* Integer value of right operand */
63737 double rA; /* Real value of left operand */
63738 double rB; /* Real value of right operand */
63739 #endif /* local variables moved into u.af */
63741 pIn1 = &aMem[pOp->p1];
63742 applyNumericAffinity(pIn1);
63743 pIn2 = &aMem[pOp->p2];
63744 applyNumericAffinity(pIn2);
63745 pOut = &aMem[pOp->p3];
63746 u.af.flags = pIn1->flags | pIn2->flags;
63747 if( (u.af.flags & MEM_Null)!=0 ) goto arithmetic_result_is_null;
63748 if( (pIn1->flags & pIn2->flags & MEM_Int)==MEM_Int ){
63749 u.af.iA = pIn1->u.i;
63750 u.af.iB = pIn2->u.i;
63751 switch( pOp->opcode ){
63752 case OP_Add: if( sqlite3AddInt64(&u.af.iB,u.af.iA) ) goto fp_math; break;
63753 case OP_Subtract: if( sqlite3SubInt64(&u.af.iB,u.af.iA) ) goto fp_math; break;
63754 case OP_Multiply: if( sqlite3MulInt64(&u.af.iB,u.af.iA) ) goto fp_math; break;
63755 case OP_Divide: {
63756 if( u.af.iA==0 ) goto arithmetic_result_is_null;
63757 if( u.af.iA==-1 && u.af.iB==SMALLEST_INT64 ) goto fp_math;
63758 u.af.iB /= u.af.iA;
63759 break;
63761 default: {
63762 if( u.af.iA==0 ) goto arithmetic_result_is_null;
63763 if( u.af.iA==-1 ) u.af.iA = 1;
63764 u.af.iB %= u.af.iA;
63765 break;
63768 pOut->u.i = u.af.iB;
63769 MemSetTypeFlag(pOut, MEM_Int);
63770 }else{
63771 fp_math:
63772 u.af.rA = sqlite3VdbeRealValue(pIn1);
63773 u.af.rB = sqlite3VdbeRealValue(pIn2);
63774 switch( pOp->opcode ){
63775 case OP_Add: u.af.rB += u.af.rA; break;
63776 case OP_Subtract: u.af.rB -= u.af.rA; break;
63777 case OP_Multiply: u.af.rB *= u.af.rA; break;
63778 case OP_Divide: {
63779 /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
63780 if( u.af.rA==(double)0 ) goto arithmetic_result_is_null;
63781 u.af.rB /= u.af.rA;
63782 break;
63784 default: {
63785 u.af.iA = (i64)u.af.rA;
63786 u.af.iB = (i64)u.af.rB;
63787 if( u.af.iA==0 ) goto arithmetic_result_is_null;
63788 if( u.af.iA==-1 ) u.af.iA = 1;
63789 u.af.rB = (double)(u.af.iB % u.af.iA);
63790 break;
63793 #ifdef SQLITE_OMIT_FLOATING_POINT
63794 pOut->u.i = u.af.rB;
63795 MemSetTypeFlag(pOut, MEM_Int);
63796 #else
63797 if( sqlite3IsNaN(u.af.rB) ){
63798 goto arithmetic_result_is_null;
63800 pOut->r = u.af.rB;
63801 MemSetTypeFlag(pOut, MEM_Real);
63802 if( (u.af.flags & MEM_Real)==0 ){
63803 sqlite3VdbeIntegerAffinity(pOut);
63805 #endif
63807 break;
63809 arithmetic_result_is_null:
63810 sqlite3VdbeMemSetNull(pOut);
63811 break;
63814 /* Opcode: CollSeq * * P4
63816 ** P4 is a pointer to a CollSeq struct. If the next call to a user function
63817 ** or aggregate calls sqlite3GetFuncCollSeq(), this collation sequence will
63818 ** be returned. This is used by the built-in min(), max() and nullif()
63819 ** functions.
63821 ** The interface used by the implementation of the aforementioned functions
63822 ** to retrieve the collation sequence set by this opcode is not available
63823 ** publicly, only to user functions defined in func.c.
63825 case OP_CollSeq: {
63826 assert( pOp->p4type==P4_COLLSEQ );
63827 break;
63830 /* Opcode: Function P1 P2 P3 P4 P5
63832 ** Invoke a user function (P4 is a pointer to a Function structure that
63833 ** defines the function) with P5 arguments taken from register P2 and
63834 ** successors. The result of the function is stored in register P3.
63835 ** Register P3 must not be one of the function inputs.
63837 ** P1 is a 32-bit bitmask indicating whether or not each argument to the
63838 ** function was determined to be constant at compile time. If the first
63839 ** argument was constant then bit 0 of P1 is set. This is used to determine
63840 ** whether meta data associated with a user function argument using the
63841 ** sqlite3_set_auxdata() API may be safely retained until the next
63842 ** invocation of this opcode.
63844 ** See also: AggStep and AggFinal
63846 case OP_Function: {
63847 #if 0 /* local variables moved into u.ag */
63848 int i;
63849 Mem *pArg;
63850 sqlite3_context ctx;
63851 sqlite3_value **apVal;
63852 int n;
63853 #endif /* local variables moved into u.ag */
63855 u.ag.n = pOp->p5;
63856 u.ag.apVal = p->apArg;
63857 assert( u.ag.apVal || u.ag.n==0 );
63858 assert( pOp->p3>0 && pOp->p3<=p->nMem );
63859 pOut = &aMem[pOp->p3];
63860 memAboutToChange(p, pOut);
63862 assert( u.ag.n==0 || (pOp->p2>0 && pOp->p2+u.ag.n<=p->nMem+1) );
63863 assert( pOp->p3<pOp->p2 || pOp->p3>=pOp->p2+u.ag.n );
63864 u.ag.pArg = &aMem[pOp->p2];
63865 for(u.ag.i=0; u.ag.i<u.ag.n; u.ag.i++, u.ag.pArg++){
63866 assert( memIsValid(u.ag.pArg) );
63867 u.ag.apVal[u.ag.i] = u.ag.pArg;
63868 Deephemeralize(u.ag.pArg);
63869 sqlite3VdbeMemStoreType(u.ag.pArg);
63870 REGISTER_TRACE(pOp->p2+u.ag.i, u.ag.pArg);
63873 assert( pOp->p4type==P4_FUNCDEF || pOp->p4type==P4_VDBEFUNC );
63874 if( pOp->p4type==P4_FUNCDEF ){
63875 u.ag.ctx.pFunc = pOp->p4.pFunc;
63876 u.ag.ctx.pVdbeFunc = 0;
63877 }else{
63878 u.ag.ctx.pVdbeFunc = (VdbeFunc*)pOp->p4.pVdbeFunc;
63879 u.ag.ctx.pFunc = u.ag.ctx.pVdbeFunc->pFunc;
63882 u.ag.ctx.s.flags = MEM_Null;
63883 u.ag.ctx.s.db = db;
63884 u.ag.ctx.s.xDel = 0;
63885 u.ag.ctx.s.zMalloc = 0;
63887 /* The output cell may already have a buffer allocated. Move
63888 ** the pointer to u.ag.ctx.s so in case the user-function can use
63889 ** the already allocated buffer instead of allocating a new one.
63891 sqlite3VdbeMemMove(&u.ag.ctx.s, pOut);
63892 MemSetTypeFlag(&u.ag.ctx.s, MEM_Null);
63894 u.ag.ctx.isError = 0;
63895 if( u.ag.ctx.pFunc->flags & SQLITE_FUNC_NEEDCOLL ){
63896 assert( pOp>aOp );
63897 assert( pOp[-1].p4type==P4_COLLSEQ );
63898 assert( pOp[-1].opcode==OP_CollSeq );
63899 u.ag.ctx.pColl = pOp[-1].p4.pColl;
63901 (*u.ag.ctx.pFunc->xFunc)(&u.ag.ctx, u.ag.n, u.ag.apVal); /* IMP: R-24505-23230 */
63902 if( db->mallocFailed ){
63903 /* Even though a malloc() has failed, the implementation of the
63904 ** user function may have called an sqlite3_result_XXX() function
63905 ** to return a value. The following call releases any resources
63906 ** associated with such a value.
63908 sqlite3VdbeMemRelease(&u.ag.ctx.s);
63909 goto no_mem;
63912 /* If any auxiliary data functions have been called by this user function,
63913 ** immediately call the destructor for any non-static values.
63915 if( u.ag.ctx.pVdbeFunc ){
63916 sqlite3VdbeDeleteAuxData(u.ag.ctx.pVdbeFunc, pOp->p1);
63917 pOp->p4.pVdbeFunc = u.ag.ctx.pVdbeFunc;
63918 pOp->p4type = P4_VDBEFUNC;
63921 /* If the function returned an error, throw an exception */
63922 if( u.ag.ctx.isError ){
63923 sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3_value_text(&u.ag.ctx.s));
63924 rc = u.ag.ctx.isError;
63927 /* Copy the result of the function into register P3 */
63928 sqlite3VdbeChangeEncoding(&u.ag.ctx.s, encoding);
63929 sqlite3VdbeMemMove(pOut, &u.ag.ctx.s);
63930 if( sqlite3VdbeMemTooBig(pOut) ){
63931 goto too_big;
63934 #if 0
63935 /* The app-defined function has done something that as caused this
63936 ** statement to expire. (Perhaps the function called sqlite3_exec()
63937 ** with a CREATE TABLE statement.)
63939 if( p->expired ) rc = SQLITE_ABORT;
63940 #endif
63942 REGISTER_TRACE(pOp->p3, pOut);
63943 UPDATE_MAX_BLOBSIZE(pOut);
63944 break;
63947 /* Opcode: BitAnd P1 P2 P3 * *
63949 ** Take the bit-wise AND of the values in register P1 and P2 and
63950 ** store the result in register P3.
63951 ** If either input is NULL, the result is NULL.
63953 /* Opcode: BitOr P1 P2 P3 * *
63955 ** Take the bit-wise OR of the values in register P1 and P2 and
63956 ** store the result in register P3.
63957 ** If either input is NULL, the result is NULL.
63959 /* Opcode: ShiftLeft P1 P2 P3 * *
63961 ** Shift the integer value in register P2 to the left by the
63962 ** number of bits specified by the integer in register P1.
63963 ** Store the result in register P3.
63964 ** If either input is NULL, the result is NULL.
63966 /* Opcode: ShiftRight P1 P2 P3 * *
63968 ** Shift the integer value in register P2 to the right by the
63969 ** number of bits specified by the integer in register P1.
63970 ** Store the result in register P3.
63971 ** If either input is NULL, the result is NULL.
63973 case OP_BitAnd: /* same as TK_BITAND, in1, in2, out3 */
63974 case OP_BitOr: /* same as TK_BITOR, in1, in2, out3 */
63975 case OP_ShiftLeft: /* same as TK_LSHIFT, in1, in2, out3 */
63976 case OP_ShiftRight: { /* same as TK_RSHIFT, in1, in2, out3 */
63977 #if 0 /* local variables moved into u.ah */
63978 i64 iA;
63979 u64 uA;
63980 i64 iB;
63981 u8 op;
63982 #endif /* local variables moved into u.ah */
63984 pIn1 = &aMem[pOp->p1];
63985 pIn2 = &aMem[pOp->p2];
63986 pOut = &aMem[pOp->p3];
63987 if( (pIn1->flags | pIn2->flags) & MEM_Null ){
63988 sqlite3VdbeMemSetNull(pOut);
63989 break;
63991 u.ah.iA = sqlite3VdbeIntValue(pIn2);
63992 u.ah.iB = sqlite3VdbeIntValue(pIn1);
63993 u.ah.op = pOp->opcode;
63994 if( u.ah.op==OP_BitAnd ){
63995 u.ah.iA &= u.ah.iB;
63996 }else if( u.ah.op==OP_BitOr ){
63997 u.ah.iA |= u.ah.iB;
63998 }else if( u.ah.iB!=0 ){
63999 assert( u.ah.op==OP_ShiftRight || u.ah.op==OP_ShiftLeft );
64001 /* If shifting by a negative amount, shift in the other direction */
64002 if( u.ah.iB<0 ){
64003 assert( OP_ShiftRight==OP_ShiftLeft+1 );
64004 u.ah.op = 2*OP_ShiftLeft + 1 - u.ah.op;
64005 u.ah.iB = u.ah.iB>(-64) ? -u.ah.iB : 64;
64008 if( u.ah.iB>=64 ){
64009 u.ah.iA = (u.ah.iA>=0 || u.ah.op==OP_ShiftLeft) ? 0 : -1;
64010 }else{
64011 memcpy(&u.ah.uA, &u.ah.iA, sizeof(u.ah.uA));
64012 if( u.ah.op==OP_ShiftLeft ){
64013 u.ah.uA <<= u.ah.iB;
64014 }else{
64015 u.ah.uA >>= u.ah.iB;
64016 /* Sign-extend on a right shift of a negative number */
64017 if( u.ah.iA<0 ) u.ah.uA |= ((((u64)0xffffffff)<<32)|0xffffffff) << (64-u.ah.iB);
64019 memcpy(&u.ah.iA, &u.ah.uA, sizeof(u.ah.iA));
64022 pOut->u.i = u.ah.iA;
64023 MemSetTypeFlag(pOut, MEM_Int);
64024 break;
64027 /* Opcode: AddImm P1 P2 * * *
64029 ** Add the constant P2 to the value in register P1.
64030 ** The result is always an integer.
64032 ** To force any register to be an integer, just add 0.
64034 case OP_AddImm: { /* in1 */
64035 pIn1 = &aMem[pOp->p1];
64036 memAboutToChange(p, pIn1);
64037 sqlite3VdbeMemIntegerify(pIn1);
64038 pIn1->u.i += pOp->p2;
64039 break;
64042 /* Opcode: MustBeInt P1 P2 * * *
64044 ** Force the value in register P1 to be an integer. If the value
64045 ** in P1 is not an integer and cannot be converted into an integer
64046 ** without data loss, then jump immediately to P2, or if P2==0
64047 ** raise an SQLITE_MISMATCH exception.
64049 case OP_MustBeInt: { /* jump, in1 */
64050 pIn1 = &aMem[pOp->p1];
64051 applyAffinity(pIn1, SQLITE_AFF_NUMERIC, encoding);
64052 if( (pIn1->flags & MEM_Int)==0 ){
64053 if( pOp->p2==0 ){
64054 rc = SQLITE_MISMATCH;
64055 goto abort_due_to_error;
64056 }else{
64057 pc = pOp->p2 - 1;
64059 }else{
64060 MemSetTypeFlag(pIn1, MEM_Int);
64062 break;
64065 #ifndef SQLITE_OMIT_FLOATING_POINT
64066 /* Opcode: RealAffinity P1 * * * *
64068 ** If register P1 holds an integer convert it to a real value.
64070 ** This opcode is used when extracting information from a column that
64071 ** has REAL affinity. Such column values may still be stored as
64072 ** integers, for space efficiency, but after extraction we want them
64073 ** to have only a real value.
64075 case OP_RealAffinity: { /* in1 */
64076 pIn1 = &aMem[pOp->p1];
64077 if( pIn1->flags & MEM_Int ){
64078 sqlite3VdbeMemRealify(pIn1);
64080 break;
64082 #endif
64084 #ifndef SQLITE_OMIT_CAST
64085 /* Opcode: ToText P1 * * * *
64087 ** Force the value in register P1 to be text.
64088 ** If the value is numeric, convert it to a string using the
64089 ** equivalent of printf(). Blob values are unchanged and
64090 ** are afterwards simply interpreted as text.
64092 ** A NULL value is not changed by this routine. It remains NULL.
64094 case OP_ToText: { /* same as TK_TO_TEXT, in1 */
64095 pIn1 = &aMem[pOp->p1];
64096 memAboutToChange(p, pIn1);
64097 if( pIn1->flags & MEM_Null ) break;
64098 assert( MEM_Str==(MEM_Blob>>3) );
64099 pIn1->flags |= (pIn1->flags&MEM_Blob)>>3;
64100 applyAffinity(pIn1, SQLITE_AFF_TEXT, encoding);
64101 rc = ExpandBlob(pIn1);
64102 assert( pIn1->flags & MEM_Str || db->mallocFailed );
64103 pIn1->flags &= ~(MEM_Int|MEM_Real|MEM_Blob|MEM_Zero);
64104 UPDATE_MAX_BLOBSIZE(pIn1);
64105 break;
64108 /* Opcode: ToBlob P1 * * * *
64110 ** Force the value in register P1 to be a BLOB.
64111 ** If the value is numeric, convert it to a string first.
64112 ** Strings are simply reinterpreted as blobs with no change
64113 ** to the underlying data.
64115 ** A NULL value is not changed by this routine. It remains NULL.
64117 case OP_ToBlob: { /* same as TK_TO_BLOB, in1 */
64118 pIn1 = &aMem[pOp->p1];
64119 if( pIn1->flags & MEM_Null ) break;
64120 if( (pIn1->flags & MEM_Blob)==0 ){
64121 applyAffinity(pIn1, SQLITE_AFF_TEXT, encoding);
64122 assert( pIn1->flags & MEM_Str || db->mallocFailed );
64123 MemSetTypeFlag(pIn1, MEM_Blob);
64124 }else{
64125 pIn1->flags &= ~(MEM_TypeMask&~MEM_Blob);
64127 UPDATE_MAX_BLOBSIZE(pIn1);
64128 break;
64131 /* Opcode: ToNumeric P1 * * * *
64133 ** Force the value in register P1 to be numeric (either an
64134 ** integer or a floating-point number.)
64135 ** If the value is text or blob, try to convert it to an using the
64136 ** equivalent of atoi() or atof() and store 0 if no such conversion
64137 ** is possible.
64139 ** A NULL value is not changed by this routine. It remains NULL.
64141 case OP_ToNumeric: { /* same as TK_TO_NUMERIC, in1 */
64142 pIn1 = &aMem[pOp->p1];
64143 sqlite3VdbeMemNumerify(pIn1);
64144 break;
64146 #endif /* SQLITE_OMIT_CAST */
64148 /* Opcode: ToInt P1 * * * *
64150 ** Force the value in register P1 to be an integer. If
64151 ** The value is currently a real number, drop its fractional part.
64152 ** If the value is text or blob, try to convert it to an integer using the
64153 ** equivalent of atoi() and store 0 if no such conversion is possible.
64155 ** A NULL value is not changed by this routine. It remains NULL.
64157 case OP_ToInt: { /* same as TK_TO_INT, in1 */
64158 pIn1 = &aMem[pOp->p1];
64159 if( (pIn1->flags & MEM_Null)==0 ){
64160 sqlite3VdbeMemIntegerify(pIn1);
64162 break;
64165 #if !defined(SQLITE_OMIT_CAST) && !defined(SQLITE_OMIT_FLOATING_POINT)
64166 /* Opcode: ToReal P1 * * * *
64168 ** Force the value in register P1 to be a floating point number.
64169 ** If The value is currently an integer, convert it.
64170 ** If the value is text or blob, try to convert it to an integer using the
64171 ** equivalent of atoi() and store 0.0 if no such conversion is possible.
64173 ** A NULL value is not changed by this routine. It remains NULL.
64175 case OP_ToReal: { /* same as TK_TO_REAL, in1 */
64176 pIn1 = &aMem[pOp->p1];
64177 memAboutToChange(p, pIn1);
64178 if( (pIn1->flags & MEM_Null)==0 ){
64179 sqlite3VdbeMemRealify(pIn1);
64181 break;
64183 #endif /* !defined(SQLITE_OMIT_CAST) && !defined(SQLITE_OMIT_FLOATING_POINT) */
64185 /* Opcode: Lt P1 P2 P3 P4 P5
64187 ** Compare the values in register P1 and P3. If reg(P3)<reg(P1) then
64188 ** jump to address P2.
64190 ** If the SQLITE_JUMPIFNULL bit of P5 is set and either reg(P1) or
64191 ** reg(P3) is NULL then take the jump. If the SQLITE_JUMPIFNULL
64192 ** bit is clear then fall through if either operand is NULL.
64194 ** The SQLITE_AFF_MASK portion of P5 must be an affinity character -
64195 ** SQLITE_AFF_TEXT, SQLITE_AFF_INTEGER, and so forth. An attempt is made
64196 ** to coerce both inputs according to this affinity before the
64197 ** comparison is made. If the SQLITE_AFF_MASK is 0x00, then numeric
64198 ** affinity is used. Note that the affinity conversions are stored
64199 ** back into the input registers P1 and P3. So this opcode can cause
64200 ** persistent changes to registers P1 and P3.
64202 ** Once any conversions have taken place, and neither value is NULL,
64203 ** the values are compared. If both values are blobs then memcmp() is
64204 ** used to determine the results of the comparison. If both values
64205 ** are text, then the appropriate collating function specified in
64206 ** P4 is used to do the comparison. If P4 is not specified then
64207 ** memcmp() is used to compare text string. If both values are
64208 ** numeric, then a numeric comparison is used. If the two values
64209 ** are of different types, then numbers are considered less than
64210 ** strings and strings are considered less than blobs.
64212 ** If the SQLITE_STOREP2 bit of P5 is set, then do not jump. Instead,
64213 ** store a boolean result (either 0, or 1, or NULL) in register P2.
64215 /* Opcode: Ne P1 P2 P3 P4 P5
64217 ** This works just like the Lt opcode except that the jump is taken if
64218 ** the operands in registers P1 and P3 are not equal. See the Lt opcode for
64219 ** additional information.
64221 ** If SQLITE_NULLEQ is set in P5 then the result of comparison is always either
64222 ** true or false and is never NULL. If both operands are NULL then the result
64223 ** of comparison is false. If either operand is NULL then the result is true.
64224 ** If neither operand is NULL the the result is the same as it would be if
64225 ** the SQLITE_NULLEQ flag were omitted from P5.
64227 /* Opcode: Eq P1 P2 P3 P4 P5
64229 ** This works just like the Lt opcode except that the jump is taken if
64230 ** the operands in registers P1 and P3 are equal.
64231 ** See the Lt opcode for additional information.
64233 ** If SQLITE_NULLEQ is set in P5 then the result of comparison is always either
64234 ** true or false and is never NULL. If both operands are NULL then the result
64235 ** of comparison is true. If either operand is NULL then the result is false.
64236 ** If neither operand is NULL the the result is the same as it would be if
64237 ** the SQLITE_NULLEQ flag were omitted from P5.
64239 /* Opcode: Le P1 P2 P3 P4 P5
64241 ** This works just like the Lt opcode except that the jump is taken if
64242 ** the content of register P3 is less than or equal to the content of
64243 ** register P1. See the Lt opcode for additional information.
64245 /* Opcode: Gt P1 P2 P3 P4 P5
64247 ** This works just like the Lt opcode except that the jump is taken if
64248 ** the content of register P3 is greater than the content of
64249 ** register P1. See the Lt opcode for additional information.
64251 /* Opcode: Ge P1 P2 P3 P4 P5
64253 ** This works just like the Lt opcode except that the jump is taken if
64254 ** the content of register P3 is greater than or equal to the content of
64255 ** register P1. See the Lt opcode for additional information.
64257 case OP_Eq: /* same as TK_EQ, jump, in1, in3 */
64258 case OP_Ne: /* same as TK_NE, jump, in1, in3 */
64259 case OP_Lt: /* same as TK_LT, jump, in1, in3 */
64260 case OP_Le: /* same as TK_LE, jump, in1, in3 */
64261 case OP_Gt: /* same as TK_GT, jump, in1, in3 */
64262 case OP_Ge: { /* same as TK_GE, jump, in1, in3 */
64263 #if 0 /* local variables moved into u.ai */
64264 int res; /* Result of the comparison of pIn1 against pIn3 */
64265 char affinity; /* Affinity to use for comparison */
64266 u16 flags1; /* Copy of initial value of pIn1->flags */
64267 u16 flags3; /* Copy of initial value of pIn3->flags */
64268 #endif /* local variables moved into u.ai */
64270 pIn1 = &aMem[pOp->p1];
64271 pIn3 = &aMem[pOp->p3];
64272 u.ai.flags1 = pIn1->flags;
64273 u.ai.flags3 = pIn3->flags;
64274 if( (pIn1->flags | pIn3->flags)&MEM_Null ){
64275 /* One or both operands are NULL */
64276 if( pOp->p5 & SQLITE_NULLEQ ){
64277 /* If SQLITE_NULLEQ is set (which will only happen if the operator is
64278 ** OP_Eq or OP_Ne) then take the jump or not depending on whether
64279 ** or not both operands are null.
64281 assert( pOp->opcode==OP_Eq || pOp->opcode==OP_Ne );
64282 u.ai.res = (pIn1->flags & pIn3->flags & MEM_Null)==0;
64283 }else{
64284 /* SQLITE_NULLEQ is clear and at least one operand is NULL,
64285 ** then the result is always NULL.
64286 ** The jump is taken if the SQLITE_JUMPIFNULL bit is set.
64288 if( pOp->p5 & SQLITE_STOREP2 ){
64289 pOut = &aMem[pOp->p2];
64290 MemSetTypeFlag(pOut, MEM_Null);
64291 REGISTER_TRACE(pOp->p2, pOut);
64292 }else if( pOp->p5 & SQLITE_JUMPIFNULL ){
64293 pc = pOp->p2-1;
64295 break;
64297 }else{
64298 /* Neither operand is NULL. Do a comparison. */
64299 u.ai.affinity = pOp->p5 & SQLITE_AFF_MASK;
64300 if( u.ai.affinity ){
64301 applyAffinity(pIn1, u.ai.affinity, encoding);
64302 applyAffinity(pIn3, u.ai.affinity, encoding);
64303 if( db->mallocFailed ) goto no_mem;
64306 assert( pOp->p4type==P4_COLLSEQ || pOp->p4.pColl==0 );
64307 ExpandBlob(pIn1);
64308 ExpandBlob(pIn3);
64309 u.ai.res = sqlite3MemCompare(pIn3, pIn1, pOp->p4.pColl);
64311 switch( pOp->opcode ){
64312 case OP_Eq: u.ai.res = u.ai.res==0; break;
64313 case OP_Ne: u.ai.res = u.ai.res!=0; break;
64314 case OP_Lt: u.ai.res = u.ai.res<0; break;
64315 case OP_Le: u.ai.res = u.ai.res<=0; break;
64316 case OP_Gt: u.ai.res = u.ai.res>0; break;
64317 default: u.ai.res = u.ai.res>=0; break;
64320 if( pOp->p5 & SQLITE_STOREP2 ){
64321 pOut = &aMem[pOp->p2];
64322 memAboutToChange(p, pOut);
64323 MemSetTypeFlag(pOut, MEM_Int);
64324 pOut->u.i = u.ai.res;
64325 REGISTER_TRACE(pOp->p2, pOut);
64326 }else if( u.ai.res ){
64327 pc = pOp->p2-1;
64330 /* Undo any changes made by applyAffinity() to the input registers. */
64331 pIn1->flags = (pIn1->flags&~MEM_TypeMask) | (u.ai.flags1&MEM_TypeMask);
64332 pIn3->flags = (pIn3->flags&~MEM_TypeMask) | (u.ai.flags3&MEM_TypeMask);
64333 break;
64336 /* Opcode: Permutation * * * P4 *
64338 ** Set the permutation used by the OP_Compare operator to be the array
64339 ** of integers in P4.
64341 ** The permutation is only valid until the next OP_Permutation, OP_Compare,
64342 ** OP_Halt, or OP_ResultRow. Typically the OP_Permutation should occur
64343 ** immediately prior to the OP_Compare.
64345 case OP_Permutation: {
64346 assert( pOp->p4type==P4_INTARRAY );
64347 assert( pOp->p4.ai );
64348 aPermute = pOp->p4.ai;
64349 break;
64352 /* Opcode: Compare P1 P2 P3 P4 *
64354 ** Compare two vectors of registers in reg(P1)..reg(P1+P3-1) (call this
64355 ** vector "A") and in reg(P2)..reg(P2+P3-1) ("B"). Save the result of
64356 ** the comparison for use by the next OP_Jump instruct.
64358 ** P4 is a KeyInfo structure that defines collating sequences and sort
64359 ** orders for the comparison. The permutation applies to registers
64360 ** only. The KeyInfo elements are used sequentially.
64362 ** The comparison is a sort comparison, so NULLs compare equal,
64363 ** NULLs are less than numbers, numbers are less than strings,
64364 ** and strings are less than blobs.
64366 case OP_Compare: {
64367 #if 0 /* local variables moved into u.aj */
64368 int n;
64369 int i;
64370 int p1;
64371 int p2;
64372 const KeyInfo *pKeyInfo;
64373 int idx;
64374 CollSeq *pColl; /* Collating sequence to use on this term */
64375 int bRev; /* True for DESCENDING sort order */
64376 #endif /* local variables moved into u.aj */
64378 u.aj.n = pOp->p3;
64379 u.aj.pKeyInfo = pOp->p4.pKeyInfo;
64380 assert( u.aj.n>0 );
64381 assert( u.aj.pKeyInfo!=0 );
64382 u.aj.p1 = pOp->p1;
64383 u.aj.p2 = pOp->p2;
64384 #if SQLITE_DEBUG
64385 if( aPermute ){
64386 int k, mx = 0;
64387 for(k=0; k<u.aj.n; k++) if( aPermute[k]>mx ) mx = aPermute[k];
64388 assert( u.aj.p1>0 && u.aj.p1+mx<=p->nMem+1 );
64389 assert( u.aj.p2>0 && u.aj.p2+mx<=p->nMem+1 );
64390 }else{
64391 assert( u.aj.p1>0 && u.aj.p1+u.aj.n<=p->nMem+1 );
64392 assert( u.aj.p2>0 && u.aj.p2+u.aj.n<=p->nMem+1 );
64394 #endif /* SQLITE_DEBUG */
64395 for(u.aj.i=0; u.aj.i<u.aj.n; u.aj.i++){
64396 u.aj.idx = aPermute ? aPermute[u.aj.i] : u.aj.i;
64397 assert( memIsValid(&aMem[u.aj.p1+u.aj.idx]) );
64398 assert( memIsValid(&aMem[u.aj.p2+u.aj.idx]) );
64399 REGISTER_TRACE(u.aj.p1+u.aj.idx, &aMem[u.aj.p1+u.aj.idx]);
64400 REGISTER_TRACE(u.aj.p2+u.aj.idx, &aMem[u.aj.p2+u.aj.idx]);
64401 assert( u.aj.i<u.aj.pKeyInfo->nField );
64402 u.aj.pColl = u.aj.pKeyInfo->aColl[u.aj.i];
64403 u.aj.bRev = u.aj.pKeyInfo->aSortOrder[u.aj.i];
64404 iCompare = sqlite3MemCompare(&aMem[u.aj.p1+u.aj.idx], &aMem[u.aj.p2+u.aj.idx], u.aj.pColl);
64405 if( iCompare ){
64406 if( u.aj.bRev ) iCompare = -iCompare;
64407 break;
64410 aPermute = 0;
64411 break;
64414 /* Opcode: Jump P1 P2 P3 * *
64416 ** Jump to the instruction at address P1, P2, or P3 depending on whether
64417 ** in the most recent OP_Compare instruction the P1 vector was less than
64418 ** equal to, or greater than the P2 vector, respectively.
64420 case OP_Jump: { /* jump */
64421 if( iCompare<0 ){
64422 pc = pOp->p1 - 1;
64423 }else if( iCompare==0 ){
64424 pc = pOp->p2 - 1;
64425 }else{
64426 pc = pOp->p3 - 1;
64428 break;
64431 /* Opcode: And P1 P2 P3 * *
64433 ** Take the logical AND of the values in registers P1 and P2 and
64434 ** write the result into register P3.
64436 ** If either P1 or P2 is 0 (false) then the result is 0 even if
64437 ** the other input is NULL. A NULL and true or two NULLs give
64438 ** a NULL output.
64440 /* Opcode: Or P1 P2 P3 * *
64442 ** Take the logical OR of the values in register P1 and P2 and
64443 ** store the answer in register P3.
64445 ** If either P1 or P2 is nonzero (true) then the result is 1 (true)
64446 ** even if the other input is NULL. A NULL and false or two NULLs
64447 ** give a NULL output.
64449 case OP_And: /* same as TK_AND, in1, in2, out3 */
64450 case OP_Or: { /* same as TK_OR, in1, in2, out3 */
64451 #if 0 /* local variables moved into u.ak */
64452 int v1; /* Left operand: 0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */
64453 int v2; /* Right operand: 0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */
64454 #endif /* local variables moved into u.ak */
64456 pIn1 = &aMem[pOp->p1];
64457 if( pIn1->flags & MEM_Null ){
64458 u.ak.v1 = 2;
64459 }else{
64460 u.ak.v1 = sqlite3VdbeIntValue(pIn1)!=0;
64462 pIn2 = &aMem[pOp->p2];
64463 if( pIn2->flags & MEM_Null ){
64464 u.ak.v2 = 2;
64465 }else{
64466 u.ak.v2 = sqlite3VdbeIntValue(pIn2)!=0;
64468 if( pOp->opcode==OP_And ){
64469 static const unsigned char and_logic[] = { 0, 0, 0, 0, 1, 2, 0, 2, 2 };
64470 u.ak.v1 = and_logic[u.ak.v1*3+u.ak.v2];
64471 }else{
64472 static const unsigned char or_logic[] = { 0, 1, 2, 1, 1, 1, 2, 1, 2 };
64473 u.ak.v1 = or_logic[u.ak.v1*3+u.ak.v2];
64475 pOut = &aMem[pOp->p3];
64476 if( u.ak.v1==2 ){
64477 MemSetTypeFlag(pOut, MEM_Null);
64478 }else{
64479 pOut->u.i = u.ak.v1;
64480 MemSetTypeFlag(pOut, MEM_Int);
64482 break;
64485 /* Opcode: Not P1 P2 * * *
64487 ** Interpret the value in register P1 as a boolean value. Store the
64488 ** boolean complement in register P2. If the value in register P1 is
64489 ** NULL, then a NULL is stored in P2.
64491 case OP_Not: { /* same as TK_NOT, in1, out2 */
64492 pIn1 = &aMem[pOp->p1];
64493 pOut = &aMem[pOp->p2];
64494 if( pIn1->flags & MEM_Null ){
64495 sqlite3VdbeMemSetNull(pOut);
64496 }else{
64497 sqlite3VdbeMemSetInt64(pOut, !sqlite3VdbeIntValue(pIn1));
64499 break;
64502 /* Opcode: BitNot P1 P2 * * *
64504 ** Interpret the content of register P1 as an integer. Store the
64505 ** ones-complement of the P1 value into register P2. If P1 holds
64506 ** a NULL then store a NULL in P2.
64508 case OP_BitNot: { /* same as TK_BITNOT, in1, out2 */
64509 pIn1 = &aMem[pOp->p1];
64510 pOut = &aMem[pOp->p2];
64511 if( pIn1->flags & MEM_Null ){
64512 sqlite3VdbeMemSetNull(pOut);
64513 }else{
64514 sqlite3VdbeMemSetInt64(pOut, ~sqlite3VdbeIntValue(pIn1));
64516 break;
64519 /* Opcode: If P1 P2 P3 * *
64521 ** Jump to P2 if the value in register P1 is true. The value is
64522 ** is considered true if it is numeric and non-zero. If the value
64523 ** in P1 is NULL then take the jump if P3 is true.
64525 /* Opcode: IfNot P1 P2 P3 * *
64527 ** Jump to P2 if the value in register P1 is False. The value is
64528 ** is considered true if it has a numeric value of zero. If the value
64529 ** in P1 is NULL then take the jump if P3 is true.
64531 case OP_If: /* jump, in1 */
64532 case OP_IfNot: { /* jump, in1 */
64533 #if 0 /* local variables moved into u.al */
64534 int c;
64535 #endif /* local variables moved into u.al */
64536 pIn1 = &aMem[pOp->p1];
64537 if( pIn1->flags & MEM_Null ){
64538 u.al.c = pOp->p3;
64539 }else{
64540 #ifdef SQLITE_OMIT_FLOATING_POINT
64541 u.al.c = sqlite3VdbeIntValue(pIn1)!=0;
64542 #else
64543 u.al.c = sqlite3VdbeRealValue(pIn1)!=0.0;
64544 #endif
64545 if( pOp->opcode==OP_IfNot ) u.al.c = !u.al.c;
64547 if( u.al.c ){
64548 pc = pOp->p2-1;
64550 break;
64553 /* Opcode: IsNull P1 P2 * * *
64555 ** Jump to P2 if the value in register P1 is NULL.
64557 case OP_IsNull: { /* same as TK_ISNULL, jump, in1 */
64558 pIn1 = &aMem[pOp->p1];
64559 if( (pIn1->flags & MEM_Null)!=0 ){
64560 pc = pOp->p2 - 1;
64562 break;
64565 /* Opcode: NotNull P1 P2 * * *
64567 ** Jump to P2 if the value in register P1 is not NULL.
64569 case OP_NotNull: { /* same as TK_NOTNULL, jump, in1 */
64570 pIn1 = &aMem[pOp->p1];
64571 if( (pIn1->flags & MEM_Null)==0 ){
64572 pc = pOp->p2 - 1;
64574 break;
64577 /* Opcode: Column P1 P2 P3 P4 P5
64579 ** Interpret the data that cursor P1 points to as a structure built using
64580 ** the MakeRecord instruction. (See the MakeRecord opcode for additional
64581 ** information about the format of the data.) Extract the P2-th column
64582 ** from this record. If there are less that (P2+1)
64583 ** values in the record, extract a NULL.
64585 ** The value extracted is stored in register P3.
64587 ** If the column contains fewer than P2 fields, then extract a NULL. Or,
64588 ** if the P4 argument is a P4_MEM use the value of the P4 argument as
64589 ** the result.
64591 ** If the OPFLAG_CLEARCACHE bit is set on P5 and P1 is a pseudo-table cursor,
64592 ** then the cache of the cursor is reset prior to extracting the column.
64593 ** The first OP_Column against a pseudo-table after the value of the content
64594 ** register has changed should have this bit set.
64596 case OP_Column: {
64597 #if 0 /* local variables moved into u.am */
64598 u32 payloadSize; /* Number of bytes in the record */
64599 i64 payloadSize64; /* Number of bytes in the record */
64600 int p1; /* P1 value of the opcode */
64601 int p2; /* column number to retrieve */
64602 VdbeCursor *pC; /* The VDBE cursor */
64603 char *zRec; /* Pointer to complete record-data */
64604 BtCursor *pCrsr; /* The BTree cursor */
64605 u32 *aType; /* aType[i] holds the numeric type of the i-th column */
64606 u32 *aOffset; /* aOffset[i] is offset to start of data for i-th column */
64607 int nField; /* number of fields in the record */
64608 int len; /* The length of the serialized data for the column */
64609 int i; /* Loop counter */
64610 char *zData; /* Part of the record being decoded */
64611 Mem *pDest; /* Where to write the extracted value */
64612 Mem sMem; /* For storing the record being decoded */
64613 u8 *zIdx; /* Index into header */
64614 u8 *zEndHdr; /* Pointer to first byte after the header */
64615 u32 offset; /* Offset into the data */
64616 u32 szField; /* Number of bytes in the content of a field */
64617 int szHdr; /* Size of the header size field at start of record */
64618 int avail; /* Number of bytes of available data */
64619 Mem *pReg; /* PseudoTable input register */
64620 #endif /* local variables moved into u.am */
64623 u.am.p1 = pOp->p1;
64624 u.am.p2 = pOp->p2;
64625 u.am.pC = 0;
64626 memset(&u.am.sMem, 0, sizeof(u.am.sMem));
64627 assert( u.am.p1<p->nCursor );
64628 assert( pOp->p3>0 && pOp->p3<=p->nMem );
64629 u.am.pDest = &aMem[pOp->p3];
64630 memAboutToChange(p, u.am.pDest);
64631 MemSetTypeFlag(u.am.pDest, MEM_Null);
64632 u.am.zRec = 0;
64634 /* This block sets the variable u.am.payloadSize to be the total number of
64635 ** bytes in the record.
64637 ** u.am.zRec is set to be the complete text of the record if it is available.
64638 ** The complete record text is always available for pseudo-tables
64639 ** If the record is stored in a cursor, the complete record text
64640 ** might be available in the u.am.pC->aRow cache. Or it might not be.
64641 ** If the data is unavailable, u.am.zRec is set to NULL.
64643 ** We also compute the number of columns in the record. For cursors,
64644 ** the number of columns is stored in the VdbeCursor.nField element.
64646 u.am.pC = p->apCsr[u.am.p1];
64647 assert( u.am.pC!=0 );
64648 #ifndef SQLITE_OMIT_VIRTUALTABLE
64649 assert( u.am.pC->pVtabCursor==0 );
64650 #endif
64651 u.am.pCrsr = u.am.pC->pCursor;
64652 if( u.am.pCrsr!=0 ){
64653 /* The record is stored in a B-Tree */
64654 rc = sqlite3VdbeCursorMoveto(u.am.pC);
64655 if( rc ) goto abort_due_to_error;
64656 if( u.am.pC->nullRow ){
64657 u.am.payloadSize = 0;
64658 }else if( u.am.pC->cacheStatus==p->cacheCtr ){
64659 u.am.payloadSize = u.am.pC->payloadSize;
64660 u.am.zRec = (char*)u.am.pC->aRow;
64661 }else if( u.am.pC->isIndex ){
64662 assert( sqlite3BtreeCursorIsValid(u.am.pCrsr) );
64663 rc = sqlite3BtreeKeySize(u.am.pCrsr, &u.am.payloadSize64);
64664 assert( rc==SQLITE_OK ); /* True because of CursorMoveto() call above */
64665 /* sqlite3BtreeParseCellPtr() uses getVarint32() to extract the
64666 ** payload size, so it is impossible for u.am.payloadSize64 to be
64667 ** larger than 32 bits. */
64668 assert( (u.am.payloadSize64 & SQLITE_MAX_U32)==(u64)u.am.payloadSize64 );
64669 u.am.payloadSize = (u32)u.am.payloadSize64;
64670 }else{
64671 assert( sqlite3BtreeCursorIsValid(u.am.pCrsr) );
64672 rc = sqlite3BtreeDataSize(u.am.pCrsr, &u.am.payloadSize);
64673 assert( rc==SQLITE_OK ); /* DataSize() cannot fail */
64675 }else if( u.am.pC->pseudoTableReg>0 ){
64676 u.am.pReg = &aMem[u.am.pC->pseudoTableReg];
64677 assert( u.am.pReg->flags & MEM_Blob );
64678 assert( memIsValid(u.am.pReg) );
64679 u.am.payloadSize = u.am.pReg->n;
64680 u.am.zRec = u.am.pReg->z;
64681 u.am.pC->cacheStatus = (pOp->p5&OPFLAG_CLEARCACHE) ? CACHE_STALE : p->cacheCtr;
64682 assert( u.am.payloadSize==0 || u.am.zRec!=0 );
64683 }else{
64684 /* Consider the row to be NULL */
64685 u.am.payloadSize = 0;
64688 /* If u.am.payloadSize is 0, then just store a NULL */
64689 if( u.am.payloadSize==0 ){
64690 assert( u.am.pDest->flags&MEM_Null );
64691 goto op_column_out;
64693 assert( db->aLimit[SQLITE_LIMIT_LENGTH]>=0 );
64694 if( u.am.payloadSize > (u32)db->aLimit[SQLITE_LIMIT_LENGTH] ){
64695 goto too_big;
64698 u.am.nField = u.am.pC->nField;
64699 assert( u.am.p2<u.am.nField );
64701 /* Read and parse the table header. Store the results of the parse
64702 ** into the record header cache fields of the cursor.
64704 u.am.aType = u.am.pC->aType;
64705 if( u.am.pC->cacheStatus==p->cacheCtr ){
64706 u.am.aOffset = u.am.pC->aOffset;
64707 }else{
64708 assert(u.am.aType);
64709 u.am.avail = 0;
64710 u.am.pC->aOffset = u.am.aOffset = &u.am.aType[u.am.nField];
64711 u.am.pC->payloadSize = u.am.payloadSize;
64712 u.am.pC->cacheStatus = p->cacheCtr;
64714 /* Figure out how many bytes are in the header */
64715 if( u.am.zRec ){
64716 u.am.zData = u.am.zRec;
64717 }else{
64718 if( u.am.pC->isIndex ){
64719 u.am.zData = (char*)sqlite3BtreeKeyFetch(u.am.pCrsr, &u.am.avail);
64720 }else{
64721 u.am.zData = (char*)sqlite3BtreeDataFetch(u.am.pCrsr, &u.am.avail);
64723 /* If KeyFetch()/DataFetch() managed to get the entire payload,
64724 ** save the payload in the u.am.pC->aRow cache. That will save us from
64725 ** having to make additional calls to fetch the content portion of
64726 ** the record.
64728 assert( u.am.avail>=0 );
64729 if( u.am.payloadSize <= (u32)u.am.avail ){
64730 u.am.zRec = u.am.zData;
64731 u.am.pC->aRow = (u8*)u.am.zData;
64732 }else{
64733 u.am.pC->aRow = 0;
64736 /* The following assert is true in all cases accept when
64737 ** the database file has been corrupted externally.
64738 ** assert( u.am.zRec!=0 || u.am.avail>=u.am.payloadSize || u.am.avail>=9 ); */
64739 u.am.szHdr = getVarint32((u8*)u.am.zData, u.am.offset);
64741 /* Make sure a corrupt database has not given us an oversize header.
64742 ** Do this now to avoid an oversize memory allocation.
64744 ** Type entries can be between 1 and 5 bytes each. But 4 and 5 byte
64745 ** types use so much data space that there can only be 4096 and 32 of
64746 ** them, respectively. So the maximum header length results from a
64747 ** 3-byte type for each of the maximum of 32768 columns plus three
64748 ** extra bytes for the header length itself. 32768*3 + 3 = 98307.
64750 if( u.am.offset > 98307 ){
64751 rc = SQLITE_CORRUPT_BKPT;
64752 goto op_column_out;
64755 /* Compute in u.am.len the number of bytes of data we need to read in order
64756 ** to get u.am.nField type values. u.am.offset is an upper bound on this. But
64757 ** u.am.nField might be significantly less than the true number of columns
64758 ** in the table, and in that case, 5*u.am.nField+3 might be smaller than u.am.offset.
64759 ** We want to minimize u.am.len in order to limit the size of the memory
64760 ** allocation, especially if a corrupt database file has caused u.am.offset
64761 ** to be oversized. Offset is limited to 98307 above. But 98307 might
64762 ** still exceed Robson memory allocation limits on some configurations.
64763 ** On systems that cannot tolerate large memory allocations, u.am.nField*5+3
64764 ** will likely be much smaller since u.am.nField will likely be less than
64765 ** 20 or so. This insures that Robson memory allocation limits are
64766 ** not exceeded even for corrupt database files.
64768 u.am.len = u.am.nField*5 + 3;
64769 if( u.am.len > (int)u.am.offset ) u.am.len = (int)u.am.offset;
64771 /* The KeyFetch() or DataFetch() above are fast and will get the entire
64772 ** record header in most cases. But they will fail to get the complete
64773 ** record header if the record header does not fit on a single page
64774 ** in the B-Tree. When that happens, use sqlite3VdbeMemFromBtree() to
64775 ** acquire the complete header text.
64777 if( !u.am.zRec && u.am.avail<u.am.len ){
64778 u.am.sMem.flags = 0;
64779 u.am.sMem.db = 0;
64780 rc = sqlite3VdbeMemFromBtree(u.am.pCrsr, 0, u.am.len, u.am.pC->isIndex, &u.am.sMem);
64781 if( rc!=SQLITE_OK ){
64782 goto op_column_out;
64784 u.am.zData = u.am.sMem.z;
64786 u.am.zEndHdr = (u8 *)&u.am.zData[u.am.len];
64787 u.am.zIdx = (u8 *)&u.am.zData[u.am.szHdr];
64789 /* Scan the header and use it to fill in the u.am.aType[] and u.am.aOffset[]
64790 ** arrays. u.am.aType[u.am.i] will contain the type integer for the u.am.i-th
64791 ** column and u.am.aOffset[u.am.i] will contain the u.am.offset from the beginning
64792 ** of the record to the start of the data for the u.am.i-th column
64794 for(u.am.i=0; u.am.i<u.am.nField; u.am.i++){
64795 if( u.am.zIdx<u.am.zEndHdr ){
64796 u.am.aOffset[u.am.i] = u.am.offset;
64797 u.am.zIdx += getVarint32(u.am.zIdx, u.am.aType[u.am.i]);
64798 u.am.szField = sqlite3VdbeSerialTypeLen(u.am.aType[u.am.i]);
64799 u.am.offset += u.am.szField;
64800 if( u.am.offset<u.am.szField ){ /* True if u.am.offset overflows */
64801 u.am.zIdx = &u.am.zEndHdr[1]; /* Forces SQLITE_CORRUPT return below */
64802 break;
64804 }else{
64805 /* If u.am.i is less that u.am.nField, then there are less fields in this
64806 ** record than SetNumColumns indicated there are columns in the
64807 ** table. Set the u.am.offset for any extra columns not present in
64808 ** the record to 0. This tells code below to store a NULL
64809 ** instead of deserializing a value from the record.
64811 u.am.aOffset[u.am.i] = 0;
64814 sqlite3VdbeMemRelease(&u.am.sMem);
64815 u.am.sMem.flags = MEM_Null;
64817 /* If we have read more header data than was contained in the header,
64818 ** or if the end of the last field appears to be past the end of the
64819 ** record, or if the end of the last field appears to be before the end
64820 ** of the record (when all fields present), then we must be dealing
64821 ** with a corrupt database.
64823 if( (u.am.zIdx > u.am.zEndHdr) || (u.am.offset > u.am.payloadSize)
64824 || (u.am.zIdx==u.am.zEndHdr && u.am.offset!=u.am.payloadSize) ){
64825 rc = SQLITE_CORRUPT_BKPT;
64826 goto op_column_out;
64830 /* Get the column information. If u.am.aOffset[u.am.p2] is non-zero, then
64831 ** deserialize the value from the record. If u.am.aOffset[u.am.p2] is zero,
64832 ** then there are not enough fields in the record to satisfy the
64833 ** request. In this case, set the value NULL or to P4 if P4 is
64834 ** a pointer to a Mem object.
64836 if( u.am.aOffset[u.am.p2] ){
64837 assert( rc==SQLITE_OK );
64838 if( u.am.zRec ){
64839 sqlite3VdbeMemReleaseExternal(u.am.pDest);
64840 sqlite3VdbeSerialGet((u8 *)&u.am.zRec[u.am.aOffset[u.am.p2]], u.am.aType[u.am.p2], u.am.pDest);
64841 }else{
64842 u.am.len = sqlite3VdbeSerialTypeLen(u.am.aType[u.am.p2]);
64843 sqlite3VdbeMemMove(&u.am.sMem, u.am.pDest);
64844 rc = sqlite3VdbeMemFromBtree(u.am.pCrsr, u.am.aOffset[u.am.p2], u.am.len, u.am.pC->isIndex, &u.am.sMem);
64845 if( rc!=SQLITE_OK ){
64846 goto op_column_out;
64848 u.am.zData = u.am.sMem.z;
64849 sqlite3VdbeSerialGet((u8*)u.am.zData, u.am.aType[u.am.p2], u.am.pDest);
64851 u.am.pDest->enc = encoding;
64852 }else{
64853 if( pOp->p4type==P4_MEM ){
64854 sqlite3VdbeMemShallowCopy(u.am.pDest, pOp->p4.pMem, MEM_Static);
64855 }else{
64856 assert( u.am.pDest->flags&MEM_Null );
64860 /* If we dynamically allocated space to hold the data (in the
64861 ** sqlite3VdbeMemFromBtree() call above) then transfer control of that
64862 ** dynamically allocated space over to the u.am.pDest structure.
64863 ** This prevents a memory copy.
64865 if( u.am.sMem.zMalloc ){
64866 assert( u.am.sMem.z==u.am.sMem.zMalloc );
64867 assert( !(u.am.pDest->flags & MEM_Dyn) );
64868 assert( !(u.am.pDest->flags & (MEM_Blob|MEM_Str)) || u.am.pDest->z==u.am.sMem.z );
64869 u.am.pDest->flags &= ~(MEM_Ephem|MEM_Static);
64870 u.am.pDest->flags |= MEM_Term;
64871 u.am.pDest->z = u.am.sMem.z;
64872 u.am.pDest->zMalloc = u.am.sMem.zMalloc;
64875 rc = sqlite3VdbeMemMakeWriteable(u.am.pDest);
64877 op_column_out:
64878 UPDATE_MAX_BLOBSIZE(u.am.pDest);
64879 REGISTER_TRACE(pOp->p3, u.am.pDest);
64880 break;
64883 /* Opcode: Affinity P1 P2 * P4 *
64885 ** Apply affinities to a range of P2 registers starting with P1.
64887 ** P4 is a string that is P2 characters long. The nth character of the
64888 ** string indicates the column affinity that should be used for the nth
64889 ** memory cell in the range.
64891 case OP_Affinity: {
64892 #if 0 /* local variables moved into u.an */
64893 const char *zAffinity; /* The affinity to be applied */
64894 char cAff; /* A single character of affinity */
64895 #endif /* local variables moved into u.an */
64897 u.an.zAffinity = pOp->p4.z;
64898 assert( u.an.zAffinity!=0 );
64899 assert( u.an.zAffinity[pOp->p2]==0 );
64900 pIn1 = &aMem[pOp->p1];
64901 while( (u.an.cAff = *(u.an.zAffinity++))!=0 ){
64902 assert( pIn1 <= &p->aMem[p->nMem] );
64903 assert( memIsValid(pIn1) );
64904 ExpandBlob(pIn1);
64905 applyAffinity(pIn1, u.an.cAff, encoding);
64906 pIn1++;
64908 break;
64911 /* Opcode: MakeRecord P1 P2 P3 P4 *
64913 ** Convert P2 registers beginning with P1 into the [record format]
64914 ** use as a data record in a database table or as a key
64915 ** in an index. The OP_Column opcode can decode the record later.
64917 ** P4 may be a string that is P2 characters long. The nth character of the
64918 ** string indicates the column affinity that should be used for the nth
64919 ** field of the index key.
64921 ** The mapping from character to affinity is given by the SQLITE_AFF_
64922 ** macros defined in sqliteInt.h.
64924 ** If P4 is NULL then all index fields have the affinity NONE.
64926 case OP_MakeRecord: {
64927 #if 0 /* local variables moved into u.ao */
64928 u8 *zNewRecord; /* A buffer to hold the data for the new record */
64929 Mem *pRec; /* The new record */
64930 u64 nData; /* Number of bytes of data space */
64931 int nHdr; /* Number of bytes of header space */
64932 i64 nByte; /* Data space required for this record */
64933 int nZero; /* Number of zero bytes at the end of the record */
64934 int nVarint; /* Number of bytes in a varint */
64935 u32 serial_type; /* Type field */
64936 Mem *pData0; /* First field to be combined into the record */
64937 Mem *pLast; /* Last field of the record */
64938 int nField; /* Number of fields in the record */
64939 char *zAffinity; /* The affinity string for the record */
64940 int file_format; /* File format to use for encoding */
64941 int i; /* Space used in zNewRecord[] */
64942 int len; /* Length of a field */
64943 #endif /* local variables moved into u.ao */
64945 /* Assuming the record contains N fields, the record format looks
64946 ** like this:
64948 ** ------------------------------------------------------------------------
64949 ** | hdr-size | type 0 | type 1 | ... | type N-1 | data0 | ... | data N-1 |
64950 ** ------------------------------------------------------------------------
64952 ** Data(0) is taken from register P1. Data(1) comes from register P1+1
64953 ** and so froth.
64955 ** Each type field is a varint representing the serial type of the
64956 ** corresponding data element (see sqlite3VdbeSerialType()). The
64957 ** hdr-size field is also a varint which is the offset from the beginning
64958 ** of the record to data0.
64960 u.ao.nData = 0; /* Number of bytes of data space */
64961 u.ao.nHdr = 0; /* Number of bytes of header space */
64962 u.ao.nZero = 0; /* Number of zero bytes at the end of the record */
64963 u.ao.nField = pOp->p1;
64964 u.ao.zAffinity = pOp->p4.z;
64965 assert( u.ao.nField>0 && pOp->p2>0 && pOp->p2+u.ao.nField<=p->nMem+1 );
64966 u.ao.pData0 = &aMem[u.ao.nField];
64967 u.ao.nField = pOp->p2;
64968 u.ao.pLast = &u.ao.pData0[u.ao.nField-1];
64969 u.ao.file_format = p->minWriteFileFormat;
64971 /* Identify the output register */
64972 assert( pOp->p3<pOp->p1 || pOp->p3>=pOp->p1+pOp->p2 );
64973 pOut = &aMem[pOp->p3];
64974 memAboutToChange(p, pOut);
64976 /* Loop through the elements that will make up the record to figure
64977 ** out how much space is required for the new record.
64979 for(u.ao.pRec=u.ao.pData0; u.ao.pRec<=u.ao.pLast; u.ao.pRec++){
64980 assert( memIsValid(u.ao.pRec) );
64981 if( u.ao.zAffinity ){
64982 applyAffinity(u.ao.pRec, u.ao.zAffinity[u.ao.pRec-u.ao.pData0], encoding);
64984 if( u.ao.pRec->flags&MEM_Zero && u.ao.pRec->n>0 ){
64985 sqlite3VdbeMemExpandBlob(u.ao.pRec);
64987 u.ao.serial_type = sqlite3VdbeSerialType(u.ao.pRec, u.ao.file_format);
64988 u.ao.len = sqlite3VdbeSerialTypeLen(u.ao.serial_type);
64989 u.ao.nData += u.ao.len;
64990 u.ao.nHdr += sqlite3VarintLen(u.ao.serial_type);
64991 if( u.ao.pRec->flags & MEM_Zero ){
64992 /* Only pure zero-filled BLOBs can be input to this Opcode.
64993 ** We do not allow blobs with a prefix and a zero-filled tail. */
64994 u.ao.nZero += u.ao.pRec->u.nZero;
64995 }else if( u.ao.len ){
64996 u.ao.nZero = 0;
65000 /* Add the initial header varint and total the size */
65001 u.ao.nHdr += u.ao.nVarint = sqlite3VarintLen(u.ao.nHdr);
65002 if( u.ao.nVarint<sqlite3VarintLen(u.ao.nHdr) ){
65003 u.ao.nHdr++;
65005 u.ao.nByte = u.ao.nHdr+u.ao.nData-u.ao.nZero;
65006 if( u.ao.nByte>db->aLimit[SQLITE_LIMIT_LENGTH] ){
65007 goto too_big;
65010 /* Make sure the output register has a buffer large enough to store
65011 ** the new record. The output register (pOp->p3) is not allowed to
65012 ** be one of the input registers (because the following call to
65013 ** sqlite3VdbeMemGrow() could clobber the value before it is used).
65015 if( sqlite3VdbeMemGrow(pOut, (int)u.ao.nByte, 0) ){
65016 goto no_mem;
65018 u.ao.zNewRecord = (u8 *)pOut->z;
65020 /* Write the record */
65021 u.ao.i = putVarint32(u.ao.zNewRecord, u.ao.nHdr);
65022 for(u.ao.pRec=u.ao.pData0; u.ao.pRec<=u.ao.pLast; u.ao.pRec++){
65023 u.ao.serial_type = sqlite3VdbeSerialType(u.ao.pRec, u.ao.file_format);
65024 u.ao.i += putVarint32(&u.ao.zNewRecord[u.ao.i], u.ao.serial_type); /* serial type */
65026 for(u.ao.pRec=u.ao.pData0; u.ao.pRec<=u.ao.pLast; u.ao.pRec++){ /* serial data */
65027 u.ao.i += sqlite3VdbeSerialPut(&u.ao.zNewRecord[u.ao.i], (int)(u.ao.nByte-u.ao.i), u.ao.pRec,u.ao.file_format);
65029 assert( u.ao.i==u.ao.nByte );
65031 assert( pOp->p3>0 && pOp->p3<=p->nMem );
65032 pOut->n = (int)u.ao.nByte;
65033 pOut->flags = MEM_Blob | MEM_Dyn;
65034 pOut->xDel = 0;
65035 if( u.ao.nZero ){
65036 pOut->u.nZero = u.ao.nZero;
65037 pOut->flags |= MEM_Zero;
65039 pOut->enc = SQLITE_UTF8; /* In case the blob is ever converted to text */
65040 REGISTER_TRACE(pOp->p3, pOut);
65041 UPDATE_MAX_BLOBSIZE(pOut);
65042 break;
65045 /* Opcode: Count P1 P2 * * *
65047 ** Store the number of entries (an integer value) in the table or index
65048 ** opened by cursor P1 in register P2
65050 #ifndef SQLITE_OMIT_BTREECOUNT
65051 case OP_Count: { /* out2-prerelease */
65052 #if 0 /* local variables moved into u.ap */
65053 i64 nEntry;
65054 BtCursor *pCrsr;
65055 #endif /* local variables moved into u.ap */
65057 u.ap.pCrsr = p->apCsr[pOp->p1]->pCursor;
65058 if( u.ap.pCrsr ){
65059 rc = sqlite3BtreeCount(u.ap.pCrsr, &u.ap.nEntry);
65060 }else{
65061 u.ap.nEntry = 0;
65063 pOut->u.i = u.ap.nEntry;
65064 break;
65066 #endif
65068 /* Opcode: Savepoint P1 * * P4 *
65070 ** Open, release or rollback the savepoint named by parameter P4, depending
65071 ** on the value of P1. To open a new savepoint, P1==0. To release (commit) an
65072 ** existing savepoint, P1==1, or to rollback an existing savepoint P1==2.
65074 case OP_Savepoint: {
65075 #if 0 /* local variables moved into u.aq */
65076 int p1; /* Value of P1 operand */
65077 char *zName; /* Name of savepoint */
65078 int nName;
65079 Savepoint *pNew;
65080 Savepoint *pSavepoint;
65081 Savepoint *pTmp;
65082 int iSavepoint;
65083 int ii;
65084 #endif /* local variables moved into u.aq */
65086 u.aq.p1 = pOp->p1;
65087 u.aq.zName = pOp->p4.z;
65089 /* Assert that the u.aq.p1 parameter is valid. Also that if there is no open
65090 ** transaction, then there cannot be any savepoints.
65092 assert( db->pSavepoint==0 || db->autoCommit==0 );
65093 assert( u.aq.p1==SAVEPOINT_BEGIN||u.aq.p1==SAVEPOINT_RELEASE||u.aq.p1==SAVEPOINT_ROLLBACK );
65094 assert( db->pSavepoint || db->isTransactionSavepoint==0 );
65095 assert( checkSavepointCount(db) );
65097 if( u.aq.p1==SAVEPOINT_BEGIN ){
65098 if( db->writeVdbeCnt>0 ){
65099 /* A new savepoint cannot be created if there are active write
65100 ** statements (i.e. open read/write incremental blob handles).
65102 sqlite3SetString(&p->zErrMsg, db, "cannot open savepoint - "
65103 "SQL statements in progress");
65104 rc = SQLITE_BUSY;
65105 }else{
65106 u.aq.nName = sqlite3Strlen30(u.aq.zName);
65108 /* Create a new savepoint structure. */
65109 u.aq.pNew = sqlite3DbMallocRaw(db, sizeof(Savepoint)+u.aq.nName+1);
65110 if( u.aq.pNew ){
65111 u.aq.pNew->zName = (char *)&u.aq.pNew[1];
65112 memcpy(u.aq.pNew->zName, u.aq.zName, u.aq.nName+1);
65114 /* If there is no open transaction, then mark this as a special
65115 ** "transaction savepoint". */
65116 if( db->autoCommit ){
65117 db->autoCommit = 0;
65118 db->isTransactionSavepoint = 1;
65119 }else{
65120 db->nSavepoint++;
65123 /* Link the new savepoint into the database handle's list. */
65124 u.aq.pNew->pNext = db->pSavepoint;
65125 db->pSavepoint = u.aq.pNew;
65126 u.aq.pNew->nDeferredCons = db->nDeferredCons;
65129 }else{
65130 u.aq.iSavepoint = 0;
65132 /* Find the named savepoint. If there is no such savepoint, then an
65133 ** an error is returned to the user. */
65134 for(
65135 u.aq.pSavepoint = db->pSavepoint;
65136 u.aq.pSavepoint && sqlite3StrICmp(u.aq.pSavepoint->zName, u.aq.zName);
65137 u.aq.pSavepoint = u.aq.pSavepoint->pNext
65139 u.aq.iSavepoint++;
65141 if( !u.aq.pSavepoint ){
65142 sqlite3SetString(&p->zErrMsg, db, "no such savepoint: %s", u.aq.zName);
65143 rc = SQLITE_ERROR;
65144 }else if(
65145 db->writeVdbeCnt>0 || (u.aq.p1==SAVEPOINT_ROLLBACK && db->activeVdbeCnt>1)
65147 /* It is not possible to release (commit) a savepoint if there are
65148 ** active write statements. It is not possible to rollback a savepoint
65149 ** if there are any active statements at all.
65151 sqlite3SetString(&p->zErrMsg, db,
65152 "cannot %s savepoint - SQL statements in progress",
65153 (u.aq.p1==SAVEPOINT_ROLLBACK ? "rollback": "release")
65155 rc = SQLITE_BUSY;
65156 }else{
65158 /* Determine whether or not this is a transaction savepoint. If so,
65159 ** and this is a RELEASE command, then the current transaction
65160 ** is committed.
65162 int isTransaction = u.aq.pSavepoint->pNext==0 && db->isTransactionSavepoint;
65163 if( isTransaction && u.aq.p1==SAVEPOINT_RELEASE ){
65164 if( (rc = sqlite3VdbeCheckFk(p, 1))!=SQLITE_OK ){
65165 goto vdbe_return;
65167 db->autoCommit = 1;
65168 if( sqlite3VdbeHalt(p)==SQLITE_BUSY ){
65169 p->pc = pc;
65170 db->autoCommit = 0;
65171 p->rc = rc = SQLITE_BUSY;
65172 goto vdbe_return;
65174 db->isTransactionSavepoint = 0;
65175 rc = p->rc;
65176 }else{
65177 u.aq.iSavepoint = db->nSavepoint - u.aq.iSavepoint - 1;
65178 for(u.aq.ii=0; u.aq.ii<db->nDb; u.aq.ii++){
65179 rc = sqlite3BtreeSavepoint(db->aDb[u.aq.ii].pBt, u.aq.p1, u.aq.iSavepoint);
65180 if( rc!=SQLITE_OK ){
65181 goto abort_due_to_error;
65184 if( u.aq.p1==SAVEPOINT_ROLLBACK && (db->flags&SQLITE_InternChanges)!=0 ){
65185 sqlite3ExpirePreparedStatements(db);
65186 sqlite3ResetInternalSchema(db, -1);
65187 db->flags = (db->flags | SQLITE_InternChanges);
65191 /* Regardless of whether this is a RELEASE or ROLLBACK, destroy all
65192 ** savepoints nested inside of the savepoint being operated on. */
65193 while( db->pSavepoint!=u.aq.pSavepoint ){
65194 u.aq.pTmp = db->pSavepoint;
65195 db->pSavepoint = u.aq.pTmp->pNext;
65196 sqlite3DbFree(db, u.aq.pTmp);
65197 db->nSavepoint--;
65200 /* If it is a RELEASE, then destroy the savepoint being operated on
65201 ** too. If it is a ROLLBACK TO, then set the number of deferred
65202 ** constraint violations present in the database to the value stored
65203 ** when the savepoint was created. */
65204 if( u.aq.p1==SAVEPOINT_RELEASE ){
65205 assert( u.aq.pSavepoint==db->pSavepoint );
65206 db->pSavepoint = u.aq.pSavepoint->pNext;
65207 sqlite3DbFree(db, u.aq.pSavepoint);
65208 if( !isTransaction ){
65209 db->nSavepoint--;
65211 }else{
65212 db->nDeferredCons = u.aq.pSavepoint->nDeferredCons;
65217 break;
65220 /* Opcode: AutoCommit P1 P2 * * *
65222 ** Set the database auto-commit flag to P1 (1 or 0). If P2 is true, roll
65223 ** back any currently active btree transactions. If there are any active
65224 ** VMs (apart from this one), then a ROLLBACK fails. A COMMIT fails if
65225 ** there are active writing VMs or active VMs that use shared cache.
65227 ** This instruction causes the VM to halt.
65229 case OP_AutoCommit: {
65230 #if 0 /* local variables moved into u.ar */
65231 int desiredAutoCommit;
65232 int iRollback;
65233 int turnOnAC;
65234 #endif /* local variables moved into u.ar */
65236 u.ar.desiredAutoCommit = pOp->p1;
65237 u.ar.iRollback = pOp->p2;
65238 u.ar.turnOnAC = u.ar.desiredAutoCommit && !db->autoCommit;
65239 assert( u.ar.desiredAutoCommit==1 || u.ar.desiredAutoCommit==0 );
65240 assert( u.ar.desiredAutoCommit==1 || u.ar.iRollback==0 );
65241 assert( db->activeVdbeCnt>0 ); /* At least this one VM is active */
65243 if( u.ar.turnOnAC && u.ar.iRollback && db->activeVdbeCnt>1 ){
65244 /* If this instruction implements a ROLLBACK and other VMs are
65245 ** still running, and a transaction is active, return an error indicating
65246 ** that the other VMs must complete first.
65248 sqlite3SetString(&p->zErrMsg, db, "cannot rollback transaction - "
65249 "SQL statements in progress");
65250 rc = SQLITE_BUSY;
65251 }else if( u.ar.turnOnAC && !u.ar.iRollback && db->writeVdbeCnt>0 ){
65252 /* If this instruction implements a COMMIT and other VMs are writing
65253 ** return an error indicating that the other VMs must complete first.
65255 sqlite3SetString(&p->zErrMsg, db, "cannot commit transaction - "
65256 "SQL statements in progress");
65257 rc = SQLITE_BUSY;
65258 }else if( u.ar.desiredAutoCommit!=db->autoCommit ){
65259 if( u.ar.iRollback ){
65260 assert( u.ar.desiredAutoCommit==1 );
65261 sqlite3RollbackAll(db);
65262 db->autoCommit = 1;
65263 }else if( (rc = sqlite3VdbeCheckFk(p, 1))!=SQLITE_OK ){
65264 goto vdbe_return;
65265 }else{
65266 db->autoCommit = (u8)u.ar.desiredAutoCommit;
65267 if( sqlite3VdbeHalt(p)==SQLITE_BUSY ){
65268 p->pc = pc;
65269 db->autoCommit = (u8)(1-u.ar.desiredAutoCommit);
65270 p->rc = rc = SQLITE_BUSY;
65271 goto vdbe_return;
65274 assert( db->nStatement==0 );
65275 sqlite3CloseSavepoints(db);
65276 if( p->rc==SQLITE_OK ){
65277 rc = SQLITE_DONE;
65278 }else{
65279 rc = SQLITE_ERROR;
65281 goto vdbe_return;
65282 }else{
65283 sqlite3SetString(&p->zErrMsg, db,
65284 (!u.ar.desiredAutoCommit)?"cannot start a transaction within a transaction":(
65285 (u.ar.iRollback)?"cannot rollback - no transaction is active":
65286 "cannot commit - no transaction is active"));
65288 rc = SQLITE_ERROR;
65290 break;
65293 /* Opcode: Transaction P1 P2 * * *
65295 ** Begin a transaction. The transaction ends when a Commit or Rollback
65296 ** opcode is encountered. Depending on the ON CONFLICT setting, the
65297 ** transaction might also be rolled back if an error is encountered.
65299 ** P1 is the index of the database file on which the transaction is
65300 ** started. Index 0 is the main database file and index 1 is the
65301 ** file used for temporary tables. Indices of 2 or more are used for
65302 ** attached databases.
65304 ** If P2 is non-zero, then a write-transaction is started. A RESERVED lock is
65305 ** obtained on the database file when a write-transaction is started. No
65306 ** other process can start another write transaction while this transaction is
65307 ** underway. Starting a write transaction also creates a rollback journal. A
65308 ** write transaction must be started before any changes can be made to the
65309 ** database. If P2 is 2 or greater then an EXCLUSIVE lock is also obtained
65310 ** on the file.
65312 ** If a write-transaction is started and the Vdbe.usesStmtJournal flag is
65313 ** true (this flag is set if the Vdbe may modify more than one row and may
65314 ** throw an ABORT exception), a statement transaction may also be opened.
65315 ** More specifically, a statement transaction is opened iff the database
65316 ** connection is currently not in autocommit mode, or if there are other
65317 ** active statements. A statement transaction allows the affects of this
65318 ** VDBE to be rolled back after an error without having to roll back the
65319 ** entire transaction. If no error is encountered, the statement transaction
65320 ** will automatically commit when the VDBE halts.
65322 ** If P2 is zero, then a read-lock is obtained on the database file.
65324 case OP_Transaction: {
65325 #if 0 /* local variables moved into u.as */
65326 Btree *pBt;
65327 #endif /* local variables moved into u.as */
65329 assert( pOp->p1>=0 && pOp->p1<db->nDb );
65330 assert( (p->btreeMask & (((yDbMask)1)<<pOp->p1))!=0 );
65331 u.as.pBt = db->aDb[pOp->p1].pBt;
65333 if( u.as.pBt ){
65334 rc = sqlite3BtreeBeginTrans(u.as.pBt, pOp->p2);
65335 if( rc==SQLITE_BUSY ){
65336 p->pc = pc;
65337 p->rc = rc = SQLITE_BUSY;
65338 goto vdbe_return;
65340 if( rc!=SQLITE_OK ){
65341 goto abort_due_to_error;
65344 if( pOp->p2 && p->usesStmtJournal
65345 && (db->autoCommit==0 || db->activeVdbeCnt>1)
65347 assert( sqlite3BtreeIsInTrans(u.as.pBt) );
65348 if( p->iStatement==0 ){
65349 assert( db->nStatement>=0 && db->nSavepoint>=0 );
65350 db->nStatement++;
65351 p->iStatement = db->nSavepoint + db->nStatement;
65353 rc = sqlite3BtreeBeginStmt(u.as.pBt, p->iStatement);
65355 /* Store the current value of the database handles deferred constraint
65356 ** counter. If the statement transaction needs to be rolled back,
65357 ** the value of this counter needs to be restored too. */
65358 p->nStmtDefCons = db->nDeferredCons;
65361 break;
65364 /* Opcode: ReadCookie P1 P2 P3 * *
65366 ** Read cookie number P3 from database P1 and write it into register P2.
65367 ** P3==1 is the schema version. P3==2 is the database format.
65368 ** P3==3 is the recommended pager cache size, and so forth. P1==0 is
65369 ** the main database file and P1==1 is the database file used to store
65370 ** temporary tables.
65372 ** There must be a read-lock on the database (either a transaction
65373 ** must be started or there must be an open cursor) before
65374 ** executing this instruction.
65376 case OP_ReadCookie: { /* out2-prerelease */
65377 #if 0 /* local variables moved into u.at */
65378 int iMeta;
65379 int iDb;
65380 int iCookie;
65381 #endif /* local variables moved into u.at */
65383 u.at.iDb = pOp->p1;
65384 u.at.iCookie = pOp->p3;
65385 assert( pOp->p3<SQLITE_N_BTREE_META );
65386 assert( u.at.iDb>=0 && u.at.iDb<db->nDb );
65387 assert( db->aDb[u.at.iDb].pBt!=0 );
65388 assert( (p->btreeMask & (((yDbMask)1)<<u.at.iDb))!=0 );
65390 sqlite3BtreeGetMeta(db->aDb[u.at.iDb].pBt, u.at.iCookie, (u32 *)&u.at.iMeta);
65391 pOut->u.i = u.at.iMeta;
65392 break;
65395 /* Opcode: SetCookie P1 P2 P3 * *
65397 ** Write the content of register P3 (interpreted as an integer)
65398 ** into cookie number P2 of database P1. P2==1 is the schema version.
65399 ** P2==2 is the database format. P2==3 is the recommended pager cache
65400 ** size, and so forth. P1==0 is the main database file and P1==1 is the
65401 ** database file used to store temporary tables.
65403 ** A transaction must be started before executing this opcode.
65405 case OP_SetCookie: { /* in3 */
65406 #if 0 /* local variables moved into u.au */
65407 Db *pDb;
65408 #endif /* local variables moved into u.au */
65409 assert( pOp->p2<SQLITE_N_BTREE_META );
65410 assert( pOp->p1>=0 && pOp->p1<db->nDb );
65411 assert( (p->btreeMask & (((yDbMask)1)<<pOp->p1))!=0 );
65412 u.au.pDb = &db->aDb[pOp->p1];
65413 assert( u.au.pDb->pBt!=0 );
65414 assert( sqlite3SchemaMutexHeld(db, pOp->p1, 0) );
65415 pIn3 = &aMem[pOp->p3];
65416 sqlite3VdbeMemIntegerify(pIn3);
65417 /* See note about index shifting on OP_ReadCookie */
65418 rc = sqlite3BtreeUpdateMeta(u.au.pDb->pBt, pOp->p2, (int)pIn3->u.i);
65419 if( pOp->p2==BTREE_SCHEMA_VERSION ){
65420 /* When the schema cookie changes, record the new cookie internally */
65421 u.au.pDb->pSchema->schema_cookie = (int)pIn3->u.i;
65422 db->flags |= SQLITE_InternChanges;
65423 }else if( pOp->p2==BTREE_FILE_FORMAT ){
65424 /* Record changes in the file format */
65425 u.au.pDb->pSchema->file_format = (u8)pIn3->u.i;
65427 if( pOp->p1==1 ){
65428 /* Invalidate all prepared statements whenever the TEMP database
65429 ** schema is changed. Ticket #1644 */
65430 sqlite3ExpirePreparedStatements(db);
65431 p->expired = 0;
65433 break;
65436 /* Opcode: VerifyCookie P1 P2 P3 * *
65438 ** Check the value of global database parameter number 0 (the
65439 ** schema version) and make sure it is equal to P2 and that the
65440 ** generation counter on the local schema parse equals P3.
65442 ** P1 is the database number which is 0 for the main database file
65443 ** and 1 for the file holding temporary tables and some higher number
65444 ** for auxiliary databases.
65446 ** The cookie changes its value whenever the database schema changes.
65447 ** This operation is used to detect when that the cookie has changed
65448 ** and that the current process needs to reread the schema.
65450 ** Either a transaction needs to have been started or an OP_Open needs
65451 ** to be executed (to establish a read lock) before this opcode is
65452 ** invoked.
65454 case OP_VerifyCookie: {
65455 #if 0 /* local variables moved into u.av */
65456 int iMeta;
65457 int iGen;
65458 Btree *pBt;
65459 #endif /* local variables moved into u.av */
65461 assert( pOp->p1>=0 && pOp->p1<db->nDb );
65462 assert( (p->btreeMask & (((yDbMask)1)<<pOp->p1))!=0 );
65463 assert( sqlite3SchemaMutexHeld(db, pOp->p1, 0) );
65464 u.av.pBt = db->aDb[pOp->p1].pBt;
65465 if( u.av.pBt ){
65466 sqlite3BtreeGetMeta(u.av.pBt, BTREE_SCHEMA_VERSION, (u32 *)&u.av.iMeta);
65467 u.av.iGen = db->aDb[pOp->p1].pSchema->iGeneration;
65468 }else{
65469 u.av.iGen = u.av.iMeta = 0;
65471 if( u.av.iMeta!=pOp->p2 || u.av.iGen!=pOp->p3 ){
65472 sqlite3DbFree(db, p->zErrMsg);
65473 p->zErrMsg = sqlite3DbStrDup(db, "database schema has changed");
65474 /* If the schema-cookie from the database file matches the cookie
65475 ** stored with the in-memory representation of the schema, do
65476 ** not reload the schema from the database file.
65478 ** If virtual-tables are in use, this is not just an optimization.
65479 ** Often, v-tables store their data in other SQLite tables, which
65480 ** are queried from within xNext() and other v-table methods using
65481 ** prepared queries. If such a query is out-of-date, we do not want to
65482 ** discard the database schema, as the user code implementing the
65483 ** v-table would have to be ready for the sqlite3_vtab structure itself
65484 ** to be invalidated whenever sqlite3_step() is called from within
65485 ** a v-table method.
65487 if( db->aDb[pOp->p1].pSchema->schema_cookie!=u.av.iMeta ){
65488 sqlite3ResetInternalSchema(db, pOp->p1);
65491 p->expired = 1;
65492 rc = SQLITE_SCHEMA;
65494 break;
65497 /* Opcode: OpenRead P1 P2 P3 P4 P5
65499 ** Open a read-only cursor for the database table whose root page is
65500 ** P2 in a database file. The database file is determined by P3.
65501 ** P3==0 means the main database, P3==1 means the database used for
65502 ** temporary tables, and P3>1 means used the corresponding attached
65503 ** database. Give the new cursor an identifier of P1. The P1
65504 ** values need not be contiguous but all P1 values should be small integers.
65505 ** It is an error for P1 to be negative.
65507 ** If P5!=0 then use the content of register P2 as the root page, not
65508 ** the value of P2 itself.
65510 ** There will be a read lock on the database whenever there is an
65511 ** open cursor. If the database was unlocked prior to this instruction
65512 ** then a read lock is acquired as part of this instruction. A read
65513 ** lock allows other processes to read the database but prohibits
65514 ** any other process from modifying the database. The read lock is
65515 ** released when all cursors are closed. If this instruction attempts
65516 ** to get a read lock but fails, the script terminates with an
65517 ** SQLITE_BUSY error code.
65519 ** The P4 value may be either an integer (P4_INT32) or a pointer to
65520 ** a KeyInfo structure (P4_KEYINFO). If it is a pointer to a KeyInfo
65521 ** structure, then said structure defines the content and collating
65522 ** sequence of the index being opened. Otherwise, if P4 is an integer
65523 ** value, it is set to the number of columns in the table.
65525 ** See also OpenWrite.
65527 /* Opcode: OpenWrite P1 P2 P3 P4 P5
65529 ** Open a read/write cursor named P1 on the table or index whose root
65530 ** page is P2. Or if P5!=0 use the content of register P2 to find the
65531 ** root page.
65533 ** The P4 value may be either an integer (P4_INT32) or a pointer to
65534 ** a KeyInfo structure (P4_KEYINFO). If it is a pointer to a KeyInfo
65535 ** structure, then said structure defines the content and collating
65536 ** sequence of the index being opened. Otherwise, if P4 is an integer
65537 ** value, it is set to the number of columns in the table, or to the
65538 ** largest index of any column of the table that is actually used.
65540 ** This instruction works just like OpenRead except that it opens the cursor
65541 ** in read/write mode. For a given table, there can be one or more read-only
65542 ** cursors or a single read/write cursor but not both.
65544 ** See also OpenRead.
65546 case OP_OpenRead:
65547 case OP_OpenWrite: {
65548 #if 0 /* local variables moved into u.aw */
65549 int nField;
65550 KeyInfo *pKeyInfo;
65551 int p2;
65552 int iDb;
65553 int wrFlag;
65554 Btree *pX;
65555 VdbeCursor *pCur;
65556 Db *pDb;
65557 #endif /* local variables moved into u.aw */
65559 if( p->expired ){
65560 rc = SQLITE_ABORT;
65561 break;
65564 u.aw.nField = 0;
65565 u.aw.pKeyInfo = 0;
65566 u.aw.p2 = pOp->p2;
65567 u.aw.iDb = pOp->p3;
65568 assert( u.aw.iDb>=0 && u.aw.iDb<db->nDb );
65569 assert( (p->btreeMask & (((yDbMask)1)<<u.aw.iDb))!=0 );
65570 u.aw.pDb = &db->aDb[u.aw.iDb];
65571 u.aw.pX = u.aw.pDb->pBt;
65572 assert( u.aw.pX!=0 );
65573 if( pOp->opcode==OP_OpenWrite ){
65574 u.aw.wrFlag = 1;
65575 assert( sqlite3SchemaMutexHeld(db, u.aw.iDb, 0) );
65576 if( u.aw.pDb->pSchema->file_format < p->minWriteFileFormat ){
65577 p->minWriteFileFormat = u.aw.pDb->pSchema->file_format;
65579 }else{
65580 u.aw.wrFlag = 0;
65582 if( pOp->p5 ){
65583 assert( u.aw.p2>0 );
65584 assert( u.aw.p2<=p->nMem );
65585 pIn2 = &aMem[u.aw.p2];
65586 assert( memIsValid(pIn2) );
65587 assert( (pIn2->flags & MEM_Int)!=0 );
65588 sqlite3VdbeMemIntegerify(pIn2);
65589 u.aw.p2 = (int)pIn2->u.i;
65590 /* The u.aw.p2 value always comes from a prior OP_CreateTable opcode and
65591 ** that opcode will always set the u.aw.p2 value to 2 or more or else fail.
65592 ** If there were a failure, the prepared statement would have halted
65593 ** before reaching this instruction. */
65594 if( NEVER(u.aw.p2<2) ) {
65595 rc = SQLITE_CORRUPT_BKPT;
65596 goto abort_due_to_error;
65599 if( pOp->p4type==P4_KEYINFO ){
65600 u.aw.pKeyInfo = pOp->p4.pKeyInfo;
65601 u.aw.pKeyInfo->enc = ENC(p->db);
65602 u.aw.nField = u.aw.pKeyInfo->nField+1;
65603 }else if( pOp->p4type==P4_INT32 ){
65604 u.aw.nField = pOp->p4.i;
65606 assert( pOp->p1>=0 );
65607 u.aw.pCur = allocateCursor(p, pOp->p1, u.aw.nField, u.aw.iDb, 1);
65608 if( u.aw.pCur==0 ) goto no_mem;
65609 u.aw.pCur->nullRow = 1;
65610 u.aw.pCur->isOrdered = 1;
65611 rc = sqlite3BtreeCursor(u.aw.pX, u.aw.p2, u.aw.wrFlag, u.aw.pKeyInfo, u.aw.pCur->pCursor);
65612 u.aw.pCur->pKeyInfo = u.aw.pKeyInfo;
65614 /* Since it performs no memory allocation or IO, the only values that
65615 ** sqlite3BtreeCursor() may return are SQLITE_EMPTY and SQLITE_OK.
65616 ** SQLITE_EMPTY is only returned when attempting to open the table
65617 ** rooted at page 1 of a zero-byte database. */
65618 assert( rc==SQLITE_EMPTY || rc==SQLITE_OK );
65619 if( rc==SQLITE_EMPTY ){
65620 u.aw.pCur->pCursor = 0;
65621 rc = SQLITE_OK;
65624 /* Set the VdbeCursor.isTable and isIndex variables. Previous versions of
65625 ** SQLite used to check if the root-page flags were sane at this point
65626 ** and report database corruption if they were not, but this check has
65627 ** since moved into the btree layer. */
65628 u.aw.pCur->isTable = pOp->p4type!=P4_KEYINFO;
65629 u.aw.pCur->isIndex = !u.aw.pCur->isTable;
65630 break;
65633 /* Opcode: OpenEphemeral P1 P2 * P4 *
65635 ** Open a new cursor P1 to a transient table.
65636 ** The cursor is always opened read/write even if
65637 ** the main database is read-only. The ephemeral
65638 ** table is deleted automatically when the cursor is closed.
65640 ** P2 is the number of columns in the ephemeral table.
65641 ** The cursor points to a BTree table if P4==0 and to a BTree index
65642 ** if P4 is not 0. If P4 is not NULL, it points to a KeyInfo structure
65643 ** that defines the format of keys in the index.
65645 ** This opcode was once called OpenTemp. But that created
65646 ** confusion because the term "temp table", might refer either
65647 ** to a TEMP table at the SQL level, or to a table opened by
65648 ** this opcode. Then this opcode was call OpenVirtual. But
65649 ** that created confusion with the whole virtual-table idea.
65651 /* Opcode: OpenAutoindex P1 P2 * P4 *
65653 ** This opcode works the same as OP_OpenEphemeral. It has a
65654 ** different name to distinguish its use. Tables created using
65655 ** by this opcode will be used for automatically created transient
65656 ** indices in joins.
65658 case OP_OpenAutoindex:
65659 case OP_OpenEphemeral: {
65660 #if 0 /* local variables moved into u.ax */
65661 VdbeCursor *pCx;
65662 #endif /* local variables moved into u.ax */
65663 static const int vfsFlags =
65664 SQLITE_OPEN_READWRITE |
65665 SQLITE_OPEN_CREATE |
65666 SQLITE_OPEN_EXCLUSIVE |
65667 SQLITE_OPEN_DELETEONCLOSE |
65668 SQLITE_OPEN_TRANSIENT_DB;
65670 assert( pOp->p1>=0 );
65671 u.ax.pCx = allocateCursor(p, pOp->p1, pOp->p2, -1, 1);
65672 if( u.ax.pCx==0 ) goto no_mem;
65673 u.ax.pCx->nullRow = 1;
65674 rc = sqlite3BtreeOpen(0, db, &u.ax.pCx->pBt,
65675 BTREE_OMIT_JOURNAL | BTREE_SINGLE | pOp->p5, vfsFlags);
65676 if( rc==SQLITE_OK ){
65677 rc = sqlite3BtreeBeginTrans(u.ax.pCx->pBt, 1);
65679 if( rc==SQLITE_OK ){
65680 /* If a transient index is required, create it by calling
65681 ** sqlite3BtreeCreateTable() with the BTREE_BLOBKEY flag before
65682 ** opening it. If a transient table is required, just use the
65683 ** automatically created table with root-page 1 (an BLOB_INTKEY table).
65685 if( pOp->p4.pKeyInfo ){
65686 int pgno;
65687 assert( pOp->p4type==P4_KEYINFO );
65688 rc = sqlite3BtreeCreateTable(u.ax.pCx->pBt, &pgno, BTREE_BLOBKEY);
65689 if( rc==SQLITE_OK ){
65690 assert( pgno==MASTER_ROOT+1 );
65691 rc = sqlite3BtreeCursor(u.ax.pCx->pBt, pgno, 1,
65692 (KeyInfo*)pOp->p4.z, u.ax.pCx->pCursor);
65693 u.ax.pCx->pKeyInfo = pOp->p4.pKeyInfo;
65694 u.ax.pCx->pKeyInfo->enc = ENC(p->db);
65696 u.ax.pCx->isTable = 0;
65697 }else{
65698 rc = sqlite3BtreeCursor(u.ax.pCx->pBt, MASTER_ROOT, 1, 0, u.ax.pCx->pCursor);
65699 u.ax.pCx->isTable = 1;
65702 u.ax.pCx->isOrdered = (pOp->p5!=BTREE_UNORDERED);
65703 u.ax.pCx->isIndex = !u.ax.pCx->isTable;
65704 break;
65707 /* Opcode: OpenPseudo P1 P2 P3 * *
65709 ** Open a new cursor that points to a fake table that contains a single
65710 ** row of data. The content of that one row in the content of memory
65711 ** register P2. In other words, cursor P1 becomes an alias for the
65712 ** MEM_Blob content contained in register P2.
65714 ** A pseudo-table created by this opcode is used to hold a single
65715 ** row output from the sorter so that the row can be decomposed into
65716 ** individual columns using the OP_Column opcode. The OP_Column opcode
65717 ** is the only cursor opcode that works with a pseudo-table.
65719 ** P3 is the number of fields in the records that will be stored by
65720 ** the pseudo-table.
65722 case OP_OpenPseudo: {
65723 #if 0 /* local variables moved into u.ay */
65724 VdbeCursor *pCx;
65725 #endif /* local variables moved into u.ay */
65727 assert( pOp->p1>=0 );
65728 u.ay.pCx = allocateCursor(p, pOp->p1, pOp->p3, -1, 0);
65729 if( u.ay.pCx==0 ) goto no_mem;
65730 u.ay.pCx->nullRow = 1;
65731 u.ay.pCx->pseudoTableReg = pOp->p2;
65732 u.ay.pCx->isTable = 1;
65733 u.ay.pCx->isIndex = 0;
65734 break;
65737 /* Opcode: Close P1 * * * *
65739 ** Close a cursor previously opened as P1. If P1 is not
65740 ** currently open, this instruction is a no-op.
65742 case OP_Close: {
65743 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
65744 sqlite3VdbeFreeCursor(p, p->apCsr[pOp->p1]);
65745 p->apCsr[pOp->p1] = 0;
65746 break;
65749 /* Opcode: SeekGe P1 P2 P3 P4 *
65751 ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
65752 ** use the value in register P3 as the key. If cursor P1 refers
65753 ** to an SQL index, then P3 is the first in an array of P4 registers
65754 ** that are used as an unpacked index key.
65756 ** Reposition cursor P1 so that it points to the smallest entry that
65757 ** is greater than or equal to the key value. If there are no records
65758 ** greater than or equal to the key and P2 is not zero, then jump to P2.
65760 ** See also: Found, NotFound, Distinct, SeekLt, SeekGt, SeekLe
65762 /* Opcode: SeekGt P1 P2 P3 P4 *
65764 ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
65765 ** use the value in register P3 as a key. If cursor P1 refers
65766 ** to an SQL index, then P3 is the first in an array of P4 registers
65767 ** that are used as an unpacked index key.
65769 ** Reposition cursor P1 so that it points to the smallest entry that
65770 ** is greater than the key value. If there are no records greater than
65771 ** the key and P2 is not zero, then jump to P2.
65773 ** See also: Found, NotFound, Distinct, SeekLt, SeekGe, SeekLe
65775 /* Opcode: SeekLt P1 P2 P3 P4 *
65777 ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
65778 ** use the value in register P3 as a key. If cursor P1 refers
65779 ** to an SQL index, then P3 is the first in an array of P4 registers
65780 ** that are used as an unpacked index key.
65782 ** Reposition cursor P1 so that it points to the largest entry that
65783 ** is less than the key value. If there are no records less than
65784 ** the key and P2 is not zero, then jump to P2.
65786 ** See also: Found, NotFound, Distinct, SeekGt, SeekGe, SeekLe
65788 /* Opcode: SeekLe P1 P2 P3 P4 *
65790 ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
65791 ** use the value in register P3 as a key. If cursor P1 refers
65792 ** to an SQL index, then P3 is the first in an array of P4 registers
65793 ** that are used as an unpacked index key.
65795 ** Reposition cursor P1 so that it points to the largest entry that
65796 ** is less than or equal to the key value. If there are no records
65797 ** less than or equal to the key and P2 is not zero, then jump to P2.
65799 ** See also: Found, NotFound, Distinct, SeekGt, SeekGe, SeekLt
65801 case OP_SeekLt: /* jump, in3 */
65802 case OP_SeekLe: /* jump, in3 */
65803 case OP_SeekGe: /* jump, in3 */
65804 case OP_SeekGt: { /* jump, in3 */
65805 #if 0 /* local variables moved into u.az */
65806 int res;
65807 int oc;
65808 VdbeCursor *pC;
65809 UnpackedRecord r;
65810 int nField;
65811 i64 iKey; /* The rowid we are to seek to */
65812 #endif /* local variables moved into u.az */
65814 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
65815 assert( pOp->p2!=0 );
65816 u.az.pC = p->apCsr[pOp->p1];
65817 assert( u.az.pC!=0 );
65818 assert( u.az.pC->pseudoTableReg==0 );
65819 assert( OP_SeekLe == OP_SeekLt+1 );
65820 assert( OP_SeekGe == OP_SeekLt+2 );
65821 assert( OP_SeekGt == OP_SeekLt+3 );
65822 assert( u.az.pC->isOrdered );
65823 if( u.az.pC->pCursor!=0 ){
65824 u.az.oc = pOp->opcode;
65825 u.az.pC->nullRow = 0;
65826 if( u.az.pC->isTable ){
65827 /* The input value in P3 might be of any type: integer, real, string,
65828 ** blob, or NULL. But it needs to be an integer before we can do
65829 ** the seek, so covert it. */
65830 pIn3 = &aMem[pOp->p3];
65831 applyNumericAffinity(pIn3);
65832 u.az.iKey = sqlite3VdbeIntValue(pIn3);
65833 u.az.pC->rowidIsValid = 0;
65835 /* If the P3 value could not be converted into an integer without
65836 ** loss of information, then special processing is required... */
65837 if( (pIn3->flags & MEM_Int)==0 ){
65838 if( (pIn3->flags & MEM_Real)==0 ){
65839 /* If the P3 value cannot be converted into any kind of a number,
65840 ** then the seek is not possible, so jump to P2 */
65841 pc = pOp->p2 - 1;
65842 break;
65844 /* If we reach this point, then the P3 value must be a floating
65845 ** point number. */
65846 assert( (pIn3->flags & MEM_Real)!=0 );
65848 if( u.az.iKey==SMALLEST_INT64 && (pIn3->r<(double)u.az.iKey || pIn3->r>0) ){
65849 /* The P3 value is too large in magnitude to be expressed as an
65850 ** integer. */
65851 u.az.res = 1;
65852 if( pIn3->r<0 ){
65853 if( u.az.oc>=OP_SeekGe ){ assert( u.az.oc==OP_SeekGe || u.az.oc==OP_SeekGt );
65854 rc = sqlite3BtreeFirst(u.az.pC->pCursor, &u.az.res);
65855 if( rc!=SQLITE_OK ) goto abort_due_to_error;
65857 }else{
65858 if( u.az.oc<=OP_SeekLe ){ assert( u.az.oc==OP_SeekLt || u.az.oc==OP_SeekLe );
65859 rc = sqlite3BtreeLast(u.az.pC->pCursor, &u.az.res);
65860 if( rc!=SQLITE_OK ) goto abort_due_to_error;
65863 if( u.az.res ){
65864 pc = pOp->p2 - 1;
65866 break;
65867 }else if( u.az.oc==OP_SeekLt || u.az.oc==OP_SeekGe ){
65868 /* Use the ceiling() function to convert real->int */
65869 if( pIn3->r > (double)u.az.iKey ) u.az.iKey++;
65870 }else{
65871 /* Use the floor() function to convert real->int */
65872 assert( u.az.oc==OP_SeekLe || u.az.oc==OP_SeekGt );
65873 if( pIn3->r < (double)u.az.iKey ) u.az.iKey--;
65876 rc = sqlite3BtreeMovetoUnpacked(u.az.pC->pCursor, 0, (u64)u.az.iKey, 0, &u.az.res);
65877 if( rc!=SQLITE_OK ){
65878 goto abort_due_to_error;
65880 if( u.az.res==0 ){
65881 u.az.pC->rowidIsValid = 1;
65882 u.az.pC->lastRowid = u.az.iKey;
65884 }else{
65885 u.az.nField = pOp->p4.i;
65886 assert( pOp->p4type==P4_INT32 );
65887 assert( u.az.nField>0 );
65888 u.az.r.pKeyInfo = u.az.pC->pKeyInfo;
65889 u.az.r.nField = (u16)u.az.nField;
65891 /* The next line of code computes as follows, only faster:
65892 ** if( u.az.oc==OP_SeekGt || u.az.oc==OP_SeekLe ){
65893 ** u.az.r.flags = UNPACKED_INCRKEY;
65894 ** }else{
65895 ** u.az.r.flags = 0;
65896 ** }
65898 u.az.r.flags = (u16)(UNPACKED_INCRKEY * (1 & (u.az.oc - OP_SeekLt)));
65899 assert( u.az.oc!=OP_SeekGt || u.az.r.flags==UNPACKED_INCRKEY );
65900 assert( u.az.oc!=OP_SeekLe || u.az.r.flags==UNPACKED_INCRKEY );
65901 assert( u.az.oc!=OP_SeekGe || u.az.r.flags==0 );
65902 assert( u.az.oc!=OP_SeekLt || u.az.r.flags==0 );
65904 u.az.r.aMem = &aMem[pOp->p3];
65905 #ifdef SQLITE_DEBUG
65906 { int i; for(i=0; i<u.az.r.nField; i++) assert( memIsValid(&u.az.r.aMem[i]) ); }
65907 #endif
65908 ExpandBlob(u.az.r.aMem);
65909 rc = sqlite3BtreeMovetoUnpacked(u.az.pC->pCursor, &u.az.r, 0, 0, &u.az.res);
65910 if( rc!=SQLITE_OK ){
65911 goto abort_due_to_error;
65913 u.az.pC->rowidIsValid = 0;
65915 u.az.pC->deferredMoveto = 0;
65916 u.az.pC->cacheStatus = CACHE_STALE;
65917 #ifdef SQLITE_TEST
65918 sqlite3_search_count++;
65919 #endif
65920 if( u.az.oc>=OP_SeekGe ){ assert( u.az.oc==OP_SeekGe || u.az.oc==OP_SeekGt );
65921 if( u.az.res<0 || (u.az.res==0 && u.az.oc==OP_SeekGt) ){
65922 rc = sqlite3BtreeNext(u.az.pC->pCursor, &u.az.res);
65923 if( rc!=SQLITE_OK ) goto abort_due_to_error;
65924 u.az.pC->rowidIsValid = 0;
65925 }else{
65926 u.az.res = 0;
65928 }else{
65929 assert( u.az.oc==OP_SeekLt || u.az.oc==OP_SeekLe );
65930 if( u.az.res>0 || (u.az.res==0 && u.az.oc==OP_SeekLt) ){
65931 rc = sqlite3BtreePrevious(u.az.pC->pCursor, &u.az.res);
65932 if( rc!=SQLITE_OK ) goto abort_due_to_error;
65933 u.az.pC->rowidIsValid = 0;
65934 }else{
65935 /* u.az.res might be negative because the table is empty. Check to
65936 ** see if this is the case.
65938 u.az.res = sqlite3BtreeEof(u.az.pC->pCursor);
65941 assert( pOp->p2>0 );
65942 if( u.az.res ){
65943 pc = pOp->p2 - 1;
65945 }else{
65946 /* This happens when attempting to open the sqlite3_master table
65947 ** for read access returns SQLITE_EMPTY. In this case always
65948 ** take the jump (since there are no records in the table).
65950 pc = pOp->p2 - 1;
65952 break;
65955 /* Opcode: Seek P1 P2 * * *
65957 ** P1 is an open table cursor and P2 is a rowid integer. Arrange
65958 ** for P1 to move so that it points to the rowid given by P2.
65960 ** This is actually a deferred seek. Nothing actually happens until
65961 ** the cursor is used to read a record. That way, if no reads
65962 ** occur, no unnecessary I/O happens.
65964 case OP_Seek: { /* in2 */
65965 #if 0 /* local variables moved into u.ba */
65966 VdbeCursor *pC;
65967 #endif /* local variables moved into u.ba */
65969 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
65970 u.ba.pC = p->apCsr[pOp->p1];
65971 assert( u.ba.pC!=0 );
65972 if( ALWAYS(u.ba.pC->pCursor!=0) ){
65973 assert( u.ba.pC->isTable );
65974 u.ba.pC->nullRow = 0;
65975 pIn2 = &aMem[pOp->p2];
65976 u.ba.pC->movetoTarget = sqlite3VdbeIntValue(pIn2);
65977 u.ba.pC->rowidIsValid = 0;
65978 u.ba.pC->deferredMoveto = 1;
65980 break;
65984 /* Opcode: Found P1 P2 P3 P4 *
65986 ** If P4==0 then register P3 holds a blob constructed by MakeRecord. If
65987 ** P4>0 then register P3 is the first of P4 registers that form an unpacked
65988 ** record.
65990 ** Cursor P1 is on an index btree. If the record identified by P3 and P4
65991 ** is a prefix of any entry in P1 then a jump is made to P2 and
65992 ** P1 is left pointing at the matching entry.
65994 /* Opcode: NotFound P1 P2 P3 P4 *
65996 ** If P4==0 then register P3 holds a blob constructed by MakeRecord. If
65997 ** P4>0 then register P3 is the first of P4 registers that form an unpacked
65998 ** record.
66000 ** Cursor P1 is on an index btree. If the record identified by P3 and P4
66001 ** is not the prefix of any entry in P1 then a jump is made to P2. If P1
66002 ** does contain an entry whose prefix matches the P3/P4 record then control
66003 ** falls through to the next instruction and P1 is left pointing at the
66004 ** matching entry.
66006 ** See also: Found, NotExists, IsUnique
66008 case OP_NotFound: /* jump, in3 */
66009 case OP_Found: { /* jump, in3 */
66010 #if 0 /* local variables moved into u.bb */
66011 int alreadyExists;
66012 VdbeCursor *pC;
66013 int res;
66014 UnpackedRecord *pIdxKey;
66015 UnpackedRecord r;
66016 char aTempRec[ROUND8(sizeof(UnpackedRecord)) + sizeof(Mem)*3 + 7];
66017 #endif /* local variables moved into u.bb */
66019 #ifdef SQLITE_TEST
66020 sqlite3_found_count++;
66021 #endif
66023 u.bb.alreadyExists = 0;
66024 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
66025 assert( pOp->p4type==P4_INT32 );
66026 u.bb.pC = p->apCsr[pOp->p1];
66027 assert( u.bb.pC!=0 );
66028 pIn3 = &aMem[pOp->p3];
66029 if( ALWAYS(u.bb.pC->pCursor!=0) ){
66031 assert( u.bb.pC->isTable==0 );
66032 if( pOp->p4.i>0 ){
66033 u.bb.r.pKeyInfo = u.bb.pC->pKeyInfo;
66034 u.bb.r.nField = (u16)pOp->p4.i;
66035 u.bb.r.aMem = pIn3;
66036 #ifdef SQLITE_DEBUG
66037 { int i; for(i=0; i<u.bb.r.nField; i++) assert( memIsValid(&u.bb.r.aMem[i]) ); }
66038 #endif
66039 u.bb.r.flags = UNPACKED_PREFIX_MATCH;
66040 u.bb.pIdxKey = &u.bb.r;
66041 }else{
66042 assert( pIn3->flags & MEM_Blob );
66043 assert( (pIn3->flags & MEM_Zero)==0 ); /* zeroblobs already expanded */
66044 u.bb.pIdxKey = sqlite3VdbeRecordUnpack(u.bb.pC->pKeyInfo, pIn3->n, pIn3->z,
66045 u.bb.aTempRec, sizeof(u.bb.aTempRec));
66046 if( u.bb.pIdxKey==0 ){
66047 goto no_mem;
66049 u.bb.pIdxKey->flags |= UNPACKED_PREFIX_MATCH;
66051 rc = sqlite3BtreeMovetoUnpacked(u.bb.pC->pCursor, u.bb.pIdxKey, 0, 0, &u.bb.res);
66052 if( pOp->p4.i==0 ){
66053 sqlite3VdbeDeleteUnpackedRecord(u.bb.pIdxKey);
66055 if( rc!=SQLITE_OK ){
66056 break;
66058 u.bb.alreadyExists = (u.bb.res==0);
66059 u.bb.pC->deferredMoveto = 0;
66060 u.bb.pC->cacheStatus = CACHE_STALE;
66062 if( pOp->opcode==OP_Found ){
66063 if( u.bb.alreadyExists ) pc = pOp->p2 - 1;
66064 }else{
66065 if( !u.bb.alreadyExists ) pc = pOp->p2 - 1;
66067 break;
66070 /* Opcode: IsUnique P1 P2 P3 P4 *
66072 ** Cursor P1 is open on an index b-tree - that is to say, a btree which
66073 ** no data and where the key are records generated by OP_MakeRecord with
66074 ** the list field being the integer ROWID of the entry that the index
66075 ** entry refers to.
66077 ** The P3 register contains an integer record number. Call this record
66078 ** number R. Register P4 is the first in a set of N contiguous registers
66079 ** that make up an unpacked index key that can be used with cursor P1.
66080 ** The value of N can be inferred from the cursor. N includes the rowid
66081 ** value appended to the end of the index record. This rowid value may
66082 ** or may not be the same as R.
66084 ** If any of the N registers beginning with register P4 contains a NULL
66085 ** value, jump immediately to P2.
66087 ** Otherwise, this instruction checks if cursor P1 contains an entry
66088 ** where the first (N-1) fields match but the rowid value at the end
66089 ** of the index entry is not R. If there is no such entry, control jumps
66090 ** to instruction P2. Otherwise, the rowid of the conflicting index
66091 ** entry is copied to register P3 and control falls through to the next
66092 ** instruction.
66094 ** See also: NotFound, NotExists, Found
66096 case OP_IsUnique: { /* jump, in3 */
66097 #if 0 /* local variables moved into u.bc */
66098 u16 ii;
66099 VdbeCursor *pCx;
66100 BtCursor *pCrsr;
66101 u16 nField;
66102 Mem *aMx;
66103 UnpackedRecord r; /* B-Tree index search key */
66104 i64 R; /* Rowid stored in register P3 */
66105 #endif /* local variables moved into u.bc */
66107 pIn3 = &aMem[pOp->p3];
66108 u.bc.aMx = &aMem[pOp->p4.i];
66109 /* Assert that the values of parameters P1 and P4 are in range. */
66110 assert( pOp->p4type==P4_INT32 );
66111 assert( pOp->p4.i>0 && pOp->p4.i<=p->nMem );
66112 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
66114 /* Find the index cursor. */
66115 u.bc.pCx = p->apCsr[pOp->p1];
66116 assert( u.bc.pCx->deferredMoveto==0 );
66117 u.bc.pCx->seekResult = 0;
66118 u.bc.pCx->cacheStatus = CACHE_STALE;
66119 u.bc.pCrsr = u.bc.pCx->pCursor;
66121 /* If any of the values are NULL, take the jump. */
66122 u.bc.nField = u.bc.pCx->pKeyInfo->nField;
66123 for(u.bc.ii=0; u.bc.ii<u.bc.nField; u.bc.ii++){
66124 if( u.bc.aMx[u.bc.ii].flags & MEM_Null ){
66125 pc = pOp->p2 - 1;
66126 u.bc.pCrsr = 0;
66127 break;
66130 assert( (u.bc.aMx[u.bc.nField].flags & MEM_Null)==0 );
66132 if( u.bc.pCrsr!=0 ){
66133 /* Populate the index search key. */
66134 u.bc.r.pKeyInfo = u.bc.pCx->pKeyInfo;
66135 u.bc.r.nField = u.bc.nField + 1;
66136 u.bc.r.flags = UNPACKED_PREFIX_SEARCH;
66137 u.bc.r.aMem = u.bc.aMx;
66138 #ifdef SQLITE_DEBUG
66139 { int i; for(i=0; i<u.bc.r.nField; i++) assert( memIsValid(&u.bc.r.aMem[i]) ); }
66140 #endif
66142 /* Extract the value of u.bc.R from register P3. */
66143 sqlite3VdbeMemIntegerify(pIn3);
66144 u.bc.R = pIn3->u.i;
66146 /* Search the B-Tree index. If no conflicting record is found, jump
66147 ** to P2. Otherwise, copy the rowid of the conflicting record to
66148 ** register P3 and fall through to the next instruction. */
66149 rc = sqlite3BtreeMovetoUnpacked(u.bc.pCrsr, &u.bc.r, 0, 0, &u.bc.pCx->seekResult);
66150 if( (u.bc.r.flags & UNPACKED_PREFIX_SEARCH) || u.bc.r.rowid==u.bc.R ){
66151 pc = pOp->p2 - 1;
66152 }else{
66153 pIn3->u.i = u.bc.r.rowid;
66156 break;
66159 /* Opcode: NotExists P1 P2 P3 * *
66161 ** Use the content of register P3 as a integer key. If a record
66162 ** with that key does not exist in table of P1, then jump to P2.
66163 ** If the record does exist, then fall through. The cursor is left
66164 ** pointing to the record if it exists.
66166 ** The difference between this operation and NotFound is that this
66167 ** operation assumes the key is an integer and that P1 is a table whereas
66168 ** NotFound assumes key is a blob constructed from MakeRecord and
66169 ** P1 is an index.
66171 ** See also: Found, NotFound, IsUnique
66173 case OP_NotExists: { /* jump, in3 */
66174 #if 0 /* local variables moved into u.bd */
66175 VdbeCursor *pC;
66176 BtCursor *pCrsr;
66177 int res;
66178 u64 iKey;
66179 #endif /* local variables moved into u.bd */
66181 pIn3 = &aMem[pOp->p3];
66182 assert( pIn3->flags & MEM_Int );
66183 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
66184 u.bd.pC = p->apCsr[pOp->p1];
66185 assert( u.bd.pC!=0 );
66186 assert( u.bd.pC->isTable );
66187 assert( u.bd.pC->pseudoTableReg==0 );
66188 u.bd.pCrsr = u.bd.pC->pCursor;
66189 if( u.bd.pCrsr!=0 ){
66190 u.bd.res = 0;
66191 u.bd.iKey = pIn3->u.i;
66192 rc = sqlite3BtreeMovetoUnpacked(u.bd.pCrsr, 0, u.bd.iKey, 0, &u.bd.res);
66193 u.bd.pC->lastRowid = pIn3->u.i;
66194 u.bd.pC->rowidIsValid = u.bd.res==0 ?1:0;
66195 u.bd.pC->nullRow = 0;
66196 u.bd.pC->cacheStatus = CACHE_STALE;
66197 u.bd.pC->deferredMoveto = 0;
66198 if( u.bd.res!=0 ){
66199 pc = pOp->p2 - 1;
66200 assert( u.bd.pC->rowidIsValid==0 );
66202 u.bd.pC->seekResult = u.bd.res;
66203 }else{
66204 /* This happens when an attempt to open a read cursor on the
66205 ** sqlite_master table returns SQLITE_EMPTY.
66207 pc = pOp->p2 - 1;
66208 assert( u.bd.pC->rowidIsValid==0 );
66209 u.bd.pC->seekResult = 0;
66211 break;
66214 /* Opcode: Sequence P1 P2 * * *
66216 ** Find the next available sequence number for cursor P1.
66217 ** Write the sequence number into register P2.
66218 ** The sequence number on the cursor is incremented after this
66219 ** instruction.
66221 case OP_Sequence: { /* out2-prerelease */
66222 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
66223 assert( p->apCsr[pOp->p1]!=0 );
66224 pOut->u.i = p->apCsr[pOp->p1]->seqCount++;
66225 break;
66229 /* Opcode: NewRowid P1 P2 P3 * *
66231 ** Get a new integer record number (a.k.a "rowid") used as the key to a table.
66232 ** The record number is not previously used as a key in the database
66233 ** table that cursor P1 points to. The new record number is written
66234 ** written to register P2.
66236 ** If P3>0 then P3 is a register in the root frame of this VDBE that holds
66237 ** the largest previously generated record number. No new record numbers are
66238 ** allowed to be less than this value. When this value reaches its maximum,
66239 ** a SQLITE_FULL error is generated. The P3 register is updated with the '
66240 ** generated record number. This P3 mechanism is used to help implement the
66241 ** AUTOINCREMENT feature.
66243 case OP_NewRowid: { /* out2-prerelease */
66244 #if 0 /* local variables moved into u.be */
66245 i64 v; /* The new rowid */
66246 VdbeCursor *pC; /* Cursor of table to get the new rowid */
66247 int res; /* Result of an sqlite3BtreeLast() */
66248 int cnt; /* Counter to limit the number of searches */
66249 Mem *pMem; /* Register holding largest rowid for AUTOINCREMENT */
66250 VdbeFrame *pFrame; /* Root frame of VDBE */
66251 #endif /* local variables moved into u.be */
66253 u.be.v = 0;
66254 u.be.res = 0;
66255 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
66256 u.be.pC = p->apCsr[pOp->p1];
66257 assert( u.be.pC!=0 );
66258 if( NEVER(u.be.pC->pCursor==0) ){
66259 /* The zero initialization above is all that is needed */
66260 }else{
66261 /* The next rowid or record number (different terms for the same
66262 ** thing) is obtained in a two-step algorithm.
66264 ** First we attempt to find the largest existing rowid and add one
66265 ** to that. But if the largest existing rowid is already the maximum
66266 ** positive integer, we have to fall through to the second
66267 ** probabilistic algorithm
66269 ** The second algorithm is to select a rowid at random and see if
66270 ** it already exists in the table. If it does not exist, we have
66271 ** succeeded. If the random rowid does exist, we select a new one
66272 ** and try again, up to 100 times.
66274 assert( u.be.pC->isTable );
66276 #ifdef SQLITE_32BIT_ROWID
66277 # define MAX_ROWID 0x7fffffff
66278 #else
66279 /* Some compilers complain about constants of the form 0x7fffffffffffffff.
66280 ** Others complain about 0x7ffffffffffffffffLL. The following macro seems
66281 ** to provide the constant while making all compilers happy.
66283 # define MAX_ROWID (i64)( (((u64)0x7fffffff)<<32) | (u64)0xffffffff )
66284 #endif
66286 if( !u.be.pC->useRandomRowid ){
66287 u.be.v = sqlite3BtreeGetCachedRowid(u.be.pC->pCursor);
66288 if( u.be.v==0 ){
66289 rc = sqlite3BtreeLast(u.be.pC->pCursor, &u.be.res);
66290 if( rc!=SQLITE_OK ){
66291 goto abort_due_to_error;
66293 if( u.be.res ){
66294 u.be.v = 1; /* IMP: R-61914-48074 */
66295 }else{
66296 assert( sqlite3BtreeCursorIsValid(u.be.pC->pCursor) );
66297 rc = sqlite3BtreeKeySize(u.be.pC->pCursor, &u.be.v);
66298 assert( rc==SQLITE_OK ); /* Cannot fail following BtreeLast() */
66299 if( u.be.v==MAX_ROWID ){
66300 u.be.pC->useRandomRowid = 1;
66301 }else{
66302 u.be.v++; /* IMP: R-29538-34987 */
66307 #ifndef SQLITE_OMIT_AUTOINCREMENT
66308 if( pOp->p3 ){
66309 /* Assert that P3 is a valid memory cell. */
66310 assert( pOp->p3>0 );
66311 if( p->pFrame ){
66312 for(u.be.pFrame=p->pFrame; u.be.pFrame->pParent; u.be.pFrame=u.be.pFrame->pParent);
66313 /* Assert that P3 is a valid memory cell. */
66314 assert( pOp->p3<=u.be.pFrame->nMem );
66315 u.be.pMem = &u.be.pFrame->aMem[pOp->p3];
66316 }else{
66317 /* Assert that P3 is a valid memory cell. */
66318 assert( pOp->p3<=p->nMem );
66319 u.be.pMem = &aMem[pOp->p3];
66320 memAboutToChange(p, u.be.pMem);
66322 assert( memIsValid(u.be.pMem) );
66324 REGISTER_TRACE(pOp->p3, u.be.pMem);
66325 sqlite3VdbeMemIntegerify(u.be.pMem);
66326 assert( (u.be.pMem->flags & MEM_Int)!=0 ); /* mem(P3) holds an integer */
66327 if( u.be.pMem->u.i==MAX_ROWID || u.be.pC->useRandomRowid ){
66328 rc = SQLITE_FULL; /* IMP: R-12275-61338 */
66329 goto abort_due_to_error;
66331 if( u.be.v<u.be.pMem->u.i+1 ){
66332 u.be.v = u.be.pMem->u.i + 1;
66334 u.be.pMem->u.i = u.be.v;
66336 #endif
66338 sqlite3BtreeSetCachedRowid(u.be.pC->pCursor, u.be.v<MAX_ROWID ? u.be.v+1 : 0);
66340 if( u.be.pC->useRandomRowid ){
66341 /* IMPLEMENTATION-OF: R-07677-41881 If the largest ROWID is equal to the
66342 ** largest possible integer (9223372036854775807) then the database
66343 ** engine starts picking positive candidate ROWIDs at random until
66344 ** it finds one that is not previously used. */
66345 assert( pOp->p3==0 ); /* We cannot be in random rowid mode if this is
66346 ** an AUTOINCREMENT table. */
66347 /* on the first attempt, simply do one more than previous */
66348 u.be.v = db->lastRowid;
66349 u.be.v &= (MAX_ROWID>>1); /* ensure doesn't go negative */
66350 u.be.v++; /* ensure non-zero */
66351 u.be.cnt = 0;
66352 while( ((rc = sqlite3BtreeMovetoUnpacked(u.be.pC->pCursor, 0, (u64)u.be.v,
66353 0, &u.be.res))==SQLITE_OK)
66354 && (u.be.res==0)
66355 && (++u.be.cnt<100)){
66356 /* collision - try another random rowid */
66357 sqlite3_randomness(sizeof(u.be.v), &u.be.v);
66358 if( u.be.cnt<5 ){
66359 /* try "small" random rowids for the initial attempts */
66360 u.be.v &= 0xffffff;
66361 }else{
66362 u.be.v &= (MAX_ROWID>>1); /* ensure doesn't go negative */
66364 u.be.v++; /* ensure non-zero */
66366 if( rc==SQLITE_OK && u.be.res==0 ){
66367 rc = SQLITE_FULL; /* IMP: R-38219-53002 */
66368 goto abort_due_to_error;
66370 assert( u.be.v>0 ); /* EV: R-40812-03570 */
66372 u.be.pC->rowidIsValid = 0;
66373 u.be.pC->deferredMoveto = 0;
66374 u.be.pC->cacheStatus = CACHE_STALE;
66376 pOut->u.i = u.be.v;
66377 break;
66380 /* Opcode: Insert P1 P2 P3 P4 P5
66382 ** Write an entry into the table of cursor P1. A new entry is
66383 ** created if it doesn't already exist or the data for an existing
66384 ** entry is overwritten. The data is the value MEM_Blob stored in register
66385 ** number P2. The key is stored in register P3. The key must
66386 ** be a MEM_Int.
66388 ** If the OPFLAG_NCHANGE flag of P5 is set, then the row change count is
66389 ** incremented (otherwise not). If the OPFLAG_LASTROWID flag of P5 is set,
66390 ** then rowid is stored for subsequent return by the
66391 ** sqlite3_last_insert_rowid() function (otherwise it is unmodified).
66393 ** If the OPFLAG_USESEEKRESULT flag of P5 is set and if the result of
66394 ** the last seek operation (OP_NotExists) was a success, then this
66395 ** operation will not attempt to find the appropriate row before doing
66396 ** the insert but will instead overwrite the row that the cursor is
66397 ** currently pointing to. Presumably, the prior OP_NotExists opcode
66398 ** has already positioned the cursor correctly. This is an optimization
66399 ** that boosts performance by avoiding redundant seeks.
66401 ** If the OPFLAG_ISUPDATE flag is set, then this opcode is part of an
66402 ** UPDATE operation. Otherwise (if the flag is clear) then this opcode
66403 ** is part of an INSERT operation. The difference is only important to
66404 ** the update hook.
66406 ** Parameter P4 may point to a string containing the table-name, or
66407 ** may be NULL. If it is not NULL, then the update-hook
66408 ** (sqlite3.xUpdateCallback) is invoked following a successful insert.
66410 ** (WARNING/TODO: If P1 is a pseudo-cursor and P2 is dynamically
66411 ** allocated, then ownership of P2 is transferred to the pseudo-cursor
66412 ** and register P2 becomes ephemeral. If the cursor is changed, the
66413 ** value of register P2 will then change. Make sure this does not
66414 ** cause any problems.)
66416 ** This instruction only works on tables. The equivalent instruction
66417 ** for indices is OP_IdxInsert.
66419 /* Opcode: InsertInt P1 P2 P3 P4 P5
66421 ** This works exactly like OP_Insert except that the key is the
66422 ** integer value P3, not the value of the integer stored in register P3.
66424 case OP_Insert:
66425 case OP_InsertInt: {
66426 #if 0 /* local variables moved into u.bf */
66427 Mem *pData; /* MEM cell holding data for the record to be inserted */
66428 Mem *pKey; /* MEM cell holding key for the record */
66429 i64 iKey; /* The integer ROWID or key for the record to be inserted */
66430 VdbeCursor *pC; /* Cursor to table into which insert is written */
66431 int nZero; /* Number of zero-bytes to append */
66432 int seekResult; /* Result of prior seek or 0 if no USESEEKRESULT flag */
66433 const char *zDb; /* database name - used by the update hook */
66434 const char *zTbl; /* Table name - used by the opdate hook */
66435 int op; /* Opcode for update hook: SQLITE_UPDATE or SQLITE_INSERT */
66436 #endif /* local variables moved into u.bf */
66438 u.bf.pData = &aMem[pOp->p2];
66439 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
66440 assert( memIsValid(u.bf.pData) );
66441 u.bf.pC = p->apCsr[pOp->p1];
66442 assert( u.bf.pC!=0 );
66443 assert( u.bf.pC->pCursor!=0 );
66444 assert( u.bf.pC->pseudoTableReg==0 );
66445 assert( u.bf.pC->isTable );
66446 REGISTER_TRACE(pOp->p2, u.bf.pData);
66448 if( pOp->opcode==OP_Insert ){
66449 u.bf.pKey = &aMem[pOp->p3];
66450 assert( u.bf.pKey->flags & MEM_Int );
66451 assert( memIsValid(u.bf.pKey) );
66452 REGISTER_TRACE(pOp->p3, u.bf.pKey);
66453 u.bf.iKey = u.bf.pKey->u.i;
66454 }else{
66455 assert( pOp->opcode==OP_InsertInt );
66456 u.bf.iKey = pOp->p3;
66459 if( pOp->p5 & OPFLAG_NCHANGE ) p->nChange++;
66460 if( pOp->p5 & OPFLAG_LASTROWID ) db->lastRowid = u.bf.iKey;
66461 if( u.bf.pData->flags & MEM_Null ){
66462 u.bf.pData->z = 0;
66463 u.bf.pData->n = 0;
66464 }else{
66465 assert( u.bf.pData->flags & (MEM_Blob|MEM_Str) );
66467 u.bf.seekResult = ((pOp->p5 & OPFLAG_USESEEKRESULT) ? u.bf.pC->seekResult : 0);
66468 if( u.bf.pData->flags & MEM_Zero ){
66469 u.bf.nZero = u.bf.pData->u.nZero;
66470 }else{
66471 u.bf.nZero = 0;
66473 sqlite3BtreeSetCachedRowid(u.bf.pC->pCursor, 0);
66474 rc = sqlite3BtreeInsert(u.bf.pC->pCursor, 0, u.bf.iKey,
66475 u.bf.pData->z, u.bf.pData->n, u.bf.nZero,
66476 pOp->p5 & OPFLAG_APPEND, u.bf.seekResult
66478 u.bf.pC->rowidIsValid = 0;
66479 u.bf.pC->deferredMoveto = 0;
66480 u.bf.pC->cacheStatus = CACHE_STALE;
66482 /* Invoke the update-hook if required. */
66483 if( rc==SQLITE_OK && db->xUpdateCallback && pOp->p4.z ){
66484 u.bf.zDb = db->aDb[u.bf.pC->iDb].zName;
66485 u.bf.zTbl = pOp->p4.z;
66486 u.bf.op = ((pOp->p5 & OPFLAG_ISUPDATE) ? SQLITE_UPDATE : SQLITE_INSERT);
66487 assert( u.bf.pC->isTable );
66488 db->xUpdateCallback(db->pUpdateArg, u.bf.op, u.bf.zDb, u.bf.zTbl, u.bf.iKey);
66489 assert( u.bf.pC->iDb>=0 );
66491 break;
66494 /* Opcode: Delete P1 P2 * P4 *
66496 ** Delete the record at which the P1 cursor is currently pointing.
66498 ** The cursor will be left pointing at either the next or the previous
66499 ** record in the table. If it is left pointing at the next record, then
66500 ** the next Next instruction will be a no-op. Hence it is OK to delete
66501 ** a record from within an Next loop.
66503 ** If the OPFLAG_NCHANGE flag of P2 is set, then the row change count is
66504 ** incremented (otherwise not).
66506 ** P1 must not be pseudo-table. It has to be a real table with
66507 ** multiple rows.
66509 ** If P4 is not NULL, then it is the name of the table that P1 is
66510 ** pointing to. The update hook will be invoked, if it exists.
66511 ** If P4 is not NULL then the P1 cursor must have been positioned
66512 ** using OP_NotFound prior to invoking this opcode.
66514 case OP_Delete: {
66515 #if 0 /* local variables moved into u.bg */
66516 i64 iKey;
66517 VdbeCursor *pC;
66518 #endif /* local variables moved into u.bg */
66520 u.bg.iKey = 0;
66521 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
66522 u.bg.pC = p->apCsr[pOp->p1];
66523 assert( u.bg.pC!=0 );
66524 assert( u.bg.pC->pCursor!=0 ); /* Only valid for real tables, no pseudotables */
66526 /* If the update-hook will be invoked, set u.bg.iKey to the rowid of the
66527 ** row being deleted.
66529 if( db->xUpdateCallback && pOp->p4.z ){
66530 assert( u.bg.pC->isTable );
66531 assert( u.bg.pC->rowidIsValid ); /* lastRowid set by previous OP_NotFound */
66532 u.bg.iKey = u.bg.pC->lastRowid;
66535 /* The OP_Delete opcode always follows an OP_NotExists or OP_Last or
66536 ** OP_Column on the same table without any intervening operations that
66537 ** might move or invalidate the cursor. Hence cursor u.bg.pC is always pointing
66538 ** to the row to be deleted and the sqlite3VdbeCursorMoveto() operation
66539 ** below is always a no-op and cannot fail. We will run it anyhow, though,
66540 ** to guard against future changes to the code generator.
66542 assert( u.bg.pC->deferredMoveto==0 );
66543 rc = sqlite3VdbeCursorMoveto(u.bg.pC);
66544 if( NEVER(rc!=SQLITE_OK) ) goto abort_due_to_error;
66546 sqlite3BtreeSetCachedRowid(u.bg.pC->pCursor, 0);
66547 rc = sqlite3BtreeDelete(u.bg.pC->pCursor);
66548 u.bg.pC->cacheStatus = CACHE_STALE;
66550 /* Invoke the update-hook if required. */
66551 if( rc==SQLITE_OK && db->xUpdateCallback && pOp->p4.z ){
66552 const char *zDb = db->aDb[u.bg.pC->iDb].zName;
66553 const char *zTbl = pOp->p4.z;
66554 db->xUpdateCallback(db->pUpdateArg, SQLITE_DELETE, zDb, zTbl, u.bg.iKey);
66555 assert( u.bg.pC->iDb>=0 );
66557 if( pOp->p2 & OPFLAG_NCHANGE ) p->nChange++;
66558 break;
66560 /* Opcode: ResetCount * * * * *
66562 ** The value of the change counter is copied to the database handle
66563 ** change counter (returned by subsequent calls to sqlite3_changes()).
66564 ** Then the VMs internal change counter resets to 0.
66565 ** This is used by trigger programs.
66567 case OP_ResetCount: {
66568 sqlite3VdbeSetChanges(db, p->nChange);
66569 p->nChange = 0;
66570 break;
66573 /* Opcode: RowData P1 P2 * * *
66575 ** Write into register P2 the complete row data for cursor P1.
66576 ** There is no interpretation of the data.
66577 ** It is just copied onto the P2 register exactly as
66578 ** it is found in the database file.
66580 ** If the P1 cursor must be pointing to a valid row (not a NULL row)
66581 ** of a real table, not a pseudo-table.
66583 /* Opcode: RowKey P1 P2 * * *
66585 ** Write into register P2 the complete row key for cursor P1.
66586 ** There is no interpretation of the data.
66587 ** The key is copied onto the P3 register exactly as
66588 ** it is found in the database file.
66590 ** If the P1 cursor must be pointing to a valid row (not a NULL row)
66591 ** of a real table, not a pseudo-table.
66593 case OP_RowKey:
66594 case OP_RowData: {
66595 #if 0 /* local variables moved into u.bh */
66596 VdbeCursor *pC;
66597 BtCursor *pCrsr;
66598 u32 n;
66599 i64 n64;
66600 #endif /* local variables moved into u.bh */
66602 pOut = &aMem[pOp->p2];
66603 memAboutToChange(p, pOut);
66605 /* Note that RowKey and RowData are really exactly the same instruction */
66606 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
66607 u.bh.pC = p->apCsr[pOp->p1];
66608 assert( u.bh.pC->isTable || pOp->opcode==OP_RowKey );
66609 assert( u.bh.pC->isIndex || pOp->opcode==OP_RowData );
66610 assert( u.bh.pC!=0 );
66611 assert( u.bh.pC->nullRow==0 );
66612 assert( u.bh.pC->pseudoTableReg==0 );
66613 assert( u.bh.pC->pCursor!=0 );
66614 u.bh.pCrsr = u.bh.pC->pCursor;
66615 assert( sqlite3BtreeCursorIsValid(u.bh.pCrsr) );
66617 /* The OP_RowKey and OP_RowData opcodes always follow OP_NotExists or
66618 ** OP_Rewind/Op_Next with no intervening instructions that might invalidate
66619 ** the cursor. Hence the following sqlite3VdbeCursorMoveto() call is always
66620 ** a no-op and can never fail. But we leave it in place as a safety.
66622 assert( u.bh.pC->deferredMoveto==0 );
66623 rc = sqlite3VdbeCursorMoveto(u.bh.pC);
66624 if( NEVER(rc!=SQLITE_OK) ) goto abort_due_to_error;
66626 if( u.bh.pC->isIndex ){
66627 assert( !u.bh.pC->isTable );
66628 rc = sqlite3BtreeKeySize(u.bh.pCrsr, &u.bh.n64);
66629 assert( rc==SQLITE_OK ); /* True because of CursorMoveto() call above */
66630 if( u.bh.n64>db->aLimit[SQLITE_LIMIT_LENGTH] ){
66631 goto too_big;
66633 u.bh.n = (u32)u.bh.n64;
66634 }else{
66635 rc = sqlite3BtreeDataSize(u.bh.pCrsr, &u.bh.n);
66636 assert( rc==SQLITE_OK ); /* DataSize() cannot fail */
66637 if( u.bh.n>(u32)db->aLimit[SQLITE_LIMIT_LENGTH] ){
66638 goto too_big;
66641 if( sqlite3VdbeMemGrow(pOut, u.bh.n, 0) ){
66642 goto no_mem;
66644 pOut->n = u.bh.n;
66645 MemSetTypeFlag(pOut, MEM_Blob);
66646 if( u.bh.pC->isIndex ){
66647 rc = sqlite3BtreeKey(u.bh.pCrsr, 0, u.bh.n, pOut->z);
66648 }else{
66649 rc = sqlite3BtreeData(u.bh.pCrsr, 0, u.bh.n, pOut->z);
66651 pOut->enc = SQLITE_UTF8; /* In case the blob is ever cast to text */
66652 UPDATE_MAX_BLOBSIZE(pOut);
66653 break;
66656 /* Opcode: Rowid P1 P2 * * *
66658 ** Store in register P2 an integer which is the key of the table entry that
66659 ** P1 is currently point to.
66661 ** P1 can be either an ordinary table or a virtual table. There used to
66662 ** be a separate OP_VRowid opcode for use with virtual tables, but this
66663 ** one opcode now works for both table types.
66665 case OP_Rowid: { /* out2-prerelease */
66666 #if 0 /* local variables moved into u.bi */
66667 VdbeCursor *pC;
66668 i64 v;
66669 sqlite3_vtab *pVtab;
66670 const sqlite3_module *pModule;
66671 #endif /* local variables moved into u.bi */
66673 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
66674 u.bi.pC = p->apCsr[pOp->p1];
66675 assert( u.bi.pC!=0 );
66676 assert( u.bi.pC->pseudoTableReg==0 );
66677 if( u.bi.pC->nullRow ){
66678 pOut->flags = MEM_Null;
66679 break;
66680 }else if( u.bi.pC->deferredMoveto ){
66681 u.bi.v = u.bi.pC->movetoTarget;
66682 #ifndef SQLITE_OMIT_VIRTUALTABLE
66683 }else if( u.bi.pC->pVtabCursor ){
66684 u.bi.pVtab = u.bi.pC->pVtabCursor->pVtab;
66685 u.bi.pModule = u.bi.pVtab->pModule;
66686 assert( u.bi.pModule->xRowid );
66687 rc = u.bi.pModule->xRowid(u.bi.pC->pVtabCursor, &u.bi.v);
66688 importVtabErrMsg(p, u.bi.pVtab);
66689 #endif /* SQLITE_OMIT_VIRTUALTABLE */
66690 }else{
66691 assert( u.bi.pC->pCursor!=0 );
66692 rc = sqlite3VdbeCursorMoveto(u.bi.pC);
66693 if( rc ) goto abort_due_to_error;
66694 if( u.bi.pC->rowidIsValid ){
66695 u.bi.v = u.bi.pC->lastRowid;
66696 }else{
66697 rc = sqlite3BtreeKeySize(u.bi.pC->pCursor, &u.bi.v);
66698 assert( rc==SQLITE_OK ); /* Always so because of CursorMoveto() above */
66701 pOut->u.i = u.bi.v;
66702 break;
66705 /* Opcode: NullRow P1 * * * *
66707 ** Move the cursor P1 to a null row. Any OP_Column operations
66708 ** that occur while the cursor is on the null row will always
66709 ** write a NULL.
66711 case OP_NullRow: {
66712 #if 0 /* local variables moved into u.bj */
66713 VdbeCursor *pC;
66714 #endif /* local variables moved into u.bj */
66716 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
66717 u.bj.pC = p->apCsr[pOp->p1];
66718 assert( u.bj.pC!=0 );
66719 u.bj.pC->nullRow = 1;
66720 u.bj.pC->rowidIsValid = 0;
66721 if( u.bj.pC->pCursor ){
66722 sqlite3BtreeClearCursor(u.bj.pC->pCursor);
66724 break;
66727 /* Opcode: Last P1 P2 * * *
66729 ** The next use of the Rowid or Column or Next instruction for P1
66730 ** will refer to the last entry in the database table or index.
66731 ** If the table or index is empty and P2>0, then jump immediately to P2.
66732 ** If P2 is 0 or if the table or index is not empty, fall through
66733 ** to the following instruction.
66735 case OP_Last: { /* jump */
66736 #if 0 /* local variables moved into u.bk */
66737 VdbeCursor *pC;
66738 BtCursor *pCrsr;
66739 int res;
66740 #endif /* local variables moved into u.bk */
66742 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
66743 u.bk.pC = p->apCsr[pOp->p1];
66744 assert( u.bk.pC!=0 );
66745 u.bk.pCrsr = u.bk.pC->pCursor;
66746 if( u.bk.pCrsr==0 ){
66747 u.bk.res = 1;
66748 }else{
66749 rc = sqlite3BtreeLast(u.bk.pCrsr, &u.bk.res);
66751 u.bk.pC->nullRow = (u8)u.bk.res;
66752 u.bk.pC->deferredMoveto = 0;
66753 u.bk.pC->rowidIsValid = 0;
66754 u.bk.pC->cacheStatus = CACHE_STALE;
66755 if( pOp->p2>0 && u.bk.res ){
66756 pc = pOp->p2 - 1;
66758 break;
66762 /* Opcode: Sort P1 P2 * * *
66764 ** This opcode does exactly the same thing as OP_Rewind except that
66765 ** it increments an undocumented global variable used for testing.
66767 ** Sorting is accomplished by writing records into a sorting index,
66768 ** then rewinding that index and playing it back from beginning to
66769 ** end. We use the OP_Sort opcode instead of OP_Rewind to do the
66770 ** rewinding so that the global variable will be incremented and
66771 ** regression tests can determine whether or not the optimizer is
66772 ** correctly optimizing out sorts.
66774 case OP_Sort: { /* jump */
66775 #ifdef SQLITE_TEST
66776 sqlite3_sort_count++;
66777 sqlite3_search_count--;
66778 #endif
66779 p->aCounter[SQLITE_STMTSTATUS_SORT-1]++;
66780 /* Fall through into OP_Rewind */
66782 /* Opcode: Rewind P1 P2 * * *
66784 ** The next use of the Rowid or Column or Next instruction for P1
66785 ** will refer to the first entry in the database table or index.
66786 ** If the table or index is empty and P2>0, then jump immediately to P2.
66787 ** If P2 is 0 or if the table or index is not empty, fall through
66788 ** to the following instruction.
66790 case OP_Rewind: { /* jump */
66791 #if 0 /* local variables moved into u.bl */
66792 VdbeCursor *pC;
66793 BtCursor *pCrsr;
66794 int res;
66795 #endif /* local variables moved into u.bl */
66797 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
66798 u.bl.pC = p->apCsr[pOp->p1];
66799 assert( u.bl.pC!=0 );
66800 u.bl.res = 1;
66801 if( (u.bl.pCrsr = u.bl.pC->pCursor)!=0 ){
66802 rc = sqlite3BtreeFirst(u.bl.pCrsr, &u.bl.res);
66803 u.bl.pC->atFirst = u.bl.res==0 ?1:0;
66804 u.bl.pC->deferredMoveto = 0;
66805 u.bl.pC->cacheStatus = CACHE_STALE;
66806 u.bl.pC->rowidIsValid = 0;
66808 u.bl.pC->nullRow = (u8)u.bl.res;
66809 assert( pOp->p2>0 && pOp->p2<p->nOp );
66810 if( u.bl.res ){
66811 pc = pOp->p2 - 1;
66813 break;
66816 /* Opcode: Next P1 P2 * * P5
66818 ** Advance cursor P1 so that it points to the next key/data pair in its
66819 ** table or index. If there are no more key/value pairs then fall through
66820 ** to the following instruction. But if the cursor advance was successful,
66821 ** jump immediately to P2.
66823 ** The P1 cursor must be for a real table, not a pseudo-table.
66825 ** If P5 is positive and the jump is taken, then event counter
66826 ** number P5-1 in the prepared statement is incremented.
66828 ** See also: Prev
66830 /* Opcode: Prev P1 P2 * * P5
66832 ** Back up cursor P1 so that it points to the previous key/data pair in its
66833 ** table or index. If there is no previous key/value pairs then fall through
66834 ** to the following instruction. But if the cursor backup was successful,
66835 ** jump immediately to P2.
66837 ** The P1 cursor must be for a real table, not a pseudo-table.
66839 ** If P5 is positive and the jump is taken, then event counter
66840 ** number P5-1 in the prepared statement is incremented.
66842 case OP_Prev: /* jump */
66843 case OP_Next: { /* jump */
66844 #if 0 /* local variables moved into u.bm */
66845 VdbeCursor *pC;
66846 BtCursor *pCrsr;
66847 int res;
66848 #endif /* local variables moved into u.bm */
66850 CHECK_FOR_INTERRUPT;
66851 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
66852 assert( pOp->p5<=ArraySize(p->aCounter) );
66853 u.bm.pC = p->apCsr[pOp->p1];
66854 if( u.bm.pC==0 ){
66855 break; /* See ticket #2273 */
66857 u.bm.pCrsr = u.bm.pC->pCursor;
66858 if( u.bm.pCrsr==0 ){
66859 u.bm.pC->nullRow = 1;
66860 break;
66862 u.bm.res = 1;
66863 assert( u.bm.pC->deferredMoveto==0 );
66864 rc = pOp->opcode==OP_Next ? sqlite3BtreeNext(u.bm.pCrsr, &u.bm.res) :
66865 sqlite3BtreePrevious(u.bm.pCrsr, &u.bm.res);
66866 u.bm.pC->nullRow = (u8)u.bm.res;
66867 u.bm.pC->cacheStatus = CACHE_STALE;
66868 if( u.bm.res==0 ){
66869 pc = pOp->p2 - 1;
66870 if( pOp->p5 ) p->aCounter[pOp->p5-1]++;
66871 #ifdef SQLITE_TEST
66872 sqlite3_search_count++;
66873 #endif
66875 u.bm.pC->rowidIsValid = 0;
66876 break;
66879 /* Opcode: IdxInsert P1 P2 P3 * P5
66881 ** Register P2 holds a SQL index key made using the
66882 ** MakeRecord instructions. This opcode writes that key
66883 ** into the index P1. Data for the entry is nil.
66885 ** P3 is a flag that provides a hint to the b-tree layer that this
66886 ** insert is likely to be an append.
66888 ** This instruction only works for indices. The equivalent instruction
66889 ** for tables is OP_Insert.
66891 case OP_IdxInsert: { /* in2 */
66892 #if 0 /* local variables moved into u.bn */
66893 VdbeCursor *pC;
66894 BtCursor *pCrsr;
66895 int nKey;
66896 const char *zKey;
66897 #endif /* local variables moved into u.bn */
66899 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
66900 u.bn.pC = p->apCsr[pOp->p1];
66901 assert( u.bn.pC!=0 );
66902 pIn2 = &aMem[pOp->p2];
66903 assert( pIn2->flags & MEM_Blob );
66904 u.bn.pCrsr = u.bn.pC->pCursor;
66905 if( ALWAYS(u.bn.pCrsr!=0) ){
66906 assert( u.bn.pC->isTable==0 );
66907 rc = ExpandBlob(pIn2);
66908 if( rc==SQLITE_OK ){
66909 u.bn.nKey = pIn2->n;
66910 u.bn.zKey = pIn2->z;
66911 rc = sqlite3BtreeInsert(u.bn.pCrsr, u.bn.zKey, u.bn.nKey, "", 0, 0, pOp->p3,
66912 ((pOp->p5 & OPFLAG_USESEEKRESULT) ? u.bn.pC->seekResult : 0)
66914 assert( u.bn.pC->deferredMoveto==0 );
66915 u.bn.pC->cacheStatus = CACHE_STALE;
66918 break;
66921 /* Opcode: IdxDelete P1 P2 P3 * *
66923 ** The content of P3 registers starting at register P2 form
66924 ** an unpacked index key. This opcode removes that entry from the
66925 ** index opened by cursor P1.
66927 case OP_IdxDelete: {
66928 #if 0 /* local variables moved into u.bo */
66929 VdbeCursor *pC;
66930 BtCursor *pCrsr;
66931 int res;
66932 UnpackedRecord r;
66933 #endif /* local variables moved into u.bo */
66935 assert( pOp->p3>0 );
66936 assert( pOp->p2>0 && pOp->p2+pOp->p3<=p->nMem+1 );
66937 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
66938 u.bo.pC = p->apCsr[pOp->p1];
66939 assert( u.bo.pC!=0 );
66940 u.bo.pCrsr = u.bo.pC->pCursor;
66941 if( ALWAYS(u.bo.pCrsr!=0) ){
66942 u.bo.r.pKeyInfo = u.bo.pC->pKeyInfo;
66943 u.bo.r.nField = (u16)pOp->p3;
66944 u.bo.r.flags = 0;
66945 u.bo.r.aMem = &aMem[pOp->p2];
66946 #ifdef SQLITE_DEBUG
66947 { int i; for(i=0; i<u.bo.r.nField; i++) assert( memIsValid(&u.bo.r.aMem[i]) ); }
66948 #endif
66949 rc = sqlite3BtreeMovetoUnpacked(u.bo.pCrsr, &u.bo.r, 0, 0, &u.bo.res);
66950 if( rc==SQLITE_OK && u.bo.res==0 ){
66951 rc = sqlite3BtreeDelete(u.bo.pCrsr);
66953 assert( u.bo.pC->deferredMoveto==0 );
66954 u.bo.pC->cacheStatus = CACHE_STALE;
66956 break;
66959 /* Opcode: IdxRowid P1 P2 * * *
66961 ** Write into register P2 an integer which is the last entry in the record at
66962 ** the end of the index key pointed to by cursor P1. This integer should be
66963 ** the rowid of the table entry to which this index entry points.
66965 ** See also: Rowid, MakeRecord.
66967 case OP_IdxRowid: { /* out2-prerelease */
66968 #if 0 /* local variables moved into u.bp */
66969 BtCursor *pCrsr;
66970 VdbeCursor *pC;
66971 i64 rowid;
66972 #endif /* local variables moved into u.bp */
66974 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
66975 u.bp.pC = p->apCsr[pOp->p1];
66976 assert( u.bp.pC!=0 );
66977 u.bp.pCrsr = u.bp.pC->pCursor;
66978 pOut->flags = MEM_Null;
66979 if( ALWAYS(u.bp.pCrsr!=0) ){
66980 rc = sqlite3VdbeCursorMoveto(u.bp.pC);
66981 if( NEVER(rc) ) goto abort_due_to_error;
66982 assert( u.bp.pC->deferredMoveto==0 );
66983 assert( u.bp.pC->isTable==0 );
66984 if( !u.bp.pC->nullRow ){
66985 rc = sqlite3VdbeIdxRowid(db, u.bp.pCrsr, &u.bp.rowid);
66986 if( rc!=SQLITE_OK ){
66987 goto abort_due_to_error;
66989 pOut->u.i = u.bp.rowid;
66990 pOut->flags = MEM_Int;
66993 break;
66996 /* Opcode: IdxGE P1 P2 P3 P4 P5
66998 ** The P4 register values beginning with P3 form an unpacked index
66999 ** key that omits the ROWID. Compare this key value against the index
67000 ** that P1 is currently pointing to, ignoring the ROWID on the P1 index.
67002 ** If the P1 index entry is greater than or equal to the key value
67003 ** then jump to P2. Otherwise fall through to the next instruction.
67005 ** If P5 is non-zero then the key value is increased by an epsilon
67006 ** prior to the comparison. This make the opcode work like IdxGT except
67007 ** that if the key from register P3 is a prefix of the key in the cursor,
67008 ** the result is false whereas it would be true with IdxGT.
67010 /* Opcode: IdxLT P1 P2 P3 P4 P5
67012 ** The P4 register values beginning with P3 form an unpacked index
67013 ** key that omits the ROWID. Compare this key value against the index
67014 ** that P1 is currently pointing to, ignoring the ROWID on the P1 index.
67016 ** If the P1 index entry is less than the key value then jump to P2.
67017 ** Otherwise fall through to the next instruction.
67019 ** If P5 is non-zero then the key value is increased by an epsilon prior
67020 ** to the comparison. This makes the opcode work like IdxLE.
67022 case OP_IdxLT: /* jump */
67023 case OP_IdxGE: { /* jump */
67024 #if 0 /* local variables moved into u.bq */
67025 VdbeCursor *pC;
67026 int res;
67027 UnpackedRecord r;
67028 #endif /* local variables moved into u.bq */
67030 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
67031 u.bq.pC = p->apCsr[pOp->p1];
67032 assert( u.bq.pC!=0 );
67033 assert( u.bq.pC->isOrdered );
67034 if( ALWAYS(u.bq.pC->pCursor!=0) ){
67035 assert( u.bq.pC->deferredMoveto==0 );
67036 assert( pOp->p5==0 || pOp->p5==1 );
67037 assert( pOp->p4type==P4_INT32 );
67038 u.bq.r.pKeyInfo = u.bq.pC->pKeyInfo;
67039 u.bq.r.nField = (u16)pOp->p4.i;
67040 if( pOp->p5 ){
67041 u.bq.r.flags = UNPACKED_INCRKEY | UNPACKED_IGNORE_ROWID;
67042 }else{
67043 u.bq.r.flags = UNPACKED_IGNORE_ROWID;
67045 u.bq.r.aMem = &aMem[pOp->p3];
67046 #ifdef SQLITE_DEBUG
67047 { int i; for(i=0; i<u.bq.r.nField; i++) assert( memIsValid(&u.bq.r.aMem[i]) ); }
67048 #endif
67049 rc = sqlite3VdbeIdxKeyCompare(u.bq.pC, &u.bq.r, &u.bq.res);
67050 if( pOp->opcode==OP_IdxLT ){
67051 u.bq.res = -u.bq.res;
67052 }else{
67053 assert( pOp->opcode==OP_IdxGE );
67054 u.bq.res++;
67056 if( u.bq.res>0 ){
67057 pc = pOp->p2 - 1 ;
67060 break;
67063 /* Opcode: Destroy P1 P2 P3 * *
67065 ** Delete an entire database table or index whose root page in the database
67066 ** file is given by P1.
67068 ** The table being destroyed is in the main database file if P3==0. If
67069 ** P3==1 then the table to be clear is in the auxiliary database file
67070 ** that is used to store tables create using CREATE TEMPORARY TABLE.
67072 ** If AUTOVACUUM is enabled then it is possible that another root page
67073 ** might be moved into the newly deleted root page in order to keep all
67074 ** root pages contiguous at the beginning of the database. The former
67075 ** value of the root page that moved - its value before the move occurred -
67076 ** is stored in register P2. If no page
67077 ** movement was required (because the table being dropped was already
67078 ** the last one in the database) then a zero is stored in register P2.
67079 ** If AUTOVACUUM is disabled then a zero is stored in register P2.
67081 ** See also: Clear
67083 case OP_Destroy: { /* out2-prerelease */
67084 #if 0 /* local variables moved into u.br */
67085 int iMoved;
67086 int iCnt;
67087 Vdbe *pVdbe;
67088 int iDb;
67089 #endif /* local variables moved into u.br */
67090 #ifndef SQLITE_OMIT_VIRTUALTABLE
67091 u.br.iCnt = 0;
67092 for(u.br.pVdbe=db->pVdbe; u.br.pVdbe; u.br.pVdbe = u.br.pVdbe->pNext){
67093 if( u.br.pVdbe->magic==VDBE_MAGIC_RUN && u.br.pVdbe->inVtabMethod<2 && u.br.pVdbe->pc>=0 ){
67094 u.br.iCnt++;
67097 #else
67098 u.br.iCnt = db->activeVdbeCnt;
67099 #endif
67100 pOut->flags = MEM_Null;
67101 if( u.br.iCnt>1 ){
67102 rc = SQLITE_LOCKED;
67103 p->errorAction = OE_Abort;
67104 }else{
67105 u.br.iDb = pOp->p3;
67106 assert( u.br.iCnt==1 );
67107 assert( (p->btreeMask & (((yDbMask)1)<<u.br.iDb))!=0 );
67108 rc = sqlite3BtreeDropTable(db->aDb[u.br.iDb].pBt, pOp->p1, &u.br.iMoved);
67109 pOut->flags = MEM_Int;
67110 pOut->u.i = u.br.iMoved;
67111 #ifndef SQLITE_OMIT_AUTOVACUUM
67112 if( rc==SQLITE_OK && u.br.iMoved!=0 ){
67113 sqlite3RootPageMoved(db, u.br.iDb, u.br.iMoved, pOp->p1);
67114 /* All OP_Destroy operations occur on the same btree */
67115 assert( resetSchemaOnFault==0 || resetSchemaOnFault==u.br.iDb+1 );
67116 resetSchemaOnFault = u.br.iDb+1;
67118 #endif
67120 break;
67123 /* Opcode: Clear P1 P2 P3
67125 ** Delete all contents of the database table or index whose root page
67126 ** in the database file is given by P1. But, unlike Destroy, do not
67127 ** remove the table or index from the database file.
67129 ** The table being clear is in the main database file if P2==0. If
67130 ** P2==1 then the table to be clear is in the auxiliary database file
67131 ** that is used to store tables create using CREATE TEMPORARY TABLE.
67133 ** If the P3 value is non-zero, then the table referred to must be an
67134 ** intkey table (an SQL table, not an index). In this case the row change
67135 ** count is incremented by the number of rows in the table being cleared.
67136 ** If P3 is greater than zero, then the value stored in register P3 is
67137 ** also incremented by the number of rows in the table being cleared.
67139 ** See also: Destroy
67141 case OP_Clear: {
67142 #if 0 /* local variables moved into u.bs */
67143 int nChange;
67144 #endif /* local variables moved into u.bs */
67146 u.bs.nChange = 0;
67147 assert( (p->btreeMask & (((yDbMask)1)<<pOp->p2))!=0 );
67148 rc = sqlite3BtreeClearTable(
67149 db->aDb[pOp->p2].pBt, pOp->p1, (pOp->p3 ? &u.bs.nChange : 0)
67151 if( pOp->p3 ){
67152 p->nChange += u.bs.nChange;
67153 if( pOp->p3>0 ){
67154 assert( memIsValid(&aMem[pOp->p3]) );
67155 memAboutToChange(p, &aMem[pOp->p3]);
67156 aMem[pOp->p3].u.i += u.bs.nChange;
67159 break;
67162 /* Opcode: CreateTable P1 P2 * * *
67164 ** Allocate a new table in the main database file if P1==0 or in the
67165 ** auxiliary database file if P1==1 or in an attached database if
67166 ** P1>1. Write the root page number of the new table into
67167 ** register P2
67169 ** The difference between a table and an index is this: A table must
67170 ** have a 4-byte integer key and can have arbitrary data. An index
67171 ** has an arbitrary key but no data.
67173 ** See also: CreateIndex
67175 /* Opcode: CreateIndex P1 P2 * * *
67177 ** Allocate a new index in the main database file if P1==0 or in the
67178 ** auxiliary database file if P1==1 or in an attached database if
67179 ** P1>1. Write the root page number of the new table into
67180 ** register P2.
67182 ** See documentation on OP_CreateTable for additional information.
67184 case OP_CreateIndex: /* out2-prerelease */
67185 case OP_CreateTable: { /* out2-prerelease */
67186 #if 0 /* local variables moved into u.bt */
67187 int pgno;
67188 int flags;
67189 Db *pDb;
67190 #endif /* local variables moved into u.bt */
67192 u.bt.pgno = 0;
67193 assert( pOp->p1>=0 && pOp->p1<db->nDb );
67194 assert( (p->btreeMask & (((yDbMask)1)<<pOp->p1))!=0 );
67195 u.bt.pDb = &db->aDb[pOp->p1];
67196 assert( u.bt.pDb->pBt!=0 );
67197 if( pOp->opcode==OP_CreateTable ){
67198 /* u.bt.flags = BTREE_INTKEY; */
67199 u.bt.flags = BTREE_INTKEY;
67200 }else{
67201 u.bt.flags = BTREE_BLOBKEY;
67203 rc = sqlite3BtreeCreateTable(u.bt.pDb->pBt, &u.bt.pgno, u.bt.flags);
67204 pOut->u.i = u.bt.pgno;
67205 break;
67208 /* Opcode: ParseSchema P1 * * P4 *
67210 ** Read and parse all entries from the SQLITE_MASTER table of database P1
67211 ** that match the WHERE clause P4.
67213 ** This opcode invokes the parser to create a new virtual machine,
67214 ** then runs the new virtual machine. It is thus a re-entrant opcode.
67216 case OP_ParseSchema: {
67217 #if 0 /* local variables moved into u.bu */
67218 int iDb;
67219 const char *zMaster;
67220 char *zSql;
67221 InitData initData;
67222 #endif /* local variables moved into u.bu */
67224 /* Any prepared statement that invokes this opcode will hold mutexes
67225 ** on every btree. This is a prerequisite for invoking
67226 ** sqlite3InitCallback().
67228 #ifdef SQLITE_DEBUG
67229 for(u.bu.iDb=0; u.bu.iDb<db->nDb; u.bu.iDb++){
67230 assert( u.bu.iDb==1 || sqlite3BtreeHoldsMutex(db->aDb[u.bu.iDb].pBt) );
67232 #endif
67234 u.bu.iDb = pOp->p1;
67235 assert( u.bu.iDb>=0 && u.bu.iDb<db->nDb );
67236 assert( DbHasProperty(db, u.bu.iDb, DB_SchemaLoaded) );
67237 /* Used to be a conditional */ {
67238 u.bu.zMaster = SCHEMA_TABLE(u.bu.iDb);
67239 u.bu.initData.db = db;
67240 u.bu.initData.iDb = pOp->p1;
67241 u.bu.initData.pzErrMsg = &p->zErrMsg;
67242 u.bu.zSql = sqlite3MPrintf(db,
67243 "SELECT name, rootpage, sql FROM '%q'.%s WHERE %s ORDER BY rowid",
67244 db->aDb[u.bu.iDb].zName, u.bu.zMaster, pOp->p4.z);
67245 if( u.bu.zSql==0 ){
67246 rc = SQLITE_NOMEM;
67247 }else{
67248 assert( db->init.busy==0 );
67249 db->init.busy = 1;
67250 u.bu.initData.rc = SQLITE_OK;
67251 assert( !db->mallocFailed );
67252 rc = sqlite3_exec(db, u.bu.zSql, sqlite3InitCallback, &u.bu.initData, 0);
67253 if( rc==SQLITE_OK ) rc = u.bu.initData.rc;
67254 sqlite3DbFree(db, u.bu.zSql);
67255 db->init.busy = 0;
67258 if( rc==SQLITE_NOMEM ){
67259 goto no_mem;
67261 break;
67264 #if !defined(SQLITE_OMIT_ANALYZE)
67265 /* Opcode: LoadAnalysis P1 * * * *
67267 ** Read the sqlite_stat1 table for database P1 and load the content
67268 ** of that table into the internal index hash table. This will cause
67269 ** the analysis to be used when preparing all subsequent queries.
67271 case OP_LoadAnalysis: {
67272 assert( pOp->p1>=0 && pOp->p1<db->nDb );
67273 rc = sqlite3AnalysisLoad(db, pOp->p1);
67274 break;
67276 #endif /* !defined(SQLITE_OMIT_ANALYZE) */
67278 /* Opcode: DropTable P1 * * P4 *
67280 ** Remove the internal (in-memory) data structures that describe
67281 ** the table named P4 in database P1. This is called after a table
67282 ** is dropped in order to keep the internal representation of the
67283 ** schema consistent with what is on disk.
67285 case OP_DropTable: {
67286 sqlite3UnlinkAndDeleteTable(db, pOp->p1, pOp->p4.z);
67287 break;
67290 /* Opcode: DropIndex P1 * * P4 *
67292 ** Remove the internal (in-memory) data structures that describe
67293 ** the index named P4 in database P1. This is called after an index
67294 ** is dropped in order to keep the internal representation of the
67295 ** schema consistent with what is on disk.
67297 case OP_DropIndex: {
67298 sqlite3UnlinkAndDeleteIndex(db, pOp->p1, pOp->p4.z);
67299 break;
67302 /* Opcode: DropTrigger P1 * * P4 *
67304 ** Remove the internal (in-memory) data structures that describe
67305 ** the trigger named P4 in database P1. This is called after a trigger
67306 ** is dropped in order to keep the internal representation of the
67307 ** schema consistent with what is on disk.
67309 case OP_DropTrigger: {
67310 sqlite3UnlinkAndDeleteTrigger(db, pOp->p1, pOp->p4.z);
67311 break;
67315 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
67316 /* Opcode: IntegrityCk P1 P2 P3 * P5
67318 ** Do an analysis of the currently open database. Store in
67319 ** register P1 the text of an error message describing any problems.
67320 ** If no problems are found, store a NULL in register P1.
67322 ** The register P3 contains the maximum number of allowed errors.
67323 ** At most reg(P3) errors will be reported.
67324 ** In other words, the analysis stops as soon as reg(P1) errors are
67325 ** seen. Reg(P1) is updated with the number of errors remaining.
67327 ** The root page numbers of all tables in the database are integer
67328 ** stored in reg(P1), reg(P1+1), reg(P1+2), .... There are P2 tables
67329 ** total.
67331 ** If P5 is not zero, the check is done on the auxiliary database
67332 ** file, not the main database file.
67334 ** This opcode is used to implement the integrity_check pragma.
67336 case OP_IntegrityCk: {
67337 #if 0 /* local variables moved into u.bv */
67338 int nRoot; /* Number of tables to check. (Number of root pages.) */
67339 int *aRoot; /* Array of rootpage numbers for tables to be checked */
67340 int j; /* Loop counter */
67341 int nErr; /* Number of errors reported */
67342 char *z; /* Text of the error report */
67343 Mem *pnErr; /* Register keeping track of errors remaining */
67344 #endif /* local variables moved into u.bv */
67346 u.bv.nRoot = pOp->p2;
67347 assert( u.bv.nRoot>0 );
67348 u.bv.aRoot = sqlite3DbMallocRaw(db, sizeof(int)*(u.bv.nRoot+1) );
67349 if( u.bv.aRoot==0 ) goto no_mem;
67350 assert( pOp->p3>0 && pOp->p3<=p->nMem );
67351 u.bv.pnErr = &aMem[pOp->p3];
67352 assert( (u.bv.pnErr->flags & MEM_Int)!=0 );
67353 assert( (u.bv.pnErr->flags & (MEM_Str|MEM_Blob))==0 );
67354 pIn1 = &aMem[pOp->p1];
67355 for(u.bv.j=0; u.bv.j<u.bv.nRoot; u.bv.j++){
67356 u.bv.aRoot[u.bv.j] = (int)sqlite3VdbeIntValue(&pIn1[u.bv.j]);
67358 u.bv.aRoot[u.bv.j] = 0;
67359 assert( pOp->p5<db->nDb );
67360 assert( (p->btreeMask & (((yDbMask)1)<<pOp->p5))!=0 );
67361 u.bv.z = sqlite3BtreeIntegrityCheck(db->aDb[pOp->p5].pBt, u.bv.aRoot, u.bv.nRoot,
67362 (int)u.bv.pnErr->u.i, &u.bv.nErr);
67363 sqlite3DbFree(db, u.bv.aRoot);
67364 u.bv.pnErr->u.i -= u.bv.nErr;
67365 sqlite3VdbeMemSetNull(pIn1);
67366 if( u.bv.nErr==0 ){
67367 assert( u.bv.z==0 );
67368 }else if( u.bv.z==0 ){
67369 goto no_mem;
67370 }else{
67371 sqlite3VdbeMemSetStr(pIn1, u.bv.z, -1, SQLITE_UTF8, sqlite3_free);
67373 UPDATE_MAX_BLOBSIZE(pIn1);
67374 sqlite3VdbeChangeEncoding(pIn1, encoding);
67375 break;
67377 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
67379 /* Opcode: RowSetAdd P1 P2 * * *
67381 ** Insert the integer value held by register P2 into a boolean index
67382 ** held in register P1.
67384 ** An assertion fails if P2 is not an integer.
67386 case OP_RowSetAdd: { /* in1, in2 */
67387 pIn1 = &aMem[pOp->p1];
67388 pIn2 = &aMem[pOp->p2];
67389 assert( (pIn2->flags & MEM_Int)!=0 );
67390 if( (pIn1->flags & MEM_RowSet)==0 ){
67391 sqlite3VdbeMemSetRowSet(pIn1);
67392 if( (pIn1->flags & MEM_RowSet)==0 ) goto no_mem;
67394 sqlite3RowSetInsert(pIn1->u.pRowSet, pIn2->u.i);
67395 break;
67398 /* Opcode: RowSetRead P1 P2 P3 * *
67400 ** Extract the smallest value from boolean index P1 and put that value into
67401 ** register P3. Or, if boolean index P1 is initially empty, leave P3
67402 ** unchanged and jump to instruction P2.
67404 case OP_RowSetRead: { /* jump, in1, out3 */
67405 #if 0 /* local variables moved into u.bw */
67406 i64 val;
67407 #endif /* local variables moved into u.bw */
67408 CHECK_FOR_INTERRUPT;
67409 pIn1 = &aMem[pOp->p1];
67410 if( (pIn1->flags & MEM_RowSet)==0
67411 || sqlite3RowSetNext(pIn1->u.pRowSet, &u.bw.val)==0
67413 /* The boolean index is empty */
67414 sqlite3VdbeMemSetNull(pIn1);
67415 pc = pOp->p2 - 1;
67416 }else{
67417 /* A value was pulled from the index */
67418 sqlite3VdbeMemSetInt64(&aMem[pOp->p3], u.bw.val);
67420 break;
67423 /* Opcode: RowSetTest P1 P2 P3 P4
67425 ** Register P3 is assumed to hold a 64-bit integer value. If register P1
67426 ** contains a RowSet object and that RowSet object contains
67427 ** the value held in P3, jump to register P2. Otherwise, insert the
67428 ** integer in P3 into the RowSet and continue on to the
67429 ** next opcode.
67431 ** The RowSet object is optimized for the case where successive sets
67432 ** of integers, where each set contains no duplicates. Each set
67433 ** of values is identified by a unique P4 value. The first set
67434 ** must have P4==0, the final set P4=-1. P4 must be either -1 or
67435 ** non-negative. For non-negative values of P4 only the lower 4
67436 ** bits are significant.
67438 ** This allows optimizations: (a) when P4==0 there is no need to test
67439 ** the rowset object for P3, as it is guaranteed not to contain it,
67440 ** (b) when P4==-1 there is no need to insert the value, as it will
67441 ** never be tested for, and (c) when a value that is part of set X is
67442 ** inserted, there is no need to search to see if the same value was
67443 ** previously inserted as part of set X (only if it was previously
67444 ** inserted as part of some other set).
67446 case OP_RowSetTest: { /* jump, in1, in3 */
67447 #if 0 /* local variables moved into u.bx */
67448 int iSet;
67449 int exists;
67450 #endif /* local variables moved into u.bx */
67452 pIn1 = &aMem[pOp->p1];
67453 pIn3 = &aMem[pOp->p3];
67454 u.bx.iSet = pOp->p4.i;
67455 assert( pIn3->flags&MEM_Int );
67457 /* If there is anything other than a rowset object in memory cell P1,
67458 ** delete it now and initialize P1 with an empty rowset
67460 if( (pIn1->flags & MEM_RowSet)==0 ){
67461 sqlite3VdbeMemSetRowSet(pIn1);
67462 if( (pIn1->flags & MEM_RowSet)==0 ) goto no_mem;
67465 assert( pOp->p4type==P4_INT32 );
67466 assert( u.bx.iSet==-1 || u.bx.iSet>=0 );
67467 if( u.bx.iSet ){
67468 u.bx.exists = sqlite3RowSetTest(pIn1->u.pRowSet,
67469 (u8)(u.bx.iSet>=0 ? u.bx.iSet & 0xf : 0xff),
67470 pIn3->u.i);
67471 if( u.bx.exists ){
67472 pc = pOp->p2 - 1;
67473 break;
67476 if( u.bx.iSet>=0 ){
67477 sqlite3RowSetInsert(pIn1->u.pRowSet, pIn3->u.i);
67479 break;
67483 #ifndef SQLITE_OMIT_TRIGGER
67485 /* Opcode: Program P1 P2 P3 P4 *
67487 ** Execute the trigger program passed as P4 (type P4_SUBPROGRAM).
67489 ** P1 contains the address of the memory cell that contains the first memory
67490 ** cell in an array of values used as arguments to the sub-program. P2
67491 ** contains the address to jump to if the sub-program throws an IGNORE
67492 ** exception using the RAISE() function. Register P3 contains the address
67493 ** of a memory cell in this (the parent) VM that is used to allocate the
67494 ** memory required by the sub-vdbe at runtime.
67496 ** P4 is a pointer to the VM containing the trigger program.
67498 case OP_Program: { /* jump */
67499 #if 0 /* local variables moved into u.by */
67500 int nMem; /* Number of memory registers for sub-program */
67501 int nByte; /* Bytes of runtime space required for sub-program */
67502 Mem *pRt; /* Register to allocate runtime space */
67503 Mem *pMem; /* Used to iterate through memory cells */
67504 Mem *pEnd; /* Last memory cell in new array */
67505 VdbeFrame *pFrame; /* New vdbe frame to execute in */
67506 SubProgram *pProgram; /* Sub-program to execute */
67507 void *t; /* Token identifying trigger */
67508 #endif /* local variables moved into u.by */
67510 u.by.pProgram = pOp->p4.pProgram;
67511 u.by.pRt = &aMem[pOp->p3];
67512 assert( memIsValid(u.by.pRt) );
67513 assert( u.by.pProgram->nOp>0 );
67515 /* If the p5 flag is clear, then recursive invocation of triggers is
67516 ** disabled for backwards compatibility (p5 is set if this sub-program
67517 ** is really a trigger, not a foreign key action, and the flag set
67518 ** and cleared by the "PRAGMA recursive_triggers" command is clear).
67520 ** It is recursive invocation of triggers, at the SQL level, that is
67521 ** disabled. In some cases a single trigger may generate more than one
67522 ** SubProgram (if the trigger may be executed with more than one different
67523 ** ON CONFLICT algorithm). SubProgram structures associated with a
67524 ** single trigger all have the same value for the SubProgram.token
67525 ** variable. */
67526 if( pOp->p5 ){
67527 u.by.t = u.by.pProgram->token;
67528 for(u.by.pFrame=p->pFrame; u.by.pFrame && u.by.pFrame->token!=u.by.t; u.by.pFrame=u.by.pFrame->pParent);
67529 if( u.by.pFrame ) break;
67532 if( p->nFrame>=db->aLimit[SQLITE_LIMIT_TRIGGER_DEPTH] ){
67533 rc = SQLITE_ERROR;
67534 sqlite3SetString(&p->zErrMsg, db, "too many levels of trigger recursion");
67535 break;
67538 /* Register u.by.pRt is used to store the memory required to save the state
67539 ** of the current program, and the memory required at runtime to execute
67540 ** the trigger program. If this trigger has been fired before, then u.by.pRt
67541 ** is already allocated. Otherwise, it must be initialized. */
67542 if( (u.by.pRt->flags&MEM_Frame)==0 ){
67543 /* SubProgram.nMem is set to the number of memory cells used by the
67544 ** program stored in SubProgram.aOp. As well as these, one memory
67545 ** cell is required for each cursor used by the program. Set local
67546 ** variable u.by.nMem (and later, VdbeFrame.nChildMem) to this value.
67548 u.by.nMem = u.by.pProgram->nMem + u.by.pProgram->nCsr;
67549 u.by.nByte = ROUND8(sizeof(VdbeFrame))
67550 + u.by.nMem * sizeof(Mem)
67551 + u.by.pProgram->nCsr * sizeof(VdbeCursor *);
67552 u.by.pFrame = sqlite3DbMallocZero(db, u.by.nByte);
67553 if( !u.by.pFrame ){
67554 goto no_mem;
67556 sqlite3VdbeMemRelease(u.by.pRt);
67557 u.by.pRt->flags = MEM_Frame;
67558 u.by.pRt->u.pFrame = u.by.pFrame;
67560 u.by.pFrame->v = p;
67561 u.by.pFrame->nChildMem = u.by.nMem;
67562 u.by.pFrame->nChildCsr = u.by.pProgram->nCsr;
67563 u.by.pFrame->pc = pc;
67564 u.by.pFrame->aMem = p->aMem;
67565 u.by.pFrame->nMem = p->nMem;
67566 u.by.pFrame->apCsr = p->apCsr;
67567 u.by.pFrame->nCursor = p->nCursor;
67568 u.by.pFrame->aOp = p->aOp;
67569 u.by.pFrame->nOp = p->nOp;
67570 u.by.pFrame->token = u.by.pProgram->token;
67572 u.by.pEnd = &VdbeFrameMem(u.by.pFrame)[u.by.pFrame->nChildMem];
67573 for(u.by.pMem=VdbeFrameMem(u.by.pFrame); u.by.pMem!=u.by.pEnd; u.by.pMem++){
67574 u.by.pMem->flags = MEM_Null;
67575 u.by.pMem->db = db;
67577 }else{
67578 u.by.pFrame = u.by.pRt->u.pFrame;
67579 assert( u.by.pProgram->nMem+u.by.pProgram->nCsr==u.by.pFrame->nChildMem );
67580 assert( u.by.pProgram->nCsr==u.by.pFrame->nChildCsr );
67581 assert( pc==u.by.pFrame->pc );
67584 p->nFrame++;
67585 u.by.pFrame->pParent = p->pFrame;
67586 u.by.pFrame->lastRowid = db->lastRowid;
67587 u.by.pFrame->nChange = p->nChange;
67588 p->nChange = 0;
67589 p->pFrame = u.by.pFrame;
67590 p->aMem = aMem = &VdbeFrameMem(u.by.pFrame)[-1];
67591 p->nMem = u.by.pFrame->nChildMem;
67592 p->nCursor = (u16)u.by.pFrame->nChildCsr;
67593 p->apCsr = (VdbeCursor **)&aMem[p->nMem+1];
67594 p->aOp = aOp = u.by.pProgram->aOp;
67595 p->nOp = u.by.pProgram->nOp;
67596 pc = -1;
67598 break;
67601 /* Opcode: Param P1 P2 * * *
67603 ** This opcode is only ever present in sub-programs called via the
67604 ** OP_Program instruction. Copy a value currently stored in a memory
67605 ** cell of the calling (parent) frame to cell P2 in the current frames
67606 ** address space. This is used by trigger programs to access the new.*
67607 ** and old.* values.
67609 ** The address of the cell in the parent frame is determined by adding
67610 ** the value of the P1 argument to the value of the P1 argument to the
67611 ** calling OP_Program instruction.
67613 case OP_Param: { /* out2-prerelease */
67614 #if 0 /* local variables moved into u.bz */
67615 VdbeFrame *pFrame;
67616 Mem *pIn;
67617 #endif /* local variables moved into u.bz */
67618 u.bz.pFrame = p->pFrame;
67619 u.bz.pIn = &u.bz.pFrame->aMem[pOp->p1 + u.bz.pFrame->aOp[u.bz.pFrame->pc].p1];
67620 sqlite3VdbeMemShallowCopy(pOut, u.bz.pIn, MEM_Ephem);
67621 break;
67624 #endif /* #ifndef SQLITE_OMIT_TRIGGER */
67626 #ifndef SQLITE_OMIT_FOREIGN_KEY
67627 /* Opcode: FkCounter P1 P2 * * *
67629 ** Increment a "constraint counter" by P2 (P2 may be negative or positive).
67630 ** If P1 is non-zero, the database constraint counter is incremented
67631 ** (deferred foreign key constraints). Otherwise, if P1 is zero, the
67632 ** statement counter is incremented (immediate foreign key constraints).
67634 case OP_FkCounter: {
67635 if( pOp->p1 ){
67636 db->nDeferredCons += pOp->p2;
67637 }else{
67638 p->nFkConstraint += pOp->p2;
67640 break;
67643 /* Opcode: FkIfZero P1 P2 * * *
67645 ** This opcode tests if a foreign key constraint-counter is currently zero.
67646 ** If so, jump to instruction P2. Otherwise, fall through to the next
67647 ** instruction.
67649 ** If P1 is non-zero, then the jump is taken if the database constraint-counter
67650 ** is zero (the one that counts deferred constraint violations). If P1 is
67651 ** zero, the jump is taken if the statement constraint-counter is zero
67652 ** (immediate foreign key constraint violations).
67654 case OP_FkIfZero: { /* jump */
67655 if( pOp->p1 ){
67656 if( db->nDeferredCons==0 ) pc = pOp->p2-1;
67657 }else{
67658 if( p->nFkConstraint==0 ) pc = pOp->p2-1;
67660 break;
67662 #endif /* #ifndef SQLITE_OMIT_FOREIGN_KEY */
67664 #ifndef SQLITE_OMIT_AUTOINCREMENT
67665 /* Opcode: MemMax P1 P2 * * *
67667 ** P1 is a register in the root frame of this VM (the root frame is
67668 ** different from the current frame if this instruction is being executed
67669 ** within a sub-program). Set the value of register P1 to the maximum of
67670 ** its current value and the value in register P2.
67672 ** This instruction throws an error if the memory cell is not initially
67673 ** an integer.
67675 case OP_MemMax: { /* in2 */
67676 #if 0 /* local variables moved into u.ca */
67677 Mem *pIn1;
67678 VdbeFrame *pFrame;
67679 #endif /* local variables moved into u.ca */
67680 if( p->pFrame ){
67681 for(u.ca.pFrame=p->pFrame; u.ca.pFrame->pParent; u.ca.pFrame=u.ca.pFrame->pParent);
67682 u.ca.pIn1 = &u.ca.pFrame->aMem[pOp->p1];
67683 }else{
67684 u.ca.pIn1 = &aMem[pOp->p1];
67686 assert( memIsValid(u.ca.pIn1) );
67687 sqlite3VdbeMemIntegerify(u.ca.pIn1);
67688 pIn2 = &aMem[pOp->p2];
67689 sqlite3VdbeMemIntegerify(pIn2);
67690 if( u.ca.pIn1->u.i<pIn2->u.i){
67691 u.ca.pIn1->u.i = pIn2->u.i;
67693 break;
67695 #endif /* SQLITE_OMIT_AUTOINCREMENT */
67697 /* Opcode: IfPos P1 P2 * * *
67699 ** If the value of register P1 is 1 or greater, jump to P2.
67701 ** It is illegal to use this instruction on a register that does
67702 ** not contain an integer. An assertion fault will result if you try.
67704 case OP_IfPos: { /* jump, in1 */
67705 pIn1 = &aMem[pOp->p1];
67706 assert( pIn1->flags&MEM_Int );
67707 if( pIn1->u.i>0 ){
67708 pc = pOp->p2 - 1;
67710 break;
67713 /* Opcode: IfNeg P1 P2 * * *
67715 ** If the value of register P1 is less than zero, jump to P2.
67717 ** It is illegal to use this instruction on a register that does
67718 ** not contain an integer. An assertion fault will result if you try.
67720 case OP_IfNeg: { /* jump, in1 */
67721 pIn1 = &aMem[pOp->p1];
67722 assert( pIn1->flags&MEM_Int );
67723 if( pIn1->u.i<0 ){
67724 pc = pOp->p2 - 1;
67726 break;
67729 /* Opcode: IfZero P1 P2 P3 * *
67731 ** The register P1 must contain an integer. Add literal P3 to the
67732 ** value in register P1. If the result is exactly 0, jump to P2.
67734 ** It is illegal to use this instruction on a register that does
67735 ** not contain an integer. An assertion fault will result if you try.
67737 case OP_IfZero: { /* jump, in1 */
67738 pIn1 = &aMem[pOp->p1];
67739 assert( pIn1->flags&MEM_Int );
67740 pIn1->u.i += pOp->p3;
67741 if( pIn1->u.i==0 ){
67742 pc = pOp->p2 - 1;
67744 break;
67747 /* Opcode: AggStep * P2 P3 P4 P5
67749 ** Execute the step function for an aggregate. The
67750 ** function has P5 arguments. P4 is a pointer to the FuncDef
67751 ** structure that specifies the function. Use register
67752 ** P3 as the accumulator.
67754 ** The P5 arguments are taken from register P2 and its
67755 ** successors.
67757 case OP_AggStep: {
67758 #if 0 /* local variables moved into u.cb */
67759 int n;
67760 int i;
67761 Mem *pMem;
67762 Mem *pRec;
67763 sqlite3_context ctx;
67764 sqlite3_value **apVal;
67765 #endif /* local variables moved into u.cb */
67767 u.cb.n = pOp->p5;
67768 assert( u.cb.n>=0 );
67769 u.cb.pRec = &aMem[pOp->p2];
67770 u.cb.apVal = p->apArg;
67771 assert( u.cb.apVal || u.cb.n==0 );
67772 for(u.cb.i=0; u.cb.i<u.cb.n; u.cb.i++, u.cb.pRec++){
67773 assert( memIsValid(u.cb.pRec) );
67774 u.cb.apVal[u.cb.i] = u.cb.pRec;
67775 memAboutToChange(p, u.cb.pRec);
67776 sqlite3VdbeMemStoreType(u.cb.pRec);
67778 u.cb.ctx.pFunc = pOp->p4.pFunc;
67779 assert( pOp->p3>0 && pOp->p3<=p->nMem );
67780 u.cb.ctx.pMem = u.cb.pMem = &aMem[pOp->p3];
67781 u.cb.pMem->n++;
67782 u.cb.ctx.s.flags = MEM_Null;
67783 u.cb.ctx.s.z = 0;
67784 u.cb.ctx.s.zMalloc = 0;
67785 u.cb.ctx.s.xDel = 0;
67786 u.cb.ctx.s.db = db;
67787 u.cb.ctx.isError = 0;
67788 u.cb.ctx.pColl = 0;
67789 if( u.cb.ctx.pFunc->flags & SQLITE_FUNC_NEEDCOLL ){
67790 assert( pOp>p->aOp );
67791 assert( pOp[-1].p4type==P4_COLLSEQ );
67792 assert( pOp[-1].opcode==OP_CollSeq );
67793 u.cb.ctx.pColl = pOp[-1].p4.pColl;
67795 (u.cb.ctx.pFunc->xStep)(&u.cb.ctx, u.cb.n, u.cb.apVal); /* IMP: R-24505-23230 */
67796 if( u.cb.ctx.isError ){
67797 sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3_value_text(&u.cb.ctx.s));
67798 rc = u.cb.ctx.isError;
67801 sqlite3VdbeMemRelease(&u.cb.ctx.s);
67803 break;
67806 /* Opcode: AggFinal P1 P2 * P4 *
67808 ** Execute the finalizer function for an aggregate. P1 is
67809 ** the memory location that is the accumulator for the aggregate.
67811 ** P2 is the number of arguments that the step function takes and
67812 ** P4 is a pointer to the FuncDef for this function. The P2
67813 ** argument is not used by this opcode. It is only there to disambiguate
67814 ** functions that can take varying numbers of arguments. The
67815 ** P4 argument is only needed for the degenerate case where
67816 ** the step function was not previously called.
67818 case OP_AggFinal: {
67819 #if 0 /* local variables moved into u.cc */
67820 Mem *pMem;
67821 #endif /* local variables moved into u.cc */
67822 assert( pOp->p1>0 && pOp->p1<=p->nMem );
67823 u.cc.pMem = &aMem[pOp->p1];
67824 assert( (u.cc.pMem->flags & ~(MEM_Null|MEM_Agg))==0 );
67825 rc = sqlite3VdbeMemFinalize(u.cc.pMem, pOp->p4.pFunc);
67826 if( rc ){
67827 sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3_value_text(u.cc.pMem));
67829 sqlite3VdbeChangeEncoding(u.cc.pMem, encoding);
67830 UPDATE_MAX_BLOBSIZE(u.cc.pMem);
67831 if( sqlite3VdbeMemTooBig(u.cc.pMem) ){
67832 goto too_big;
67834 break;
67837 #ifndef SQLITE_OMIT_WAL
67838 /* Opcode: Checkpoint P1 P2 P3 * *
67840 ** Checkpoint database P1. This is a no-op if P1 is not currently in
67841 ** WAL mode. Parameter P2 is one of SQLITE_CHECKPOINT_PASSIVE, FULL
67842 ** or RESTART. Write 1 or 0 into mem[P3] if the checkpoint returns
67843 ** SQLITE_BUSY or not, respectively. Write the number of pages in the
67844 ** WAL after the checkpoint into mem[P3+1] and the number of pages
67845 ** in the WAL that have been checkpointed after the checkpoint
67846 ** completes into mem[P3+2]. However on an error, mem[P3+1] and
67847 ** mem[P3+2] are initialized to -1.
67849 case OP_Checkpoint: {
67850 #if 0 /* local variables moved into u.cd */
67851 int i; /* Loop counter */
67852 int aRes[3]; /* Results */
67853 Mem *pMem; /* Write results here */
67854 #endif /* local variables moved into u.cd */
67856 u.cd.aRes[0] = 0;
67857 u.cd.aRes[1] = u.cd.aRes[2] = -1;
67858 assert( pOp->p2==SQLITE_CHECKPOINT_PASSIVE
67859 || pOp->p2==SQLITE_CHECKPOINT_FULL
67860 || pOp->p2==SQLITE_CHECKPOINT_RESTART
67862 rc = sqlite3Checkpoint(db, pOp->p1, pOp->p2, &u.cd.aRes[1], &u.cd.aRes[2]);
67863 if( rc==SQLITE_BUSY ){
67864 rc = SQLITE_OK;
67865 u.cd.aRes[0] = 1;
67867 for(u.cd.i=0, u.cd.pMem = &aMem[pOp->p3]; u.cd.i<3; u.cd.i++, u.cd.pMem++){
67868 sqlite3VdbeMemSetInt64(u.cd.pMem, (i64)u.cd.aRes[u.cd.i]);
67870 break;
67872 #endif
67874 #ifndef SQLITE_OMIT_PRAGMA
67875 /* Opcode: JournalMode P1 P2 P3 * P5
67877 ** Change the journal mode of database P1 to P3. P3 must be one of the
67878 ** PAGER_JOURNALMODE_XXX values. If changing between the various rollback
67879 ** modes (delete, truncate, persist, off and memory), this is a simple
67880 ** operation. No IO is required.
67882 ** If changing into or out of WAL mode the procedure is more complicated.
67884 ** Write a string containing the final journal-mode to register P2.
67886 case OP_JournalMode: { /* out2-prerelease */
67887 #if 0 /* local variables moved into u.ce */
67888 Btree *pBt; /* Btree to change journal mode of */
67889 Pager *pPager; /* Pager associated with pBt */
67890 int eNew; /* New journal mode */
67891 int eOld; /* The old journal mode */
67892 const char *zFilename; /* Name of database file for pPager */
67893 #endif /* local variables moved into u.ce */
67895 u.ce.eNew = pOp->p3;
67896 assert( u.ce.eNew==PAGER_JOURNALMODE_DELETE
67897 || u.ce.eNew==PAGER_JOURNALMODE_TRUNCATE
67898 || u.ce.eNew==PAGER_JOURNALMODE_PERSIST
67899 || u.ce.eNew==PAGER_JOURNALMODE_OFF
67900 || u.ce.eNew==PAGER_JOURNALMODE_MEMORY
67901 || u.ce.eNew==PAGER_JOURNALMODE_WAL
67902 || u.ce.eNew==PAGER_JOURNALMODE_QUERY
67904 assert( pOp->p1>=0 && pOp->p1<db->nDb );
67906 u.ce.pBt = db->aDb[pOp->p1].pBt;
67907 u.ce.pPager = sqlite3BtreePager(u.ce.pBt);
67908 u.ce.eOld = sqlite3PagerGetJournalMode(u.ce.pPager);
67909 if( u.ce.eNew==PAGER_JOURNALMODE_QUERY ) u.ce.eNew = u.ce.eOld;
67910 if( !sqlite3PagerOkToChangeJournalMode(u.ce.pPager) ) u.ce.eNew = u.ce.eOld;
67912 #ifndef SQLITE_OMIT_WAL
67913 u.ce.zFilename = sqlite3PagerFilename(u.ce.pPager);
67915 /* Do not allow a transition to journal_mode=WAL for a database
67916 ** in temporary storage or if the VFS does not support shared memory
67918 if( u.ce.eNew==PAGER_JOURNALMODE_WAL
67919 && (u.ce.zFilename[0]==0 /* Temp file */
67920 || !sqlite3PagerWalSupported(u.ce.pPager)) /* No shared-memory support */
67922 u.ce.eNew = u.ce.eOld;
67925 if( (u.ce.eNew!=u.ce.eOld)
67926 && (u.ce.eOld==PAGER_JOURNALMODE_WAL || u.ce.eNew==PAGER_JOURNALMODE_WAL)
67928 if( !db->autoCommit || db->activeVdbeCnt>1 ){
67929 rc = SQLITE_ERROR;
67930 sqlite3SetString(&p->zErrMsg, db,
67931 "cannot change %s wal mode from within a transaction",
67932 (u.ce.eNew==PAGER_JOURNALMODE_WAL ? "into" : "out of")
67934 break;
67935 }else{
67937 if( u.ce.eOld==PAGER_JOURNALMODE_WAL ){
67938 /* If leaving WAL mode, close the log file. If successful, the call
67939 ** to PagerCloseWal() checkpoints and deletes the write-ahead-log
67940 ** file. An EXCLUSIVE lock may still be held on the database file
67941 ** after a successful return.
67943 rc = sqlite3PagerCloseWal(u.ce.pPager);
67944 if( rc==SQLITE_OK ){
67945 sqlite3PagerSetJournalMode(u.ce.pPager, u.ce.eNew);
67947 }else if( u.ce.eOld==PAGER_JOURNALMODE_MEMORY ){
67948 /* Cannot transition directly from MEMORY to WAL. Use mode OFF
67949 ** as an intermediate */
67950 sqlite3PagerSetJournalMode(u.ce.pPager, PAGER_JOURNALMODE_OFF);
67953 /* Open a transaction on the database file. Regardless of the journal
67954 ** mode, this transaction always uses a rollback journal.
67956 assert( sqlite3BtreeIsInTrans(u.ce.pBt)==0 );
67957 if( rc==SQLITE_OK ){
67958 rc = sqlite3BtreeSetVersion(u.ce.pBt, (u.ce.eNew==PAGER_JOURNALMODE_WAL ? 2 : 1));
67962 #endif /* ifndef SQLITE_OMIT_WAL */
67964 if( rc ){
67965 u.ce.eNew = u.ce.eOld;
67967 u.ce.eNew = sqlite3PagerSetJournalMode(u.ce.pPager, u.ce.eNew);
67969 pOut = &aMem[pOp->p2];
67970 pOut->flags = MEM_Str|MEM_Static|MEM_Term;
67971 pOut->z = (char *)sqlite3JournalModename(u.ce.eNew);
67972 pOut->n = sqlite3Strlen30(pOut->z);
67973 pOut->enc = SQLITE_UTF8;
67974 sqlite3VdbeChangeEncoding(pOut, encoding);
67975 break;
67977 #endif /* SQLITE_OMIT_PRAGMA */
67979 #if !defined(SQLITE_OMIT_VACUUM) && !defined(SQLITE_OMIT_ATTACH)
67980 /* Opcode: Vacuum * * * * *
67982 ** Vacuum the entire database. This opcode will cause other virtual
67983 ** machines to be created and run. It may not be called from within
67984 ** a transaction.
67986 case OP_Vacuum: {
67987 rc = sqlite3RunVacuum(&p->zErrMsg, db);
67988 break;
67990 #endif
67992 #if !defined(SQLITE_OMIT_AUTOVACUUM)
67993 /* Opcode: IncrVacuum P1 P2 * * *
67995 ** Perform a single step of the incremental vacuum procedure on
67996 ** the P1 database. If the vacuum has finished, jump to instruction
67997 ** P2. Otherwise, fall through to the next instruction.
67999 case OP_IncrVacuum: { /* jump */
68000 #if 0 /* local variables moved into u.cf */
68001 Btree *pBt;
68002 #endif /* local variables moved into u.cf */
68004 assert( pOp->p1>=0 && pOp->p1<db->nDb );
68005 assert( (p->btreeMask & (((yDbMask)1)<<pOp->p1))!=0 );
68006 u.cf.pBt = db->aDb[pOp->p1].pBt;
68007 rc = sqlite3BtreeIncrVacuum(u.cf.pBt);
68008 if( rc==SQLITE_DONE ){
68009 pc = pOp->p2 - 1;
68010 rc = SQLITE_OK;
68012 break;
68014 #endif
68016 /* Opcode: Expire P1 * * * *
68018 ** Cause precompiled statements to become expired. An expired statement
68019 ** fails with an error code of SQLITE_SCHEMA if it is ever executed
68020 ** (via sqlite3_step()).
68022 ** If P1 is 0, then all SQL statements become expired. If P1 is non-zero,
68023 ** then only the currently executing statement is affected.
68025 case OP_Expire: {
68026 if( !pOp->p1 ){
68027 sqlite3ExpirePreparedStatements(db);
68028 }else{
68029 p->expired = 1;
68031 break;
68034 #ifndef SQLITE_OMIT_SHARED_CACHE
68035 /* Opcode: TableLock P1 P2 P3 P4 *
68037 ** Obtain a lock on a particular table. This instruction is only used when
68038 ** the shared-cache feature is enabled.
68040 ** P1 is the index of the database in sqlite3.aDb[] of the database
68041 ** on which the lock is acquired. A readlock is obtained if P3==0 or
68042 ** a write lock if P3==1.
68044 ** P2 contains the root-page of the table to lock.
68046 ** P4 contains a pointer to the name of the table being locked. This is only
68047 ** used to generate an error message if the lock cannot be obtained.
68049 case OP_TableLock: {
68050 u8 isWriteLock = (u8)pOp->p3;
68051 if( isWriteLock || 0==(db->flags&SQLITE_ReadUncommitted) ){
68052 int p1 = pOp->p1;
68053 assert( p1>=0 && p1<db->nDb );
68054 assert( (p->btreeMask & (((yDbMask)1)<<p1))!=0 );
68055 assert( isWriteLock==0 || isWriteLock==1 );
68056 rc = sqlite3BtreeLockTable(db->aDb[p1].pBt, pOp->p2, isWriteLock);
68057 if( (rc&0xFF)==SQLITE_LOCKED ){
68058 const char *z = pOp->p4.z;
68059 sqlite3SetString(&p->zErrMsg, db, "database table is locked: %s", z);
68062 break;
68064 #endif /* SQLITE_OMIT_SHARED_CACHE */
68066 #ifndef SQLITE_OMIT_VIRTUALTABLE
68067 /* Opcode: VBegin * * * P4 *
68069 ** P4 may be a pointer to an sqlite3_vtab structure. If so, call the
68070 ** xBegin method for that table.
68072 ** Also, whether or not P4 is set, check that this is not being called from
68073 ** within a callback to a virtual table xSync() method. If it is, the error
68074 ** code will be set to SQLITE_LOCKED.
68076 case OP_VBegin: {
68077 #if 0 /* local variables moved into u.cg */
68078 VTable *pVTab;
68079 #endif /* local variables moved into u.cg */
68080 u.cg.pVTab = pOp->p4.pVtab;
68081 rc = sqlite3VtabBegin(db, u.cg.pVTab);
68082 if( u.cg.pVTab ) importVtabErrMsg(p, u.cg.pVTab->pVtab);
68083 break;
68085 #endif /* SQLITE_OMIT_VIRTUALTABLE */
68087 #ifndef SQLITE_OMIT_VIRTUALTABLE
68088 /* Opcode: VCreate P1 * * P4 *
68090 ** P4 is the name of a virtual table in database P1. Call the xCreate method
68091 ** for that table.
68093 case OP_VCreate: {
68094 rc = sqlite3VtabCallCreate(db, pOp->p1, pOp->p4.z, &p->zErrMsg);
68095 break;
68097 #endif /* SQLITE_OMIT_VIRTUALTABLE */
68099 #ifndef SQLITE_OMIT_VIRTUALTABLE
68100 /* Opcode: VDestroy P1 * * P4 *
68102 ** P4 is the name of a virtual table in database P1. Call the xDestroy method
68103 ** of that table.
68105 case OP_VDestroy: {
68106 p->inVtabMethod = 2;
68107 rc = sqlite3VtabCallDestroy(db, pOp->p1, pOp->p4.z);
68108 p->inVtabMethod = 0;
68109 break;
68111 #endif /* SQLITE_OMIT_VIRTUALTABLE */
68113 #ifndef SQLITE_OMIT_VIRTUALTABLE
68114 /* Opcode: VOpen P1 * * P4 *
68116 ** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
68117 ** P1 is a cursor number. This opcode opens a cursor to the virtual
68118 ** table and stores that cursor in P1.
68120 case OP_VOpen: {
68121 #if 0 /* local variables moved into u.ch */
68122 VdbeCursor *pCur;
68123 sqlite3_vtab_cursor *pVtabCursor;
68124 sqlite3_vtab *pVtab;
68125 sqlite3_module *pModule;
68126 #endif /* local variables moved into u.ch */
68128 u.ch.pCur = 0;
68129 u.ch.pVtabCursor = 0;
68130 u.ch.pVtab = pOp->p4.pVtab->pVtab;
68131 u.ch.pModule = (sqlite3_module *)u.ch.pVtab->pModule;
68132 assert(u.ch.pVtab && u.ch.pModule);
68133 rc = u.ch.pModule->xOpen(u.ch.pVtab, &u.ch.pVtabCursor);
68134 importVtabErrMsg(p, u.ch.pVtab);
68135 if( SQLITE_OK==rc ){
68136 /* Initialize sqlite3_vtab_cursor base class */
68137 u.ch.pVtabCursor->pVtab = u.ch.pVtab;
68139 /* Initialise vdbe cursor object */
68140 u.ch.pCur = allocateCursor(p, pOp->p1, 0, -1, 0);
68141 if( u.ch.pCur ){
68142 u.ch.pCur->pVtabCursor = u.ch.pVtabCursor;
68143 u.ch.pCur->pModule = u.ch.pVtabCursor->pVtab->pModule;
68144 }else{
68145 db->mallocFailed = 1;
68146 u.ch.pModule->xClose(u.ch.pVtabCursor);
68149 break;
68151 #endif /* SQLITE_OMIT_VIRTUALTABLE */
68153 #ifndef SQLITE_OMIT_VIRTUALTABLE
68154 /* Opcode: VFilter P1 P2 P3 P4 *
68156 ** P1 is a cursor opened using VOpen. P2 is an address to jump to if
68157 ** the filtered result set is empty.
68159 ** P4 is either NULL or a string that was generated by the xBestIndex
68160 ** method of the module. The interpretation of the P4 string is left
68161 ** to the module implementation.
68163 ** This opcode invokes the xFilter method on the virtual table specified
68164 ** by P1. The integer query plan parameter to xFilter is stored in register
68165 ** P3. Register P3+1 stores the argc parameter to be passed to the
68166 ** xFilter method. Registers P3+2..P3+1+argc are the argc
68167 ** additional parameters which are passed to
68168 ** xFilter as argv. Register P3+2 becomes argv[0] when passed to xFilter.
68170 ** A jump is made to P2 if the result set after filtering would be empty.
68172 case OP_VFilter: { /* jump */
68173 #if 0 /* local variables moved into u.ci */
68174 int nArg;
68175 int iQuery;
68176 const sqlite3_module *pModule;
68177 Mem *pQuery;
68178 Mem *pArgc;
68179 sqlite3_vtab_cursor *pVtabCursor;
68180 sqlite3_vtab *pVtab;
68181 VdbeCursor *pCur;
68182 int res;
68183 int i;
68184 Mem **apArg;
68185 #endif /* local variables moved into u.ci */
68187 u.ci.pQuery = &aMem[pOp->p3];
68188 u.ci.pArgc = &u.ci.pQuery[1];
68189 u.ci.pCur = p->apCsr[pOp->p1];
68190 assert( memIsValid(u.ci.pQuery) );
68191 REGISTER_TRACE(pOp->p3, u.ci.pQuery);
68192 assert( u.ci.pCur->pVtabCursor );
68193 u.ci.pVtabCursor = u.ci.pCur->pVtabCursor;
68194 u.ci.pVtab = u.ci.pVtabCursor->pVtab;
68195 u.ci.pModule = u.ci.pVtab->pModule;
68197 /* Grab the index number and argc parameters */
68198 assert( (u.ci.pQuery->flags&MEM_Int)!=0 && u.ci.pArgc->flags==MEM_Int );
68199 u.ci.nArg = (int)u.ci.pArgc->u.i;
68200 u.ci.iQuery = (int)u.ci.pQuery->u.i;
68202 /* Invoke the xFilter method */
68204 u.ci.res = 0;
68205 u.ci.apArg = p->apArg;
68206 for(u.ci.i = 0; u.ci.i<u.ci.nArg; u.ci.i++){
68207 u.ci.apArg[u.ci.i] = &u.ci.pArgc[u.ci.i+1];
68208 sqlite3VdbeMemStoreType(u.ci.apArg[u.ci.i]);
68211 p->inVtabMethod = 1;
68212 rc = u.ci.pModule->xFilter(u.ci.pVtabCursor, u.ci.iQuery, pOp->p4.z, u.ci.nArg, u.ci.apArg);
68213 p->inVtabMethod = 0;
68214 importVtabErrMsg(p, u.ci.pVtab);
68215 if( rc==SQLITE_OK ){
68216 u.ci.res = u.ci.pModule->xEof(u.ci.pVtabCursor);
68219 if( u.ci.res ){
68220 pc = pOp->p2 - 1;
68223 u.ci.pCur->nullRow = 0;
68225 break;
68227 #endif /* SQLITE_OMIT_VIRTUALTABLE */
68229 #ifndef SQLITE_OMIT_VIRTUALTABLE
68230 /* Opcode: VColumn P1 P2 P3 * *
68232 ** Store the value of the P2-th column of
68233 ** the row of the virtual-table that the
68234 ** P1 cursor is pointing to into register P3.
68236 case OP_VColumn: {
68237 #if 0 /* local variables moved into u.cj */
68238 sqlite3_vtab *pVtab;
68239 const sqlite3_module *pModule;
68240 Mem *pDest;
68241 sqlite3_context sContext;
68242 #endif /* local variables moved into u.cj */
68244 VdbeCursor *pCur = p->apCsr[pOp->p1];
68245 assert( pCur->pVtabCursor );
68246 assert( pOp->p3>0 && pOp->p3<=p->nMem );
68247 u.cj.pDest = &aMem[pOp->p3];
68248 memAboutToChange(p, u.cj.pDest);
68249 if( pCur->nullRow ){
68250 sqlite3VdbeMemSetNull(u.cj.pDest);
68251 break;
68253 u.cj.pVtab = pCur->pVtabCursor->pVtab;
68254 u.cj.pModule = u.cj.pVtab->pModule;
68255 assert( u.cj.pModule->xColumn );
68256 memset(&u.cj.sContext, 0, sizeof(u.cj.sContext));
68258 /* The output cell may already have a buffer allocated. Move
68259 ** the current contents to u.cj.sContext.s so in case the user-function
68260 ** can use the already allocated buffer instead of allocating a
68261 ** new one.
68263 sqlite3VdbeMemMove(&u.cj.sContext.s, u.cj.pDest);
68264 MemSetTypeFlag(&u.cj.sContext.s, MEM_Null);
68266 rc = u.cj.pModule->xColumn(pCur->pVtabCursor, &u.cj.sContext, pOp->p2);
68267 importVtabErrMsg(p, u.cj.pVtab);
68268 if( u.cj.sContext.isError ){
68269 rc = u.cj.sContext.isError;
68272 /* Copy the result of the function to the P3 register. We
68273 ** do this regardless of whether or not an error occurred to ensure any
68274 ** dynamic allocation in u.cj.sContext.s (a Mem struct) is released.
68276 sqlite3VdbeChangeEncoding(&u.cj.sContext.s, encoding);
68277 sqlite3VdbeMemMove(u.cj.pDest, &u.cj.sContext.s);
68278 REGISTER_TRACE(pOp->p3, u.cj.pDest);
68279 UPDATE_MAX_BLOBSIZE(u.cj.pDest);
68281 if( sqlite3VdbeMemTooBig(u.cj.pDest) ){
68282 goto too_big;
68284 break;
68286 #endif /* SQLITE_OMIT_VIRTUALTABLE */
68288 #ifndef SQLITE_OMIT_VIRTUALTABLE
68289 /* Opcode: VNext P1 P2 * * *
68291 ** Advance virtual table P1 to the next row in its result set and
68292 ** jump to instruction P2. Or, if the virtual table has reached
68293 ** the end of its result set, then fall through to the next instruction.
68295 case OP_VNext: { /* jump */
68296 #if 0 /* local variables moved into u.ck */
68297 sqlite3_vtab *pVtab;
68298 const sqlite3_module *pModule;
68299 int res;
68300 VdbeCursor *pCur;
68301 #endif /* local variables moved into u.ck */
68303 u.ck.res = 0;
68304 u.ck.pCur = p->apCsr[pOp->p1];
68305 assert( u.ck.pCur->pVtabCursor );
68306 if( u.ck.pCur->nullRow ){
68307 break;
68309 u.ck.pVtab = u.ck.pCur->pVtabCursor->pVtab;
68310 u.ck.pModule = u.ck.pVtab->pModule;
68311 assert( u.ck.pModule->xNext );
68313 /* Invoke the xNext() method of the module. There is no way for the
68314 ** underlying implementation to return an error if one occurs during
68315 ** xNext(). Instead, if an error occurs, true is returned (indicating that
68316 ** data is available) and the error code returned when xColumn or
68317 ** some other method is next invoked on the save virtual table cursor.
68319 p->inVtabMethod = 1;
68320 rc = u.ck.pModule->xNext(u.ck.pCur->pVtabCursor);
68321 p->inVtabMethod = 0;
68322 importVtabErrMsg(p, u.ck.pVtab);
68323 if( rc==SQLITE_OK ){
68324 u.ck.res = u.ck.pModule->xEof(u.ck.pCur->pVtabCursor);
68327 if( !u.ck.res ){
68328 /* If there is data, jump to P2 */
68329 pc = pOp->p2 - 1;
68331 break;
68333 #endif /* SQLITE_OMIT_VIRTUALTABLE */
68335 #ifndef SQLITE_OMIT_VIRTUALTABLE
68336 /* Opcode: VRename P1 * * P4 *
68338 ** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
68339 ** This opcode invokes the corresponding xRename method. The value
68340 ** in register P1 is passed as the zName argument to the xRename method.
68342 case OP_VRename: {
68343 #if 0 /* local variables moved into u.cl */
68344 sqlite3_vtab *pVtab;
68345 Mem *pName;
68346 #endif /* local variables moved into u.cl */
68348 u.cl.pVtab = pOp->p4.pVtab->pVtab;
68349 u.cl.pName = &aMem[pOp->p1];
68350 assert( u.cl.pVtab->pModule->xRename );
68351 assert( memIsValid(u.cl.pName) );
68352 REGISTER_TRACE(pOp->p1, u.cl.pName);
68353 assert( u.cl.pName->flags & MEM_Str );
68354 rc = u.cl.pVtab->pModule->xRename(u.cl.pVtab, u.cl.pName->z);
68355 importVtabErrMsg(p, u.cl.pVtab);
68356 p->expired = 0;
68358 break;
68360 #endif
68362 #ifndef SQLITE_OMIT_VIRTUALTABLE
68363 /* Opcode: VUpdate P1 P2 P3 P4 *
68365 ** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
68366 ** This opcode invokes the corresponding xUpdate method. P2 values
68367 ** are contiguous memory cells starting at P3 to pass to the xUpdate
68368 ** invocation. The value in register (P3+P2-1) corresponds to the
68369 ** p2th element of the argv array passed to xUpdate.
68371 ** The xUpdate method will do a DELETE or an INSERT or both.
68372 ** The argv[0] element (which corresponds to memory cell P3)
68373 ** is the rowid of a row to delete. If argv[0] is NULL then no
68374 ** deletion occurs. The argv[1] element is the rowid of the new
68375 ** row. This can be NULL to have the virtual table select the new
68376 ** rowid for itself. The subsequent elements in the array are
68377 ** the values of columns in the new row.
68379 ** If P2==1 then no insert is performed. argv[0] is the rowid of
68380 ** a row to delete.
68382 ** P1 is a boolean flag. If it is set to true and the xUpdate call
68383 ** is successful, then the value returned by sqlite3_last_insert_rowid()
68384 ** is set to the value of the rowid for the row just inserted.
68386 case OP_VUpdate: {
68387 #if 0 /* local variables moved into u.cm */
68388 sqlite3_vtab *pVtab;
68389 sqlite3_module *pModule;
68390 int nArg;
68391 int i;
68392 sqlite_int64 rowid;
68393 Mem **apArg;
68394 Mem *pX;
68395 #endif /* local variables moved into u.cm */
68397 u.cm.pVtab = pOp->p4.pVtab->pVtab;
68398 u.cm.pModule = (sqlite3_module *)u.cm.pVtab->pModule;
68399 u.cm.nArg = pOp->p2;
68400 assert( pOp->p4type==P4_VTAB );
68401 if( ALWAYS(u.cm.pModule->xUpdate) ){
68402 u.cm.apArg = p->apArg;
68403 u.cm.pX = &aMem[pOp->p3];
68404 for(u.cm.i=0; u.cm.i<u.cm.nArg; u.cm.i++){
68405 assert( memIsValid(u.cm.pX) );
68406 memAboutToChange(p, u.cm.pX);
68407 sqlite3VdbeMemStoreType(u.cm.pX);
68408 u.cm.apArg[u.cm.i] = u.cm.pX;
68409 u.cm.pX++;
68411 rc = u.cm.pModule->xUpdate(u.cm.pVtab, u.cm.nArg, u.cm.apArg, &u.cm.rowid);
68412 importVtabErrMsg(p, u.cm.pVtab);
68413 if( rc==SQLITE_OK && pOp->p1 ){
68414 assert( u.cm.nArg>1 && u.cm.apArg[0] && (u.cm.apArg[0]->flags&MEM_Null) );
68415 db->lastRowid = u.cm.rowid;
68417 p->nChange++;
68419 break;
68421 #endif /* SQLITE_OMIT_VIRTUALTABLE */
68423 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
68424 /* Opcode: Pagecount P1 P2 * * *
68426 ** Write the current number of pages in database P1 to memory cell P2.
68428 case OP_Pagecount: { /* out2-prerelease */
68429 pOut->u.i = sqlite3BtreeLastPage(db->aDb[pOp->p1].pBt);
68430 break;
68432 #endif
68435 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
68436 /* Opcode: MaxPgcnt P1 P2 P3 * *
68438 ** Try to set the maximum page count for database P1 to the value in P3.
68439 ** Do not let the maximum page count fall below the current page count and
68440 ** do not change the maximum page count value if P3==0.
68442 ** Store the maximum page count after the change in register P2.
68444 case OP_MaxPgcnt: { /* out2-prerelease */
68445 unsigned int newMax;
68446 Btree *pBt;
68448 pBt = db->aDb[pOp->p1].pBt;
68449 newMax = 0;
68450 if( pOp->p3 ){
68451 newMax = sqlite3BtreeLastPage(pBt);
68452 if( newMax < (unsigned)pOp->p3 ) newMax = (unsigned)pOp->p3;
68454 pOut->u.i = sqlite3BtreeMaxPageCount(pBt, newMax);
68455 break;
68457 #endif
68460 #ifndef SQLITE_OMIT_TRACE
68461 /* Opcode: Trace * * * P4 *
68463 ** If tracing is enabled (by the sqlite3_trace()) interface, then
68464 ** the UTF-8 string contained in P4 is emitted on the trace callback.
68466 case OP_Trace: {
68467 #if 0 /* local variables moved into u.cn */
68468 char *zTrace;
68469 #endif /* local variables moved into u.cn */
68471 u.cn.zTrace = (pOp->p4.z ? pOp->p4.z : p->zSql);
68472 if( u.cn.zTrace ){
68473 if( db->xTrace ){
68474 char *z = sqlite3VdbeExpandSql(p, u.cn.zTrace);
68475 db->xTrace(db->pTraceArg, z);
68476 sqlite3DbFree(db, z);
68478 #ifdef SQLITE_DEBUG
68479 if( (db->flags & SQLITE_SqlTrace)!=0 ){
68480 sqlite3DebugPrintf("SQL-trace: %s\n", u.cn.zTrace);
68482 #endif /* SQLITE_DEBUG */
68484 break;
68486 #endif
68489 /* Opcode: Noop * * * * *
68491 ** Do nothing. This instruction is often useful as a jump
68492 ** destination.
68495 ** The magic Explain opcode are only inserted when explain==2 (which
68496 ** is to say when the EXPLAIN QUERY PLAN syntax is used.)
68497 ** This opcode records information from the optimizer. It is the
68498 ** the same as a no-op. This opcodesnever appears in a real VM program.
68500 default: { /* This is really OP_Noop and OP_Explain */
68501 assert( pOp->opcode==OP_Noop || pOp->opcode==OP_Explain );
68502 break;
68505 /*****************************************************************************
68506 ** The cases of the switch statement above this line should all be indented
68507 ** by 6 spaces. But the left-most 6 spaces have been removed to improve the
68508 ** readability. From this point on down, the normal indentation rules are
68509 ** restored.
68510 *****************************************************************************/
68513 #ifdef VDBE_PROFILE
68515 u64 elapsed = sqlite3Hwtime() - start;
68516 pOp->cycles += elapsed;
68517 pOp->cnt++;
68518 #if 0
68519 fprintf(stdout, "%10llu ", elapsed);
68520 sqlite3VdbePrintOp(stdout, origPc, &aOp[origPc]);
68521 #endif
68523 #endif
68525 /* The following code adds nothing to the actual functionality
68526 ** of the program. It is only here for testing and debugging.
68527 ** On the other hand, it does burn CPU cycles every time through
68528 ** the evaluator loop. So we can leave it out when NDEBUG is defined.
68530 #ifndef NDEBUG
68531 assert( pc>=-1 && pc<p->nOp );
68533 #ifdef SQLITE_DEBUG
68534 if( p->trace ){
68535 if( rc!=0 ) fprintf(p->trace,"rc=%d\n",rc);
68536 if( pOp->opflags & (OPFLG_OUT2_PRERELEASE|OPFLG_OUT2) ){
68537 registerTrace(p->trace, pOp->p2, &aMem[pOp->p2]);
68539 if( pOp->opflags & OPFLG_OUT3 ){
68540 registerTrace(p->trace, pOp->p3, &aMem[pOp->p3]);
68543 #endif /* SQLITE_DEBUG */
68544 #endif /* NDEBUG */
68545 } /* The end of the for(;;) loop the loops through opcodes */
68547 /* If we reach this point, it means that execution is finished with
68548 ** an error of some kind.
68550 vdbe_error_halt:
68551 assert( rc );
68552 p->rc = rc;
68553 testcase( sqlite3GlobalConfig.xLog!=0 );
68554 sqlite3_log(rc, "statement aborts at %d: [%s] %s",
68555 pc, p->zSql, p->zErrMsg);
68556 sqlite3VdbeHalt(p);
68557 if( rc==SQLITE_IOERR_NOMEM ) db->mallocFailed = 1;
68558 rc = SQLITE_ERROR;
68559 if( resetSchemaOnFault>0 ){
68560 sqlite3ResetInternalSchema(db, resetSchemaOnFault-1);
68563 /* This is the only way out of this procedure. We have to
68564 ** release the mutexes on btrees that were acquired at the
68565 ** top. */
68566 vdbe_return:
68567 sqlite3VdbeLeave(p);
68568 return rc;
68570 /* Jump to here if a string or blob larger than SQLITE_MAX_LENGTH
68571 ** is encountered.
68573 too_big:
68574 sqlite3SetString(&p->zErrMsg, db, "string or blob too big");
68575 rc = SQLITE_TOOBIG;
68576 goto vdbe_error_halt;
68578 /* Jump to here if a malloc() fails.
68580 no_mem:
68581 db->mallocFailed = 1;
68582 sqlite3SetString(&p->zErrMsg, db, "out of memory");
68583 rc = SQLITE_NOMEM;
68584 goto vdbe_error_halt;
68586 /* Jump to here for any other kind of fatal error. The "rc" variable
68587 ** should hold the error number.
68589 abort_due_to_error:
68590 assert( p->zErrMsg==0 );
68591 if( db->mallocFailed ) rc = SQLITE_NOMEM;
68592 if( rc!=SQLITE_IOERR_NOMEM ){
68593 sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3ErrStr(rc));
68595 goto vdbe_error_halt;
68597 /* Jump to here if the sqlite3_interrupt() API sets the interrupt
68598 ** flag.
68600 abort_due_to_interrupt:
68601 assert( db->u1.isInterrupted );
68602 rc = SQLITE_INTERRUPT;
68603 p->rc = rc;
68604 sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3ErrStr(rc));
68605 goto vdbe_error_halt;
68608 /************** End of vdbe.c ************************************************/
68609 /************** Begin file vdbeblob.c ****************************************/
68611 ** 2007 May 1
68613 ** The author disclaims copyright to this source code. In place of
68614 ** a legal notice, here is a blessing:
68616 ** May you do good and not evil.
68617 ** May you find forgiveness for yourself and forgive others.
68618 ** May you share freely, never taking more than you give.
68620 *************************************************************************
68622 ** This file contains code used to implement incremental BLOB I/O.
68626 #ifndef SQLITE_OMIT_INCRBLOB
68629 ** Valid sqlite3_blob* handles point to Incrblob structures.
68631 typedef struct Incrblob Incrblob;
68632 struct Incrblob {
68633 int flags; /* Copy of "flags" passed to sqlite3_blob_open() */
68634 int nByte; /* Size of open blob, in bytes */
68635 int iOffset; /* Byte offset of blob in cursor data */
68636 int iCol; /* Table column this handle is open on */
68637 BtCursor *pCsr; /* Cursor pointing at blob row */
68638 sqlite3_stmt *pStmt; /* Statement holding cursor open */
68639 sqlite3 *db; /* The associated database */
68644 ** This function is used by both blob_open() and blob_reopen(). It seeks
68645 ** the b-tree cursor associated with blob handle p to point to row iRow.
68646 ** If successful, SQLITE_OK is returned and subsequent calls to
68647 ** sqlite3_blob_read() or sqlite3_blob_write() access the specified row.
68649 ** If an error occurs, or if the specified row does not exist or does not
68650 ** contain a value of type TEXT or BLOB in the column nominated when the
68651 ** blob handle was opened, then an error code is returned and *pzErr may
68652 ** be set to point to a buffer containing an error message. It is the
68653 ** responsibility of the caller to free the error message buffer using
68654 ** sqlite3DbFree().
68656 ** If an error does occur, then the b-tree cursor is closed. All subsequent
68657 ** calls to sqlite3_blob_read(), blob_write() or blob_reopen() will
68658 ** immediately return SQLITE_ABORT.
68660 static int blobSeekToRow(Incrblob *p, sqlite3_int64 iRow, char **pzErr){
68661 int rc; /* Error code */
68662 char *zErr = 0; /* Error message */
68663 Vdbe *v = (Vdbe *)p->pStmt;
68665 /* Set the value of the SQL statements only variable to integer iRow.
68666 ** This is done directly instead of using sqlite3_bind_int64() to avoid
68667 ** triggering asserts related to mutexes.
68669 assert( v->aVar[0].flags&MEM_Int );
68670 v->aVar[0].u.i = iRow;
68672 rc = sqlite3_step(p->pStmt);
68673 if( rc==SQLITE_ROW ){
68674 u32 type = v->apCsr[0]->aType[p->iCol];
68675 if( type<12 ){
68676 zErr = sqlite3MPrintf(p->db, "cannot open value of type %s",
68677 type==0?"null": type==7?"real": "integer"
68679 rc = SQLITE_ERROR;
68680 sqlite3_finalize(p->pStmt);
68681 p->pStmt = 0;
68682 }else{
68683 p->iOffset = v->apCsr[0]->aOffset[p->iCol];
68684 p->nByte = sqlite3VdbeSerialTypeLen(type);
68685 p->pCsr = v->apCsr[0]->pCursor;
68686 sqlite3BtreeEnterCursor(p->pCsr);
68687 sqlite3BtreeCacheOverflow(p->pCsr);
68688 sqlite3BtreeLeaveCursor(p->pCsr);
68692 if( rc==SQLITE_ROW ){
68693 rc = SQLITE_OK;
68694 }else if( p->pStmt ){
68695 rc = sqlite3_finalize(p->pStmt);
68696 p->pStmt = 0;
68697 if( rc==SQLITE_OK ){
68698 zErr = sqlite3MPrintf(p->db, "no such rowid: %lld", iRow);
68699 rc = SQLITE_ERROR;
68700 }else{
68701 zErr = sqlite3MPrintf(p->db, "%s", sqlite3_errmsg(p->db));
68705 assert( rc!=SQLITE_OK || zErr==0 );
68706 assert( rc!=SQLITE_ROW && rc!=SQLITE_DONE );
68708 *pzErr = zErr;
68709 return rc;
68713 ** Open a blob handle.
68715 SQLITE_API int sqlite3_blob_open(
68716 sqlite3* db, /* The database connection */
68717 const char *zDb, /* The attached database containing the blob */
68718 const char *zTable, /* The table containing the blob */
68719 const char *zColumn, /* The column containing the blob */
68720 sqlite_int64 iRow, /* The row containing the glob */
68721 int flags, /* True -> read/write access, false -> read-only */
68722 sqlite3_blob **ppBlob /* Handle for accessing the blob returned here */
68724 int nAttempt = 0;
68725 int iCol; /* Index of zColumn in row-record */
68727 /* This VDBE program seeks a btree cursor to the identified
68728 ** db/table/row entry. The reason for using a vdbe program instead
68729 ** of writing code to use the b-tree layer directly is that the
68730 ** vdbe program will take advantage of the various transaction,
68731 ** locking and error handling infrastructure built into the vdbe.
68733 ** After seeking the cursor, the vdbe executes an OP_ResultRow.
68734 ** Code external to the Vdbe then "borrows" the b-tree cursor and
68735 ** uses it to implement the blob_read(), blob_write() and
68736 ** blob_bytes() functions.
68738 ** The sqlite3_blob_close() function finalizes the vdbe program,
68739 ** which closes the b-tree cursor and (possibly) commits the
68740 ** transaction.
68742 static const VdbeOpList openBlob[] = {
68743 {OP_Transaction, 0, 0, 0}, /* 0: Start a transaction */
68744 {OP_VerifyCookie, 0, 0, 0}, /* 1: Check the schema cookie */
68745 {OP_TableLock, 0, 0, 0}, /* 2: Acquire a read or write lock */
68747 /* One of the following two instructions is replaced by an OP_Noop. */
68748 {OP_OpenRead, 0, 0, 0}, /* 3: Open cursor 0 for reading */
68749 {OP_OpenWrite, 0, 0, 0}, /* 4: Open cursor 0 for read/write */
68751 {OP_Variable, 1, 1, 1}, /* 5: Push the rowid to the stack */
68752 {OP_NotExists, 0, 10, 1}, /* 6: Seek the cursor */
68753 {OP_Column, 0, 0, 1}, /* 7 */
68754 {OP_ResultRow, 1, 0, 0}, /* 8 */
68755 {OP_Goto, 0, 5, 0}, /* 9 */
68756 {OP_Close, 0, 0, 0}, /* 10 */
68757 {OP_Halt, 0, 0, 0}, /* 11 */
68760 int rc = SQLITE_OK;
68761 char *zErr = 0;
68762 Table *pTab;
68763 Parse *pParse = 0;
68764 Incrblob *pBlob = 0;
68766 flags = !!flags; /* flags = (flags ? 1 : 0); */
68767 *ppBlob = 0;
68769 sqlite3_mutex_enter(db->mutex);
68771 pBlob = (Incrblob *)sqlite3DbMallocZero(db, sizeof(Incrblob));
68772 if( !pBlob ) goto blob_open_out;
68773 pParse = sqlite3StackAllocRaw(db, sizeof(*pParse));
68774 if( !pParse ) goto blob_open_out;
68776 do {
68777 memset(pParse, 0, sizeof(Parse));
68778 pParse->db = db;
68779 sqlite3DbFree(db, zErr);
68780 zErr = 0;
68782 sqlite3BtreeEnterAll(db);
68783 pTab = sqlite3LocateTable(pParse, 0, zTable, zDb);
68784 if( pTab && IsVirtual(pTab) ){
68785 pTab = 0;
68786 sqlite3ErrorMsg(pParse, "cannot open virtual table: %s", zTable);
68788 #ifndef SQLITE_OMIT_VIEW
68789 if( pTab && pTab->pSelect ){
68790 pTab = 0;
68791 sqlite3ErrorMsg(pParse, "cannot open view: %s", zTable);
68793 #endif
68794 if( !pTab ){
68795 if( pParse->zErrMsg ){
68796 sqlite3DbFree(db, zErr);
68797 zErr = pParse->zErrMsg;
68798 pParse->zErrMsg = 0;
68800 rc = SQLITE_ERROR;
68801 sqlite3BtreeLeaveAll(db);
68802 goto blob_open_out;
68805 /* Now search pTab for the exact column. */
68806 for(iCol=0; iCol<pTab->nCol; iCol++) {
68807 if( sqlite3StrICmp(pTab->aCol[iCol].zName, zColumn)==0 ){
68808 break;
68811 if( iCol==pTab->nCol ){
68812 sqlite3DbFree(db, zErr);
68813 zErr = sqlite3MPrintf(db, "no such column: \"%s\"", zColumn);
68814 rc = SQLITE_ERROR;
68815 sqlite3BtreeLeaveAll(db);
68816 goto blob_open_out;
68819 /* If the value is being opened for writing, check that the
68820 ** column is not indexed, and that it is not part of a foreign key.
68821 ** It is against the rules to open a column to which either of these
68822 ** descriptions applies for writing. */
68823 if( flags ){
68824 const char *zFault = 0;
68825 Index *pIdx;
68826 #ifndef SQLITE_OMIT_FOREIGN_KEY
68827 if( db->flags&SQLITE_ForeignKeys ){
68828 /* Check that the column is not part of an FK child key definition. It
68829 ** is not necessary to check if it is part of a parent key, as parent
68830 ** key columns must be indexed. The check below will pick up this
68831 ** case. */
68832 FKey *pFKey;
68833 for(pFKey=pTab->pFKey; pFKey; pFKey=pFKey->pNextFrom){
68834 int j;
68835 for(j=0; j<pFKey->nCol; j++){
68836 if( pFKey->aCol[j].iFrom==iCol ){
68837 zFault = "foreign key";
68842 #endif
68843 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
68844 int j;
68845 for(j=0; j<pIdx->nColumn; j++){
68846 if( pIdx->aiColumn[j]==iCol ){
68847 zFault = "indexed";
68851 if( zFault ){
68852 sqlite3DbFree(db, zErr);
68853 zErr = sqlite3MPrintf(db, "cannot open %s column for writing", zFault);
68854 rc = SQLITE_ERROR;
68855 sqlite3BtreeLeaveAll(db);
68856 goto blob_open_out;
68860 pBlob->pStmt = (sqlite3_stmt *)sqlite3VdbeCreate(db);
68861 assert( pBlob->pStmt || db->mallocFailed );
68862 if( pBlob->pStmt ){
68863 Vdbe *v = (Vdbe *)pBlob->pStmt;
68864 int iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
68866 sqlite3VdbeAddOpList(v, sizeof(openBlob)/sizeof(VdbeOpList), openBlob);
68869 /* Configure the OP_Transaction */
68870 sqlite3VdbeChangeP1(v, 0, iDb);
68871 sqlite3VdbeChangeP2(v, 0, flags);
68873 /* Configure the OP_VerifyCookie */
68874 sqlite3VdbeChangeP1(v, 1, iDb);
68875 sqlite3VdbeChangeP2(v, 1, pTab->pSchema->schema_cookie);
68876 sqlite3VdbeChangeP3(v, 1, pTab->pSchema->iGeneration);
68878 /* Make sure a mutex is held on the table to be accessed */
68879 sqlite3VdbeUsesBtree(v, iDb);
68881 /* Configure the OP_TableLock instruction */
68882 #ifdef SQLITE_OMIT_SHARED_CACHE
68883 sqlite3VdbeChangeToNoop(v, 2, 1);
68884 #else
68885 sqlite3VdbeChangeP1(v, 2, iDb);
68886 sqlite3VdbeChangeP2(v, 2, pTab->tnum);
68887 sqlite3VdbeChangeP3(v, 2, flags);
68888 sqlite3VdbeChangeP4(v, 2, pTab->zName, P4_TRANSIENT);
68889 #endif
68891 /* Remove either the OP_OpenWrite or OpenRead. Set the P2
68892 ** parameter of the other to pTab->tnum. */
68893 sqlite3VdbeChangeToNoop(v, 4 - flags, 1);
68894 sqlite3VdbeChangeP2(v, 3 + flags, pTab->tnum);
68895 sqlite3VdbeChangeP3(v, 3 + flags, iDb);
68897 /* Configure the number of columns. Configure the cursor to
68898 ** think that the table has one more column than it really
68899 ** does. An OP_Column to retrieve this imaginary column will
68900 ** always return an SQL NULL. This is useful because it means
68901 ** we can invoke OP_Column to fill in the vdbe cursors type
68902 ** and offset cache without causing any IO.
68904 sqlite3VdbeChangeP4(v, 3+flags, SQLITE_INT_TO_PTR(pTab->nCol+1),P4_INT32);
68905 sqlite3VdbeChangeP2(v, 7, pTab->nCol);
68906 if( !db->mallocFailed ){
68907 sqlite3VdbeMakeReady(v, 1, 1, 1, 0, 0, 0);
68911 pBlob->flags = flags;
68912 pBlob->iCol = iCol;
68913 pBlob->db = db;
68914 sqlite3BtreeLeaveAll(db);
68915 if( db->mallocFailed ){
68916 goto blob_open_out;
68918 sqlite3_bind_int64(pBlob->pStmt, 1, iRow);
68919 rc = blobSeekToRow(pBlob, iRow, &zErr);
68920 } while( (++nAttempt)<5 && rc==SQLITE_SCHEMA );
68922 blob_open_out:
68923 if( rc==SQLITE_OK && db->mallocFailed==0 ){
68924 *ppBlob = (sqlite3_blob *)pBlob;
68925 }else{
68926 if( pBlob && pBlob->pStmt ) sqlite3VdbeFinalize((Vdbe *)pBlob->pStmt);
68927 sqlite3DbFree(db, pBlob);
68929 sqlite3Error(db, rc, (zErr ? "%s" : 0), zErr);
68930 sqlite3DbFree(db, zErr);
68931 sqlite3StackFree(db, pParse);
68932 rc = sqlite3ApiExit(db, rc);
68933 sqlite3_mutex_leave(db->mutex);
68934 return rc;
68938 ** Close a blob handle that was previously created using
68939 ** sqlite3_blob_open().
68941 SQLITE_API int sqlite3_blob_close(sqlite3_blob *pBlob){
68942 Incrblob *p = (Incrblob *)pBlob;
68943 int rc;
68944 sqlite3 *db;
68946 if( p ){
68947 db = p->db;
68948 sqlite3_mutex_enter(db->mutex);
68949 rc = sqlite3_finalize(p->pStmt);
68950 sqlite3DbFree(db, p);
68951 sqlite3_mutex_leave(db->mutex);
68952 }else{
68953 rc = SQLITE_OK;
68955 return rc;
68959 ** Perform a read or write operation on a blob
68961 static int blobReadWrite(
68962 sqlite3_blob *pBlob,
68963 void *z,
68964 int n,
68965 int iOffset,
68966 int (*xCall)(BtCursor*, u32, u32, void*)
68968 int rc;
68969 Incrblob *p = (Incrblob *)pBlob;
68970 Vdbe *v;
68971 sqlite3 *db;
68973 if( p==0 ) return SQLITE_MISUSE_BKPT;
68974 db = p->db;
68975 sqlite3_mutex_enter(db->mutex);
68976 v = (Vdbe*)p->pStmt;
68978 if( n<0 || iOffset<0 || (iOffset+n)>p->nByte ){
68979 /* Request is out of range. Return a transient error. */
68980 rc = SQLITE_ERROR;
68981 sqlite3Error(db, SQLITE_ERROR, 0);
68982 }else if( v==0 ){
68983 /* If there is no statement handle, then the blob-handle has
68984 ** already been invalidated. Return SQLITE_ABORT in this case.
68986 rc = SQLITE_ABORT;
68987 }else{
68988 /* Call either BtreeData() or BtreePutData(). If SQLITE_ABORT is
68989 ** returned, clean-up the statement handle.
68991 assert( db == v->db );
68992 sqlite3BtreeEnterCursor(p->pCsr);
68993 rc = xCall(p->pCsr, iOffset+p->iOffset, n, z);
68994 sqlite3BtreeLeaveCursor(p->pCsr);
68995 if( rc==SQLITE_ABORT ){
68996 sqlite3VdbeFinalize(v);
68997 p->pStmt = 0;
68998 }else{
68999 db->errCode = rc;
69000 v->rc = rc;
69003 rc = sqlite3ApiExit(db, rc);
69004 sqlite3_mutex_leave(db->mutex);
69005 return rc;
69009 ** Read data from a blob handle.
69011 SQLITE_API int sqlite3_blob_read(sqlite3_blob *pBlob, void *z, int n, int iOffset){
69012 return blobReadWrite(pBlob, z, n, iOffset, sqlite3BtreeData);
69016 ** Write data to a blob handle.
69018 SQLITE_API int sqlite3_blob_write(sqlite3_blob *pBlob, const void *z, int n, int iOffset){
69019 return blobReadWrite(pBlob, (void *)z, n, iOffset, sqlite3BtreePutData);
69023 ** Query a blob handle for the size of the data.
69025 ** The Incrblob.nByte field is fixed for the lifetime of the Incrblob
69026 ** so no mutex is required for access.
69028 SQLITE_API int sqlite3_blob_bytes(sqlite3_blob *pBlob){
69029 Incrblob *p = (Incrblob *)pBlob;
69030 return (p && p->pStmt) ? p->nByte : 0;
69034 ** Move an existing blob handle to point to a different row of the same
69035 ** database table.
69037 ** If an error occurs, or if the specified row does not exist or does not
69038 ** contain a blob or text value, then an error code is returned and the
69039 ** database handle error code and message set. If this happens, then all
69040 ** subsequent calls to sqlite3_blob_xxx() functions (except blob_close())
69041 ** immediately return SQLITE_ABORT.
69043 SQLITE_API int sqlite3_blob_reopen(sqlite3_blob *pBlob, sqlite3_int64 iRow){
69044 int rc;
69045 Incrblob *p = (Incrblob *)pBlob;
69046 sqlite3 *db;
69048 if( p==0 ) return SQLITE_MISUSE_BKPT;
69049 db = p->db;
69050 sqlite3_mutex_enter(db->mutex);
69052 if( p->pStmt==0 ){
69053 /* If there is no statement handle, then the blob-handle has
69054 ** already been invalidated. Return SQLITE_ABORT in this case.
69056 rc = SQLITE_ABORT;
69057 }else{
69058 char *zErr;
69059 rc = blobSeekToRow(p, iRow, &zErr);
69060 if( rc!=SQLITE_OK ){
69061 sqlite3Error(db, rc, (zErr ? "%s" : 0), zErr);
69062 sqlite3DbFree(db, zErr);
69064 assert( rc!=SQLITE_SCHEMA );
69067 rc = sqlite3ApiExit(db, rc);
69068 assert( rc==SQLITE_OK || p->pStmt==0 );
69069 sqlite3_mutex_leave(db->mutex);
69070 return rc;
69073 #endif /* #ifndef SQLITE_OMIT_INCRBLOB */
69075 /************** End of vdbeblob.c ********************************************/
69076 /************** Begin file journal.c *****************************************/
69078 ** 2007 August 22
69080 ** The author disclaims copyright to this source code. In place of
69081 ** a legal notice, here is a blessing:
69083 ** May you do good and not evil.
69084 ** May you find forgiveness for yourself and forgive others.
69085 ** May you share freely, never taking more than you give.
69087 *************************************************************************
69089 ** This file implements a special kind of sqlite3_file object used
69090 ** by SQLite to create journal files if the atomic-write optimization
69091 ** is enabled.
69093 ** The distinctive characteristic of this sqlite3_file is that the
69094 ** actual on disk file is created lazily. When the file is created,
69095 ** the caller specifies a buffer size for an in-memory buffer to
69096 ** be used to service read() and write() requests. The actual file
69097 ** on disk is not created or populated until either:
69099 ** 1) The in-memory representation grows too large for the allocated
69100 ** buffer, or
69101 ** 2) The sqlite3JournalCreate() function is called.
69103 #ifdef SQLITE_ENABLE_ATOMIC_WRITE
69107 ** A JournalFile object is a subclass of sqlite3_file used by
69108 ** as an open file handle for journal files.
69110 struct JournalFile {
69111 sqlite3_io_methods *pMethod; /* I/O methods on journal files */
69112 int nBuf; /* Size of zBuf[] in bytes */
69113 char *zBuf; /* Space to buffer journal writes */
69114 int iSize; /* Amount of zBuf[] currently used */
69115 int flags; /* xOpen flags */
69116 sqlite3_vfs *pVfs; /* The "real" underlying VFS */
69117 sqlite3_file *pReal; /* The "real" underlying file descriptor */
69118 const char *zJournal; /* Name of the journal file */
69120 typedef struct JournalFile JournalFile;
69123 ** If it does not already exists, create and populate the on-disk file
69124 ** for JournalFile p.
69126 static int createFile(JournalFile *p){
69127 int rc = SQLITE_OK;
69128 if( !p->pReal ){
69129 sqlite3_file *pReal = (sqlite3_file *)&p[1];
69130 rc = sqlite3OsOpen(p->pVfs, p->zJournal, pReal, p->flags, 0);
69131 if( rc==SQLITE_OK ){
69132 p->pReal = pReal;
69133 if( p->iSize>0 ){
69134 assert(p->iSize<=p->nBuf);
69135 rc = sqlite3OsWrite(p->pReal, p->zBuf, p->iSize, 0);
69139 return rc;
69143 ** Close the file.
69145 static int jrnlClose(sqlite3_file *pJfd){
69146 JournalFile *p = (JournalFile *)pJfd;
69147 if( p->pReal ){
69148 sqlite3OsClose(p->pReal);
69150 sqlite3_free(p->zBuf);
69151 return SQLITE_OK;
69155 ** Read data from the file.
69157 static int jrnlRead(
69158 sqlite3_file *pJfd, /* The journal file from which to read */
69159 void *zBuf, /* Put the results here */
69160 int iAmt, /* Number of bytes to read */
69161 sqlite_int64 iOfst /* Begin reading at this offset */
69163 int rc = SQLITE_OK;
69164 JournalFile *p = (JournalFile *)pJfd;
69165 if( p->pReal ){
69166 rc = sqlite3OsRead(p->pReal, zBuf, iAmt, iOfst);
69167 }else if( (iAmt+iOfst)>p->iSize ){
69168 rc = SQLITE_IOERR_SHORT_READ;
69169 }else{
69170 memcpy(zBuf, &p->zBuf[iOfst], iAmt);
69172 return rc;
69176 ** Write data to the file.
69178 static int jrnlWrite(
69179 sqlite3_file *pJfd, /* The journal file into which to write */
69180 const void *zBuf, /* Take data to be written from here */
69181 int iAmt, /* Number of bytes to write */
69182 sqlite_int64 iOfst /* Begin writing at this offset into the file */
69184 int rc = SQLITE_OK;
69185 JournalFile *p = (JournalFile *)pJfd;
69186 if( !p->pReal && (iOfst+iAmt)>p->nBuf ){
69187 rc = createFile(p);
69189 if( rc==SQLITE_OK ){
69190 if( p->pReal ){
69191 rc = sqlite3OsWrite(p->pReal, zBuf, iAmt, iOfst);
69192 }else{
69193 memcpy(&p->zBuf[iOfst], zBuf, iAmt);
69194 if( p->iSize<(iOfst+iAmt) ){
69195 p->iSize = (iOfst+iAmt);
69199 return rc;
69203 ** Truncate the file.
69205 static int jrnlTruncate(sqlite3_file *pJfd, sqlite_int64 size){
69206 int rc = SQLITE_OK;
69207 JournalFile *p = (JournalFile *)pJfd;
69208 if( p->pReal ){
69209 rc = sqlite3OsTruncate(p->pReal, size);
69210 }else if( size<p->iSize ){
69211 p->iSize = size;
69213 return rc;
69217 ** Sync the file.
69219 static int jrnlSync(sqlite3_file *pJfd, int flags){
69220 int rc;
69221 JournalFile *p = (JournalFile *)pJfd;
69222 if( p->pReal ){
69223 rc = sqlite3OsSync(p->pReal, flags);
69224 }else{
69225 rc = SQLITE_OK;
69227 return rc;
69231 ** Query the size of the file in bytes.
69233 static int jrnlFileSize(sqlite3_file *pJfd, sqlite_int64 *pSize){
69234 int rc = SQLITE_OK;
69235 JournalFile *p = (JournalFile *)pJfd;
69236 if( p->pReal ){
69237 rc = sqlite3OsFileSize(p->pReal, pSize);
69238 }else{
69239 *pSize = (sqlite_int64) p->iSize;
69241 return rc;
69245 ** Table of methods for JournalFile sqlite3_file object.
69247 static struct sqlite3_io_methods JournalFileMethods = {
69248 1, /* iVersion */
69249 jrnlClose, /* xClose */
69250 jrnlRead, /* xRead */
69251 jrnlWrite, /* xWrite */
69252 jrnlTruncate, /* xTruncate */
69253 jrnlSync, /* xSync */
69254 jrnlFileSize, /* xFileSize */
69255 0, /* xLock */
69256 0, /* xUnlock */
69257 0, /* xCheckReservedLock */
69258 0, /* xFileControl */
69259 0, /* xSectorSize */
69260 0, /* xDeviceCharacteristics */
69261 0, /* xShmMap */
69262 0, /* xShmLock */
69263 0, /* xShmBarrier */
69264 0 /* xShmUnmap */
69268 ** Open a journal file.
69270 SQLITE_PRIVATE int sqlite3JournalOpen(
69271 sqlite3_vfs *pVfs, /* The VFS to use for actual file I/O */
69272 const char *zName, /* Name of the journal file */
69273 sqlite3_file *pJfd, /* Preallocated, blank file handle */
69274 int flags, /* Opening flags */
69275 int nBuf /* Bytes buffered before opening the file */
69277 JournalFile *p = (JournalFile *)pJfd;
69278 memset(p, 0, sqlite3JournalSize(pVfs));
69279 if( nBuf>0 ){
69280 p->zBuf = sqlite3MallocZero(nBuf);
69281 if( !p->zBuf ){
69282 return SQLITE_NOMEM;
69284 }else{
69285 return sqlite3OsOpen(pVfs, zName, pJfd, flags, 0);
69287 p->pMethod = &JournalFileMethods;
69288 p->nBuf = nBuf;
69289 p->flags = flags;
69290 p->zJournal = zName;
69291 p->pVfs = pVfs;
69292 return SQLITE_OK;
69296 ** If the argument p points to a JournalFile structure, and the underlying
69297 ** file has not yet been created, create it now.
69299 SQLITE_PRIVATE int sqlite3JournalCreate(sqlite3_file *p){
69300 if( p->pMethods!=&JournalFileMethods ){
69301 return SQLITE_OK;
69303 return createFile((JournalFile *)p);
69307 ** Return the number of bytes required to store a JournalFile that uses vfs
69308 ** pVfs to create the underlying on-disk files.
69310 SQLITE_PRIVATE int sqlite3JournalSize(sqlite3_vfs *pVfs){
69311 return (pVfs->szOsFile+sizeof(JournalFile));
69313 #endif
69315 /************** End of journal.c *********************************************/
69316 /************** Begin file memjournal.c **************************************/
69318 ** 2008 October 7
69320 ** The author disclaims copyright to this source code. In place of
69321 ** a legal notice, here is a blessing:
69323 ** May you do good and not evil.
69324 ** May you find forgiveness for yourself and forgive others.
69325 ** May you share freely, never taking more than you give.
69327 *************************************************************************
69329 ** This file contains code use to implement an in-memory rollback journal.
69330 ** The in-memory rollback journal is used to journal transactions for
69331 ** ":memory:" databases and when the journal_mode=MEMORY pragma is used.
69334 /* Forward references to internal structures */
69335 typedef struct MemJournal MemJournal;
69336 typedef struct FilePoint FilePoint;
69337 typedef struct FileChunk FileChunk;
69339 /* Space to hold the rollback journal is allocated in increments of
69340 ** this many bytes.
69342 ** The size chosen is a little less than a power of two. That way,
69343 ** the FileChunk object will have a size that almost exactly fills
69344 ** a power-of-two allocation. This mimimizes wasted space in power-of-two
69345 ** memory allocators.
69347 #define JOURNAL_CHUNKSIZE ((int)(1024-sizeof(FileChunk*)))
69349 /* Macro to find the minimum of two numeric values.
69351 #ifndef MIN
69352 # define MIN(x,y) ((x)<(y)?(x):(y))
69353 #endif
69356 ** The rollback journal is composed of a linked list of these structures.
69358 struct FileChunk {
69359 FileChunk *pNext; /* Next chunk in the journal */
69360 u8 zChunk[JOURNAL_CHUNKSIZE]; /* Content of this chunk */
69364 ** An instance of this object serves as a cursor into the rollback journal.
69365 ** The cursor can be either for reading or writing.
69367 struct FilePoint {
69368 sqlite3_int64 iOffset; /* Offset from the beginning of the file */
69369 FileChunk *pChunk; /* Specific chunk into which cursor points */
69373 ** This subclass is a subclass of sqlite3_file. Each open memory-journal
69374 ** is an instance of this class.
69376 struct MemJournal {
69377 sqlite3_io_methods *pMethod; /* Parent class. MUST BE FIRST */
69378 FileChunk *pFirst; /* Head of in-memory chunk-list */
69379 FilePoint endpoint; /* Pointer to the end of the file */
69380 FilePoint readpoint; /* Pointer to the end of the last xRead() */
69384 ** Read data from the in-memory journal file. This is the implementation
69385 ** of the sqlite3_vfs.xRead method.
69387 static int memjrnlRead(
69388 sqlite3_file *pJfd, /* The journal file from which to read */
69389 void *zBuf, /* Put the results here */
69390 int iAmt, /* Number of bytes to read */
69391 sqlite_int64 iOfst /* Begin reading at this offset */
69393 MemJournal *p = (MemJournal *)pJfd;
69394 u8 *zOut = zBuf;
69395 int nRead = iAmt;
69396 int iChunkOffset;
69397 FileChunk *pChunk;
69399 /* SQLite never tries to read past the end of a rollback journal file */
69400 assert( iOfst+iAmt<=p->endpoint.iOffset );
69402 if( p->readpoint.iOffset!=iOfst || iOfst==0 ){
69403 sqlite3_int64 iOff = 0;
69404 for(pChunk=p->pFirst;
69405 ALWAYS(pChunk) && (iOff+JOURNAL_CHUNKSIZE)<=iOfst;
69406 pChunk=pChunk->pNext
69408 iOff += JOURNAL_CHUNKSIZE;
69410 }else{
69411 pChunk = p->readpoint.pChunk;
69414 iChunkOffset = (int)(iOfst%JOURNAL_CHUNKSIZE);
69415 do {
69416 int iSpace = JOURNAL_CHUNKSIZE - iChunkOffset;
69417 int nCopy = MIN(nRead, (JOURNAL_CHUNKSIZE - iChunkOffset));
69418 memcpy(zOut, &pChunk->zChunk[iChunkOffset], nCopy);
69419 zOut += nCopy;
69420 nRead -= iSpace;
69421 iChunkOffset = 0;
69422 } while( nRead>=0 && (pChunk=pChunk->pNext)!=0 && nRead>0 );
69423 p->readpoint.iOffset = iOfst+iAmt;
69424 p->readpoint.pChunk = pChunk;
69426 return SQLITE_OK;
69430 ** Write data to the file.
69432 static int memjrnlWrite(
69433 sqlite3_file *pJfd, /* The journal file into which to write */
69434 const void *zBuf, /* Take data to be written from here */
69435 int iAmt, /* Number of bytes to write */
69436 sqlite_int64 iOfst /* Begin writing at this offset into the file */
69438 MemJournal *p = (MemJournal *)pJfd;
69439 int nWrite = iAmt;
69440 u8 *zWrite = (u8 *)zBuf;
69442 /* An in-memory journal file should only ever be appended to. Random
69443 ** access writes are not required by sqlite.
69445 assert( iOfst==p->endpoint.iOffset );
69446 UNUSED_PARAMETER(iOfst);
69448 while( nWrite>0 ){
69449 FileChunk *pChunk = p->endpoint.pChunk;
69450 int iChunkOffset = (int)(p->endpoint.iOffset%JOURNAL_CHUNKSIZE);
69451 int iSpace = MIN(nWrite, JOURNAL_CHUNKSIZE - iChunkOffset);
69453 if( iChunkOffset==0 ){
69454 /* New chunk is required to extend the file. */
69455 FileChunk *pNew = sqlite3_malloc(sizeof(FileChunk));
69456 if( !pNew ){
69457 return SQLITE_IOERR_NOMEM;
69459 pNew->pNext = 0;
69460 if( pChunk ){
69461 assert( p->pFirst );
69462 pChunk->pNext = pNew;
69463 }else{
69464 assert( !p->pFirst );
69465 p->pFirst = pNew;
69467 p->endpoint.pChunk = pNew;
69470 memcpy(&p->endpoint.pChunk->zChunk[iChunkOffset], zWrite, iSpace);
69471 zWrite += iSpace;
69472 nWrite -= iSpace;
69473 p->endpoint.iOffset += iSpace;
69476 return SQLITE_OK;
69480 ** Truncate the file.
69482 static int memjrnlTruncate(sqlite3_file *pJfd, sqlite_int64 size){
69483 MemJournal *p = (MemJournal *)pJfd;
69484 FileChunk *pChunk;
69485 assert(size==0);
69486 UNUSED_PARAMETER(size);
69487 pChunk = p->pFirst;
69488 while( pChunk ){
69489 FileChunk *pTmp = pChunk;
69490 pChunk = pChunk->pNext;
69491 sqlite3_free(pTmp);
69493 sqlite3MemJournalOpen(pJfd);
69494 return SQLITE_OK;
69498 ** Close the file.
69500 static int memjrnlClose(sqlite3_file *pJfd){
69501 memjrnlTruncate(pJfd, 0);
69502 return SQLITE_OK;
69507 ** Sync the file.
69509 ** Syncing an in-memory journal is a no-op. And, in fact, this routine
69510 ** is never called in a working implementation. This implementation
69511 ** exists purely as a contingency, in case some malfunction in some other
69512 ** part of SQLite causes Sync to be called by mistake.
69514 static int memjrnlSync(sqlite3_file *NotUsed, int NotUsed2){
69515 UNUSED_PARAMETER2(NotUsed, NotUsed2);
69516 return SQLITE_OK;
69520 ** Query the size of the file in bytes.
69522 static int memjrnlFileSize(sqlite3_file *pJfd, sqlite_int64 *pSize){
69523 MemJournal *p = (MemJournal *)pJfd;
69524 *pSize = (sqlite_int64) p->endpoint.iOffset;
69525 return SQLITE_OK;
69529 ** Table of methods for MemJournal sqlite3_file object.
69531 static const struct sqlite3_io_methods MemJournalMethods = {
69532 1, /* iVersion */
69533 memjrnlClose, /* xClose */
69534 memjrnlRead, /* xRead */
69535 memjrnlWrite, /* xWrite */
69536 memjrnlTruncate, /* xTruncate */
69537 memjrnlSync, /* xSync */
69538 memjrnlFileSize, /* xFileSize */
69539 0, /* xLock */
69540 0, /* xUnlock */
69541 0, /* xCheckReservedLock */
69542 0, /* xFileControl */
69543 0, /* xSectorSize */
69544 0, /* xDeviceCharacteristics */
69545 0, /* xShmMap */
69546 0, /* xShmLock */
69547 0, /* xShmBarrier */
69548 0 /* xShmUnlock */
69552 ** Open a journal file.
69554 SQLITE_PRIVATE void sqlite3MemJournalOpen(sqlite3_file *pJfd){
69555 MemJournal *p = (MemJournal *)pJfd;
69556 assert( EIGHT_BYTE_ALIGNMENT(p) );
69557 memset(p, 0, sqlite3MemJournalSize());
69558 p->pMethod = (sqlite3_io_methods*)&MemJournalMethods;
69562 ** Return true if the file-handle passed as an argument is
69563 ** an in-memory journal
69565 SQLITE_PRIVATE int sqlite3IsMemJournal(sqlite3_file *pJfd){
69566 return pJfd->pMethods==&MemJournalMethods;
69570 ** Return the number of bytes required to store a MemJournal file descriptor.
69572 SQLITE_PRIVATE int sqlite3MemJournalSize(void){
69573 return sizeof(MemJournal);
69576 /************** End of memjournal.c ******************************************/
69577 /************** Begin file walker.c ******************************************/
69579 ** 2008 August 16
69581 ** The author disclaims copyright to this source code. In place of
69582 ** a legal notice, here is a blessing:
69584 ** May you do good and not evil.
69585 ** May you find forgiveness for yourself and forgive others.
69586 ** May you share freely, never taking more than you give.
69588 *************************************************************************
69589 ** This file contains routines used for walking the parser tree for
69590 ** an SQL statement.
69595 ** Walk an expression tree. Invoke the callback once for each node
69596 ** of the expression, while decending. (In other words, the callback
69597 ** is invoked before visiting children.)
69599 ** The return value from the callback should be one of the WRC_*
69600 ** constants to specify how to proceed with the walk.
69602 ** WRC_Continue Continue descending down the tree.
69604 ** WRC_Prune Do not descend into child nodes. But allow
69605 ** the walk to continue with sibling nodes.
69607 ** WRC_Abort Do no more callbacks. Unwind the stack and
69608 ** return the top-level walk call.
69610 ** The return value from this routine is WRC_Abort to abandon the tree walk
69611 ** and WRC_Continue to continue.
69613 SQLITE_PRIVATE int sqlite3WalkExpr(Walker *pWalker, Expr *pExpr){
69614 int rc;
69615 if( pExpr==0 ) return WRC_Continue;
69616 testcase( ExprHasProperty(pExpr, EP_TokenOnly) );
69617 testcase( ExprHasProperty(pExpr, EP_Reduced) );
69618 rc = pWalker->xExprCallback(pWalker, pExpr);
69619 if( rc==WRC_Continue
69620 && !ExprHasAnyProperty(pExpr,EP_TokenOnly) ){
69621 if( sqlite3WalkExpr(pWalker, pExpr->pLeft) ) return WRC_Abort;
69622 if( sqlite3WalkExpr(pWalker, pExpr->pRight) ) return WRC_Abort;
69623 if( ExprHasProperty(pExpr, EP_xIsSelect) ){
69624 if( sqlite3WalkSelect(pWalker, pExpr->x.pSelect) ) return WRC_Abort;
69625 }else{
69626 if( sqlite3WalkExprList(pWalker, pExpr->x.pList) ) return WRC_Abort;
69629 return rc & WRC_Abort;
69633 ** Call sqlite3WalkExpr() for every expression in list p or until
69634 ** an abort request is seen.
69636 SQLITE_PRIVATE int sqlite3WalkExprList(Walker *pWalker, ExprList *p){
69637 int i;
69638 struct ExprList_item *pItem;
69639 if( p ){
69640 for(i=p->nExpr, pItem=p->a; i>0; i--, pItem++){
69641 if( sqlite3WalkExpr(pWalker, pItem->pExpr) ) return WRC_Abort;
69644 return WRC_Continue;
69648 ** Walk all expressions associated with SELECT statement p. Do
69649 ** not invoke the SELECT callback on p, but do (of course) invoke
69650 ** any expr callbacks and SELECT callbacks that come from subqueries.
69651 ** Return WRC_Abort or WRC_Continue.
69653 SQLITE_PRIVATE int sqlite3WalkSelectExpr(Walker *pWalker, Select *p){
69654 if( sqlite3WalkExprList(pWalker, p->pEList) ) return WRC_Abort;
69655 if( sqlite3WalkExpr(pWalker, p->pWhere) ) return WRC_Abort;
69656 if( sqlite3WalkExprList(pWalker, p->pGroupBy) ) return WRC_Abort;
69657 if( sqlite3WalkExpr(pWalker, p->pHaving) ) return WRC_Abort;
69658 if( sqlite3WalkExprList(pWalker, p->pOrderBy) ) return WRC_Abort;
69659 if( sqlite3WalkExpr(pWalker, p->pLimit) ) return WRC_Abort;
69660 if( sqlite3WalkExpr(pWalker, p->pOffset) ) return WRC_Abort;
69661 return WRC_Continue;
69665 ** Walk the parse trees associated with all subqueries in the
69666 ** FROM clause of SELECT statement p. Do not invoke the select
69667 ** callback on p, but do invoke it on each FROM clause subquery
69668 ** and on any subqueries further down in the tree. Return
69669 ** WRC_Abort or WRC_Continue;
69671 SQLITE_PRIVATE int sqlite3WalkSelectFrom(Walker *pWalker, Select *p){
69672 SrcList *pSrc;
69673 int i;
69674 struct SrcList_item *pItem;
69676 pSrc = p->pSrc;
69677 if( ALWAYS(pSrc) ){
69678 for(i=pSrc->nSrc, pItem=pSrc->a; i>0; i--, pItem++){
69679 if( sqlite3WalkSelect(pWalker, pItem->pSelect) ){
69680 return WRC_Abort;
69684 return WRC_Continue;
69688 ** Call sqlite3WalkExpr() for every expression in Select statement p.
69689 ** Invoke sqlite3WalkSelect() for subqueries in the FROM clause and
69690 ** on the compound select chain, p->pPrior.
69692 ** Return WRC_Continue under normal conditions. Return WRC_Abort if
69693 ** there is an abort request.
69695 ** If the Walker does not have an xSelectCallback() then this routine
69696 ** is a no-op returning WRC_Continue.
69698 SQLITE_PRIVATE int sqlite3WalkSelect(Walker *pWalker, Select *p){
69699 int rc;
69700 if( p==0 || pWalker->xSelectCallback==0 ) return WRC_Continue;
69701 rc = WRC_Continue;
69702 while( p ){
69703 rc = pWalker->xSelectCallback(pWalker, p);
69704 if( rc ) break;
69705 if( sqlite3WalkSelectExpr(pWalker, p) ) return WRC_Abort;
69706 if( sqlite3WalkSelectFrom(pWalker, p) ) return WRC_Abort;
69707 p = p->pPrior;
69709 return rc & WRC_Abort;
69712 /************** End of walker.c **********************************************/
69713 /************** Begin file resolve.c *****************************************/
69715 ** 2008 August 18
69717 ** The author disclaims copyright to this source code. In place of
69718 ** a legal notice, here is a blessing:
69720 ** May you do good and not evil.
69721 ** May you find forgiveness for yourself and forgive others.
69722 ** May you share freely, never taking more than you give.
69724 *************************************************************************
69726 ** This file contains routines used for walking the parser tree and
69727 ** resolve all identifiers by associating them with a particular
69728 ** table and column.
69732 ** Turn the pExpr expression into an alias for the iCol-th column of the
69733 ** result set in pEList.
69735 ** If the result set column is a simple column reference, then this routine
69736 ** makes an exact copy. But for any other kind of expression, this
69737 ** routine make a copy of the result set column as the argument to the
69738 ** TK_AS operator. The TK_AS operator causes the expression to be
69739 ** evaluated just once and then reused for each alias.
69741 ** The reason for suppressing the TK_AS term when the expression is a simple
69742 ** column reference is so that the column reference will be recognized as
69743 ** usable by indices within the WHERE clause processing logic.
69745 ** Hack: The TK_AS operator is inhibited if zType[0]=='G'. This means
69746 ** that in a GROUP BY clause, the expression is evaluated twice. Hence:
69748 ** SELECT random()%5 AS x, count(*) FROM tab GROUP BY x
69750 ** Is equivalent to:
69752 ** SELECT random()%5 AS x, count(*) FROM tab GROUP BY random()%5
69754 ** The result of random()%5 in the GROUP BY clause is probably different
69755 ** from the result in the result-set. We might fix this someday. Or
69756 ** then again, we might not...
69758 static void resolveAlias(
69759 Parse *pParse, /* Parsing context */
69760 ExprList *pEList, /* A result set */
69761 int iCol, /* A column in the result set. 0..pEList->nExpr-1 */
69762 Expr *pExpr, /* Transform this into an alias to the result set */
69763 const char *zType /* "GROUP" or "ORDER" or "" */
69765 Expr *pOrig; /* The iCol-th column of the result set */
69766 Expr *pDup; /* Copy of pOrig */
69767 sqlite3 *db; /* The database connection */
69769 assert( iCol>=0 && iCol<pEList->nExpr );
69770 pOrig = pEList->a[iCol].pExpr;
69771 assert( pOrig!=0 );
69772 assert( pOrig->flags & EP_Resolved );
69773 db = pParse->db;
69774 if( pOrig->op!=TK_COLUMN && zType[0]!='G' ){
69775 pDup = sqlite3ExprDup(db, pOrig, 0);
69776 pDup = sqlite3PExpr(pParse, TK_AS, pDup, 0, 0);
69777 if( pDup==0 ) return;
69778 if( pEList->a[iCol].iAlias==0 ){
69779 pEList->a[iCol].iAlias = (u16)(++pParse->nAlias);
69781 pDup->iTable = pEList->a[iCol].iAlias;
69782 }else if( ExprHasProperty(pOrig, EP_IntValue) || pOrig->u.zToken==0 ){
69783 pDup = sqlite3ExprDup(db, pOrig, 0);
69784 if( pDup==0 ) return;
69785 }else{
69786 char *zToken = pOrig->u.zToken;
69787 assert( zToken!=0 );
69788 pOrig->u.zToken = 0;
69789 pDup = sqlite3ExprDup(db, pOrig, 0);
69790 pOrig->u.zToken = zToken;
69791 if( pDup==0 ) return;
69792 assert( (pDup->flags & (EP_Reduced|EP_TokenOnly))==0 );
69793 pDup->flags2 |= EP2_MallocedToken;
69794 pDup->u.zToken = sqlite3DbStrDup(db, zToken);
69796 if( pExpr->flags & EP_ExpCollate ){
69797 pDup->pColl = pExpr->pColl;
69798 pDup->flags |= EP_ExpCollate;
69801 /* Before calling sqlite3ExprDelete(), set the EP_Static flag. This
69802 ** prevents ExprDelete() from deleting the Expr structure itself,
69803 ** allowing it to be repopulated by the memcpy() on the following line.
69805 ExprSetProperty(pExpr, EP_Static);
69806 sqlite3ExprDelete(db, pExpr);
69807 memcpy(pExpr, pDup, sizeof(*pExpr));
69808 sqlite3DbFree(db, pDup);
69812 ** Given the name of a column of the form X.Y.Z or Y.Z or just Z, look up
69813 ** that name in the set of source tables in pSrcList and make the pExpr
69814 ** expression node refer back to that source column. The following changes
69815 ** are made to pExpr:
69817 ** pExpr->iDb Set the index in db->aDb[] of the database X
69818 ** (even if X is implied).
69819 ** pExpr->iTable Set to the cursor number for the table obtained
69820 ** from pSrcList.
69821 ** pExpr->pTab Points to the Table structure of X.Y (even if
69822 ** X and/or Y are implied.)
69823 ** pExpr->iColumn Set to the column number within the table.
69824 ** pExpr->op Set to TK_COLUMN.
69825 ** pExpr->pLeft Any expression this points to is deleted
69826 ** pExpr->pRight Any expression this points to is deleted.
69828 ** The zDb variable is the name of the database (the "X"). This value may be
69829 ** NULL meaning that name is of the form Y.Z or Z. Any available database
69830 ** can be used. The zTable variable is the name of the table (the "Y"). This
69831 ** value can be NULL if zDb is also NULL. If zTable is NULL it
69832 ** means that the form of the name is Z and that columns from any table
69833 ** can be used.
69835 ** If the name cannot be resolved unambiguously, leave an error message
69836 ** in pParse and return WRC_Abort. Return WRC_Prune on success.
69838 static int lookupName(
69839 Parse *pParse, /* The parsing context */
69840 const char *zDb, /* Name of the database containing table, or NULL */
69841 const char *zTab, /* Name of table containing column, or NULL */
69842 const char *zCol, /* Name of the column. */
69843 NameContext *pNC, /* The name context used to resolve the name */
69844 Expr *pExpr /* Make this EXPR node point to the selected column */
69846 int i, j; /* Loop counters */
69847 int cnt = 0; /* Number of matching column names */
69848 int cntTab = 0; /* Number of matching table names */
69849 sqlite3 *db = pParse->db; /* The database connection */
69850 struct SrcList_item *pItem; /* Use for looping over pSrcList items */
69851 struct SrcList_item *pMatch = 0; /* The matching pSrcList item */
69852 NameContext *pTopNC = pNC; /* First namecontext in the list */
69853 Schema *pSchema = 0; /* Schema of the expression */
69854 int isTrigger = 0;
69856 assert( pNC ); /* the name context cannot be NULL. */
69857 assert( zCol ); /* The Z in X.Y.Z cannot be NULL */
69858 assert( ~ExprHasAnyProperty(pExpr, EP_TokenOnly|EP_Reduced) );
69860 /* Initialize the node to no-match */
69861 pExpr->iTable = -1;
69862 pExpr->pTab = 0;
69863 ExprSetIrreducible(pExpr);
69865 /* Start at the inner-most context and move outward until a match is found */
69866 while( pNC && cnt==0 ){
69867 ExprList *pEList;
69868 SrcList *pSrcList = pNC->pSrcList;
69870 if( pSrcList ){
69871 for(i=0, pItem=pSrcList->a; i<pSrcList->nSrc; i++, pItem++){
69872 Table *pTab;
69873 int iDb;
69874 Column *pCol;
69876 pTab = pItem->pTab;
69877 assert( pTab!=0 && pTab->zName!=0 );
69878 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
69879 assert( pTab->nCol>0 );
69880 if( zTab ){
69881 if( pItem->zAlias ){
69882 char *zTabName = pItem->zAlias;
69883 if( sqlite3StrICmp(zTabName, zTab)!=0 ) continue;
69884 }else{
69885 char *zTabName = pTab->zName;
69886 if( NEVER(zTabName==0) || sqlite3StrICmp(zTabName, zTab)!=0 ){
69887 continue;
69889 if( zDb!=0 && sqlite3StrICmp(db->aDb[iDb].zName, zDb)!=0 ){
69890 continue;
69894 if( 0==(cntTab++) ){
69895 pExpr->iTable = pItem->iCursor;
69896 pExpr->pTab = pTab;
69897 pSchema = pTab->pSchema;
69898 pMatch = pItem;
69900 for(j=0, pCol=pTab->aCol; j<pTab->nCol; j++, pCol++){
69901 if( sqlite3StrICmp(pCol->zName, zCol)==0 ){
69902 IdList *pUsing;
69903 cnt++;
69904 pExpr->iTable = pItem->iCursor;
69905 pExpr->pTab = pTab;
69906 pMatch = pItem;
69907 pSchema = pTab->pSchema;
69908 /* Substitute the rowid (column -1) for the INTEGER PRIMARY KEY */
69909 pExpr->iColumn = j==pTab->iPKey ? -1 : (i16)j;
69910 if( i<pSrcList->nSrc-1 ){
69911 if( pItem[1].jointype & JT_NATURAL ){
69912 /* If this match occurred in the left table of a natural join,
69913 ** then skip the right table to avoid a duplicate match */
69914 pItem++;
69915 i++;
69916 }else if( (pUsing = pItem[1].pUsing)!=0 ){
69917 /* If this match occurs on a column that is in the USING clause
69918 ** of a join, skip the search of the right table of the join
69919 ** to avoid a duplicate match there. */
69920 int k;
69921 for(k=0; k<pUsing->nId; k++){
69922 if( sqlite3StrICmp(pUsing->a[k].zName, zCol)==0 ){
69923 pItem++;
69924 i++;
69925 break;
69930 break;
69936 #ifndef SQLITE_OMIT_TRIGGER
69937 /* If we have not already resolved the name, then maybe
69938 ** it is a new.* or old.* trigger argument reference
69940 if( zDb==0 && zTab!=0 && cnt==0 && pParse->pTriggerTab!=0 ){
69941 int op = pParse->eTriggerOp;
69942 Table *pTab = 0;
69943 assert( op==TK_DELETE || op==TK_UPDATE || op==TK_INSERT );
69944 if( op!=TK_DELETE && sqlite3StrICmp("new",zTab) == 0 ){
69945 pExpr->iTable = 1;
69946 pTab = pParse->pTriggerTab;
69947 }else if( op!=TK_INSERT && sqlite3StrICmp("old",zTab)==0 ){
69948 pExpr->iTable = 0;
69949 pTab = pParse->pTriggerTab;
69952 if( pTab ){
69953 int iCol;
69954 pSchema = pTab->pSchema;
69955 cntTab++;
69956 for(iCol=0; iCol<pTab->nCol; iCol++){
69957 Column *pCol = &pTab->aCol[iCol];
69958 if( sqlite3StrICmp(pCol->zName, zCol)==0 ){
69959 if( iCol==pTab->iPKey ){
69960 iCol = -1;
69962 break;
69965 if( iCol>=pTab->nCol && sqlite3IsRowid(zCol) ){
69966 iCol = -1; /* IMP: R-44911-55124 */
69968 if( iCol<pTab->nCol ){
69969 cnt++;
69970 if( iCol<0 ){
69971 pExpr->affinity = SQLITE_AFF_INTEGER;
69972 }else if( pExpr->iTable==0 ){
69973 testcase( iCol==31 );
69974 testcase( iCol==32 );
69975 pParse->oldmask |= (iCol>=32 ? 0xffffffff : (((u32)1)<<iCol));
69976 }else{
69977 testcase( iCol==31 );
69978 testcase( iCol==32 );
69979 pParse->newmask |= (iCol>=32 ? 0xffffffff : (((u32)1)<<iCol));
69981 pExpr->iColumn = (i16)iCol;
69982 pExpr->pTab = pTab;
69983 isTrigger = 1;
69987 #endif /* !defined(SQLITE_OMIT_TRIGGER) */
69990 ** Perhaps the name is a reference to the ROWID
69992 if( cnt==0 && cntTab==1 && sqlite3IsRowid(zCol) ){
69993 cnt = 1;
69994 pExpr->iColumn = -1; /* IMP: R-44911-55124 */
69995 pExpr->affinity = SQLITE_AFF_INTEGER;
69999 ** If the input is of the form Z (not Y.Z or X.Y.Z) then the name Z
70000 ** might refer to an result-set alias. This happens, for example, when
70001 ** we are resolving names in the WHERE clause of the following command:
70003 ** SELECT a+b AS x FROM table WHERE x<10;
70005 ** In cases like this, replace pExpr with a copy of the expression that
70006 ** forms the result set entry ("a+b" in the example) and return immediately.
70007 ** Note that the expression in the result set should have already been
70008 ** resolved by the time the WHERE clause is resolved.
70010 if( cnt==0 && (pEList = pNC->pEList)!=0 && zTab==0 ){
70011 for(j=0; j<pEList->nExpr; j++){
70012 char *zAs = pEList->a[j].zName;
70013 if( zAs!=0 && sqlite3StrICmp(zAs, zCol)==0 ){
70014 Expr *pOrig;
70015 assert( pExpr->pLeft==0 && pExpr->pRight==0 );
70016 assert( pExpr->x.pList==0 );
70017 assert( pExpr->x.pSelect==0 );
70018 pOrig = pEList->a[j].pExpr;
70019 if( !pNC->allowAgg && ExprHasProperty(pOrig, EP_Agg) ){
70020 sqlite3ErrorMsg(pParse, "misuse of aliased aggregate %s", zAs);
70021 return WRC_Abort;
70023 resolveAlias(pParse, pEList, j, pExpr, "");
70024 cnt = 1;
70025 pMatch = 0;
70026 assert( zTab==0 && zDb==0 );
70027 goto lookupname_end;
70032 /* Advance to the next name context. The loop will exit when either
70033 ** we have a match (cnt>0) or when we run out of name contexts.
70035 if( cnt==0 ){
70036 pNC = pNC->pNext;
70041 ** If X and Y are NULL (in other words if only the column name Z is
70042 ** supplied) and the value of Z is enclosed in double-quotes, then
70043 ** Z is a string literal if it doesn't match any column names. In that
70044 ** case, we need to return right away and not make any changes to
70045 ** pExpr.
70047 ** Because no reference was made to outer contexts, the pNC->nRef
70048 ** fields are not changed in any context.
70050 if( cnt==0 && zTab==0 && ExprHasProperty(pExpr,EP_DblQuoted) ){
70051 pExpr->op = TK_STRING;
70052 pExpr->pTab = 0;
70053 return WRC_Prune;
70057 ** cnt==0 means there was not match. cnt>1 means there were two or
70058 ** more matches. Either way, we have an error.
70060 if( cnt!=1 ){
70061 const char *zErr;
70062 zErr = cnt==0 ? "no such column" : "ambiguous column name";
70063 if( zDb ){
70064 sqlite3ErrorMsg(pParse, "%s: %s.%s.%s", zErr, zDb, zTab, zCol);
70065 }else if( zTab ){
70066 sqlite3ErrorMsg(pParse, "%s: %s.%s", zErr, zTab, zCol);
70067 }else{
70068 sqlite3ErrorMsg(pParse, "%s: %s", zErr, zCol);
70070 pParse->checkSchema = 1;
70071 pTopNC->nErr++;
70074 /* If a column from a table in pSrcList is referenced, then record
70075 ** this fact in the pSrcList.a[].colUsed bitmask. Column 0 causes
70076 ** bit 0 to be set. Column 1 sets bit 1. And so forth. If the
70077 ** column number is greater than the number of bits in the bitmask
70078 ** then set the high-order bit of the bitmask.
70080 if( pExpr->iColumn>=0 && pMatch!=0 ){
70081 int n = pExpr->iColumn;
70082 testcase( n==BMS-1 );
70083 if( n>=BMS ){
70084 n = BMS-1;
70086 assert( pMatch->iCursor==pExpr->iTable );
70087 pMatch->colUsed |= ((Bitmask)1)<<n;
70090 /* Clean up and return
70092 sqlite3ExprDelete(db, pExpr->pLeft);
70093 pExpr->pLeft = 0;
70094 sqlite3ExprDelete(db, pExpr->pRight);
70095 pExpr->pRight = 0;
70096 pExpr->op = (isTrigger ? TK_TRIGGER : TK_COLUMN);
70097 lookupname_end:
70098 if( cnt==1 ){
70099 assert( pNC!=0 );
70100 sqlite3AuthRead(pParse, pExpr, pSchema, pNC->pSrcList);
70101 /* Increment the nRef value on all name contexts from TopNC up to
70102 ** the point where the name matched. */
70103 for(;;){
70104 assert( pTopNC!=0 );
70105 pTopNC->nRef++;
70106 if( pTopNC==pNC ) break;
70107 pTopNC = pTopNC->pNext;
70109 return WRC_Prune;
70110 } else {
70111 return WRC_Abort;
70116 ** Allocate and return a pointer to an expression to load the column iCol
70117 ** from datasource iSrc in SrcList pSrc.
70119 SQLITE_PRIVATE Expr *sqlite3CreateColumnExpr(sqlite3 *db, SrcList *pSrc, int iSrc, int iCol){
70120 Expr *p = sqlite3ExprAlloc(db, TK_COLUMN, 0, 0);
70121 if( p ){
70122 struct SrcList_item *pItem = &pSrc->a[iSrc];
70123 p->pTab = pItem->pTab;
70124 p->iTable = pItem->iCursor;
70125 if( p->pTab->iPKey==iCol ){
70126 p->iColumn = -1;
70127 }else{
70128 p->iColumn = (ynVar)iCol;
70129 testcase( iCol==BMS );
70130 testcase( iCol==BMS-1 );
70131 pItem->colUsed |= ((Bitmask)1)<<(iCol>=BMS ? BMS-1 : iCol);
70133 ExprSetProperty(p, EP_Resolved);
70135 return p;
70139 ** This routine is callback for sqlite3WalkExpr().
70141 ** Resolve symbolic names into TK_COLUMN operators for the current
70142 ** node in the expression tree. Return 0 to continue the search down
70143 ** the tree or 2 to abort the tree walk.
70145 ** This routine also does error checking and name resolution for
70146 ** function names. The operator for aggregate functions is changed
70147 ** to TK_AGG_FUNCTION.
70149 static int resolveExprStep(Walker *pWalker, Expr *pExpr){
70150 NameContext *pNC;
70151 Parse *pParse;
70153 pNC = pWalker->u.pNC;
70154 assert( pNC!=0 );
70155 pParse = pNC->pParse;
70156 assert( pParse==pWalker->pParse );
70158 if( ExprHasAnyProperty(pExpr, EP_Resolved) ) return WRC_Prune;
70159 ExprSetProperty(pExpr, EP_Resolved);
70160 #ifndef NDEBUG
70161 if( pNC->pSrcList && pNC->pSrcList->nAlloc>0 ){
70162 SrcList *pSrcList = pNC->pSrcList;
70163 int i;
70164 for(i=0; i<pNC->pSrcList->nSrc; i++){
70165 assert( pSrcList->a[i].iCursor>=0 && pSrcList->a[i].iCursor<pParse->nTab);
70168 #endif
70169 switch( pExpr->op ){
70171 #if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY)
70172 /* The special operator TK_ROW means use the rowid for the first
70173 ** column in the FROM clause. This is used by the LIMIT and ORDER BY
70174 ** clause processing on UPDATE and DELETE statements.
70176 case TK_ROW: {
70177 SrcList *pSrcList = pNC->pSrcList;
70178 struct SrcList_item *pItem;
70179 assert( pSrcList && pSrcList->nSrc==1 );
70180 pItem = pSrcList->a;
70181 pExpr->op = TK_COLUMN;
70182 pExpr->pTab = pItem->pTab;
70183 pExpr->iTable = pItem->iCursor;
70184 pExpr->iColumn = -1;
70185 pExpr->affinity = SQLITE_AFF_INTEGER;
70186 break;
70188 #endif /* defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY) */
70190 /* A lone identifier is the name of a column.
70192 case TK_ID: {
70193 return lookupName(pParse, 0, 0, pExpr->u.zToken, pNC, pExpr);
70196 /* A table name and column name: ID.ID
70197 ** Or a database, table and column: ID.ID.ID
70199 case TK_DOT: {
70200 const char *zColumn;
70201 const char *zTable;
70202 const char *zDb;
70203 Expr *pRight;
70205 /* if( pSrcList==0 ) break; */
70206 pRight = pExpr->pRight;
70207 if( pRight->op==TK_ID ){
70208 zDb = 0;
70209 zTable = pExpr->pLeft->u.zToken;
70210 zColumn = pRight->u.zToken;
70211 }else{
70212 assert( pRight->op==TK_DOT );
70213 zDb = pExpr->pLeft->u.zToken;
70214 zTable = pRight->pLeft->u.zToken;
70215 zColumn = pRight->pRight->u.zToken;
70217 return lookupName(pParse, zDb, zTable, zColumn, pNC, pExpr);
70220 /* Resolve function names
70222 case TK_CONST_FUNC:
70223 case TK_FUNCTION: {
70224 ExprList *pList = pExpr->x.pList; /* The argument list */
70225 int n = pList ? pList->nExpr : 0; /* Number of arguments */
70226 int no_such_func = 0; /* True if no such function exists */
70227 int wrong_num_args = 0; /* True if wrong number of arguments */
70228 int is_agg = 0; /* True if is an aggregate function */
70229 int auth; /* Authorization to use the function */
70230 int nId; /* Number of characters in function name */
70231 const char *zId; /* The function name. */
70232 FuncDef *pDef; /* Information about the function */
70233 u8 enc = ENC(pParse->db); /* The database encoding */
70235 testcase( pExpr->op==TK_CONST_FUNC );
70236 assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
70237 zId = pExpr->u.zToken;
70238 nId = sqlite3Strlen30(zId);
70239 pDef = sqlite3FindFunction(pParse->db, zId, nId, n, enc, 0);
70240 if( pDef==0 ){
70241 pDef = sqlite3FindFunction(pParse->db, zId, nId, -1, enc, 0);
70242 if( pDef==0 ){
70243 no_such_func = 1;
70244 }else{
70245 wrong_num_args = 1;
70247 }else{
70248 is_agg = pDef->xFunc==0;
70250 #ifndef SQLITE_OMIT_AUTHORIZATION
70251 if( pDef ){
70252 auth = sqlite3AuthCheck(pParse, SQLITE_FUNCTION, 0, pDef->zName, 0);
70253 if( auth!=SQLITE_OK ){
70254 if( auth==SQLITE_DENY ){
70255 sqlite3ErrorMsg(pParse, "not authorized to use function: %s",
70256 pDef->zName);
70257 pNC->nErr++;
70259 pExpr->op = TK_NULL;
70260 return WRC_Prune;
70263 #endif
70264 if( is_agg && !pNC->allowAgg ){
70265 sqlite3ErrorMsg(pParse, "misuse of aggregate function %.*s()", nId,zId);
70266 pNC->nErr++;
70267 is_agg = 0;
70268 }else if( no_such_func ){
70269 sqlite3ErrorMsg(pParse, "no such function: %.*s", nId, zId);
70270 pNC->nErr++;
70271 }else if( wrong_num_args ){
70272 sqlite3ErrorMsg(pParse,"wrong number of arguments to function %.*s()",
70273 nId, zId);
70274 pNC->nErr++;
70276 if( is_agg ){
70277 pExpr->op = TK_AGG_FUNCTION;
70278 pNC->hasAgg = 1;
70280 if( is_agg ) pNC->allowAgg = 0;
70281 sqlite3WalkExprList(pWalker, pList);
70282 if( is_agg ) pNC->allowAgg = 1;
70283 /* FIX ME: Compute pExpr->affinity based on the expected return
70284 ** type of the function
70286 return WRC_Prune;
70288 #ifndef SQLITE_OMIT_SUBQUERY
70289 case TK_SELECT:
70290 case TK_EXISTS: testcase( pExpr->op==TK_EXISTS );
70291 #endif
70292 case TK_IN: {
70293 testcase( pExpr->op==TK_IN );
70294 if( ExprHasProperty(pExpr, EP_xIsSelect) ){
70295 int nRef = pNC->nRef;
70296 #ifndef SQLITE_OMIT_CHECK
70297 if( pNC->isCheck ){
70298 sqlite3ErrorMsg(pParse,"subqueries prohibited in CHECK constraints");
70300 #endif
70301 sqlite3WalkSelect(pWalker, pExpr->x.pSelect);
70302 assert( pNC->nRef>=nRef );
70303 if( nRef!=pNC->nRef ){
70304 ExprSetProperty(pExpr, EP_VarSelect);
70307 break;
70309 #ifndef SQLITE_OMIT_CHECK
70310 case TK_VARIABLE: {
70311 if( pNC->isCheck ){
70312 sqlite3ErrorMsg(pParse,"parameters prohibited in CHECK constraints");
70314 break;
70316 #endif
70318 return (pParse->nErr || pParse->db->mallocFailed) ? WRC_Abort : WRC_Continue;
70322 ** pEList is a list of expressions which are really the result set of the
70323 ** a SELECT statement. pE is a term in an ORDER BY or GROUP BY clause.
70324 ** This routine checks to see if pE is a simple identifier which corresponds
70325 ** to the AS-name of one of the terms of the expression list. If it is,
70326 ** this routine return an integer between 1 and N where N is the number of
70327 ** elements in pEList, corresponding to the matching entry. If there is
70328 ** no match, or if pE is not a simple identifier, then this routine
70329 ** return 0.
70331 ** pEList has been resolved. pE has not.
70333 static int resolveAsName(
70334 Parse *pParse, /* Parsing context for error messages */
70335 ExprList *pEList, /* List of expressions to scan */
70336 Expr *pE /* Expression we are trying to match */
70338 int i; /* Loop counter */
70340 UNUSED_PARAMETER(pParse);
70342 if( pE->op==TK_ID ){
70343 char *zCol = pE->u.zToken;
70344 for(i=0; i<pEList->nExpr; i++){
70345 char *zAs = pEList->a[i].zName;
70346 if( zAs!=0 && sqlite3StrICmp(zAs, zCol)==0 ){
70347 return i+1;
70351 return 0;
70355 ** pE is a pointer to an expression which is a single term in the
70356 ** ORDER BY of a compound SELECT. The expression has not been
70357 ** name resolved.
70359 ** At the point this routine is called, we already know that the
70360 ** ORDER BY term is not an integer index into the result set. That
70361 ** case is handled by the calling routine.
70363 ** Attempt to match pE against result set columns in the left-most
70364 ** SELECT statement. Return the index i of the matching column,
70365 ** as an indication to the caller that it should sort by the i-th column.
70366 ** The left-most column is 1. In other words, the value returned is the
70367 ** same integer value that would be used in the SQL statement to indicate
70368 ** the column.
70370 ** If there is no match, return 0. Return -1 if an error occurs.
70372 static int resolveOrderByTermToExprList(
70373 Parse *pParse, /* Parsing context for error messages */
70374 Select *pSelect, /* The SELECT statement with the ORDER BY clause */
70375 Expr *pE /* The specific ORDER BY term */
70377 int i; /* Loop counter */
70378 ExprList *pEList; /* The columns of the result set */
70379 NameContext nc; /* Name context for resolving pE */
70380 sqlite3 *db; /* Database connection */
70381 int rc; /* Return code from subprocedures */
70382 u8 savedSuppErr; /* Saved value of db->suppressErr */
70384 assert( sqlite3ExprIsInteger(pE, &i)==0 );
70385 pEList = pSelect->pEList;
70387 /* Resolve all names in the ORDER BY term expression
70389 memset(&nc, 0, sizeof(nc));
70390 nc.pParse = pParse;
70391 nc.pSrcList = pSelect->pSrc;
70392 nc.pEList = pEList;
70393 nc.allowAgg = 1;
70394 nc.nErr = 0;
70395 db = pParse->db;
70396 savedSuppErr = db->suppressErr;
70397 db->suppressErr = 1;
70398 rc = sqlite3ResolveExprNames(&nc, pE);
70399 db->suppressErr = savedSuppErr;
70400 if( rc ) return 0;
70402 /* Try to match the ORDER BY expression against an expression
70403 ** in the result set. Return an 1-based index of the matching
70404 ** result-set entry.
70406 for(i=0; i<pEList->nExpr; i++){
70407 if( sqlite3ExprCompare(pEList->a[i].pExpr, pE)<2 ){
70408 return i+1;
70412 /* If no match, return 0. */
70413 return 0;
70417 ** Generate an ORDER BY or GROUP BY term out-of-range error.
70419 static void resolveOutOfRangeError(
70420 Parse *pParse, /* The error context into which to write the error */
70421 const char *zType, /* "ORDER" or "GROUP" */
70422 int i, /* The index (1-based) of the term out of range */
70423 int mx /* Largest permissible value of i */
70425 sqlite3ErrorMsg(pParse,
70426 "%r %s BY term out of range - should be "
70427 "between 1 and %d", i, zType, mx);
70431 ** Analyze the ORDER BY clause in a compound SELECT statement. Modify
70432 ** each term of the ORDER BY clause is a constant integer between 1
70433 ** and N where N is the number of columns in the compound SELECT.
70435 ** ORDER BY terms that are already an integer between 1 and N are
70436 ** unmodified. ORDER BY terms that are integers outside the range of
70437 ** 1 through N generate an error. ORDER BY terms that are expressions
70438 ** are matched against result set expressions of compound SELECT
70439 ** beginning with the left-most SELECT and working toward the right.
70440 ** At the first match, the ORDER BY expression is transformed into
70441 ** the integer column number.
70443 ** Return the number of errors seen.
70445 static int resolveCompoundOrderBy(
70446 Parse *pParse, /* Parsing context. Leave error messages here */
70447 Select *pSelect /* The SELECT statement containing the ORDER BY */
70449 int i;
70450 ExprList *pOrderBy;
70451 ExprList *pEList;
70452 sqlite3 *db;
70453 int moreToDo = 1;
70455 pOrderBy = pSelect->pOrderBy;
70456 if( pOrderBy==0 ) return 0;
70457 db = pParse->db;
70458 #if SQLITE_MAX_COLUMN
70459 if( pOrderBy->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
70460 sqlite3ErrorMsg(pParse, "too many terms in ORDER BY clause");
70461 return 1;
70463 #endif
70464 for(i=0; i<pOrderBy->nExpr; i++){
70465 pOrderBy->a[i].done = 0;
70467 pSelect->pNext = 0;
70468 while( pSelect->pPrior ){
70469 pSelect->pPrior->pNext = pSelect;
70470 pSelect = pSelect->pPrior;
70472 while( pSelect && moreToDo ){
70473 struct ExprList_item *pItem;
70474 moreToDo = 0;
70475 pEList = pSelect->pEList;
70476 assert( pEList!=0 );
70477 for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
70478 int iCol = -1;
70479 Expr *pE, *pDup;
70480 if( pItem->done ) continue;
70481 pE = pItem->pExpr;
70482 if( sqlite3ExprIsInteger(pE, &iCol) ){
70483 if( iCol<=0 || iCol>pEList->nExpr ){
70484 resolveOutOfRangeError(pParse, "ORDER", i+1, pEList->nExpr);
70485 return 1;
70487 }else{
70488 iCol = resolveAsName(pParse, pEList, pE);
70489 if( iCol==0 ){
70490 pDup = sqlite3ExprDup(db, pE, 0);
70491 if( !db->mallocFailed ){
70492 assert(pDup);
70493 iCol = resolveOrderByTermToExprList(pParse, pSelect, pDup);
70495 sqlite3ExprDelete(db, pDup);
70498 if( iCol>0 ){
70499 CollSeq *pColl = pE->pColl;
70500 int flags = pE->flags & EP_ExpCollate;
70501 sqlite3ExprDelete(db, pE);
70502 pItem->pExpr = pE = sqlite3Expr(db, TK_INTEGER, 0);
70503 if( pE==0 ) return 1;
70504 pE->pColl = pColl;
70505 pE->flags |= EP_IntValue | flags;
70506 pE->u.iValue = iCol;
70507 pItem->iCol = (u16)iCol;
70508 pItem->done = 1;
70509 }else{
70510 moreToDo = 1;
70513 pSelect = pSelect->pNext;
70515 for(i=0; i<pOrderBy->nExpr; i++){
70516 if( pOrderBy->a[i].done==0 ){
70517 sqlite3ErrorMsg(pParse, "%r ORDER BY term does not match any "
70518 "column in the result set", i+1);
70519 return 1;
70522 return 0;
70526 ** Check every term in the ORDER BY or GROUP BY clause pOrderBy of
70527 ** the SELECT statement pSelect. If any term is reference to a
70528 ** result set expression (as determined by the ExprList.a.iCol field)
70529 ** then convert that term into a copy of the corresponding result set
70530 ** column.
70532 ** If any errors are detected, add an error message to pParse and
70533 ** return non-zero. Return zero if no errors are seen.
70535 SQLITE_PRIVATE int sqlite3ResolveOrderGroupBy(
70536 Parse *pParse, /* Parsing context. Leave error messages here */
70537 Select *pSelect, /* The SELECT statement containing the clause */
70538 ExprList *pOrderBy, /* The ORDER BY or GROUP BY clause to be processed */
70539 const char *zType /* "ORDER" or "GROUP" */
70541 int i;
70542 sqlite3 *db = pParse->db;
70543 ExprList *pEList;
70544 struct ExprList_item *pItem;
70546 if( pOrderBy==0 || pParse->db->mallocFailed ) return 0;
70547 #if SQLITE_MAX_COLUMN
70548 if( pOrderBy->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
70549 sqlite3ErrorMsg(pParse, "too many terms in %s BY clause", zType);
70550 return 1;
70552 #endif
70553 pEList = pSelect->pEList;
70554 assert( pEList!=0 ); /* sqlite3SelectNew() guarantees this */
70555 for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
70556 if( pItem->iCol ){
70557 if( pItem->iCol>pEList->nExpr ){
70558 resolveOutOfRangeError(pParse, zType, i+1, pEList->nExpr);
70559 return 1;
70561 resolveAlias(pParse, pEList, pItem->iCol-1, pItem->pExpr, zType);
70564 return 0;
70568 ** pOrderBy is an ORDER BY or GROUP BY clause in SELECT statement pSelect.
70569 ** The Name context of the SELECT statement is pNC. zType is either
70570 ** "ORDER" or "GROUP" depending on which type of clause pOrderBy is.
70572 ** This routine resolves each term of the clause into an expression.
70573 ** If the order-by term is an integer I between 1 and N (where N is the
70574 ** number of columns in the result set of the SELECT) then the expression
70575 ** in the resolution is a copy of the I-th result-set expression. If
70576 ** the order-by term is an identify that corresponds to the AS-name of
70577 ** a result-set expression, then the term resolves to a copy of the
70578 ** result-set expression. Otherwise, the expression is resolved in
70579 ** the usual way - using sqlite3ResolveExprNames().
70581 ** This routine returns the number of errors. If errors occur, then
70582 ** an appropriate error message might be left in pParse. (OOM errors
70583 ** excepted.)
70585 static int resolveOrderGroupBy(
70586 NameContext *pNC, /* The name context of the SELECT statement */
70587 Select *pSelect, /* The SELECT statement holding pOrderBy */
70588 ExprList *pOrderBy, /* An ORDER BY or GROUP BY clause to resolve */
70589 const char *zType /* Either "ORDER" or "GROUP", as appropriate */
70591 int i; /* Loop counter */
70592 int iCol; /* Column number */
70593 struct ExprList_item *pItem; /* A term of the ORDER BY clause */
70594 Parse *pParse; /* Parsing context */
70595 int nResult; /* Number of terms in the result set */
70597 if( pOrderBy==0 ) return 0;
70598 nResult = pSelect->pEList->nExpr;
70599 pParse = pNC->pParse;
70600 for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
70601 Expr *pE = pItem->pExpr;
70602 iCol = resolveAsName(pParse, pSelect->pEList, pE);
70603 if( iCol>0 ){
70604 /* If an AS-name match is found, mark this ORDER BY column as being
70605 ** a copy of the iCol-th result-set column. The subsequent call to
70606 ** sqlite3ResolveOrderGroupBy() will convert the expression to a
70607 ** copy of the iCol-th result-set expression. */
70608 pItem->iCol = (u16)iCol;
70609 continue;
70611 if( sqlite3ExprIsInteger(pE, &iCol) ){
70612 /* The ORDER BY term is an integer constant. Again, set the column
70613 ** number so that sqlite3ResolveOrderGroupBy() will convert the
70614 ** order-by term to a copy of the result-set expression */
70615 if( iCol<1 ){
70616 resolveOutOfRangeError(pParse, zType, i+1, nResult);
70617 return 1;
70619 pItem->iCol = (u16)iCol;
70620 continue;
70623 /* Otherwise, treat the ORDER BY term as an ordinary expression */
70624 pItem->iCol = 0;
70625 if( sqlite3ResolveExprNames(pNC, pE) ){
70626 return 1;
70629 return sqlite3ResolveOrderGroupBy(pParse, pSelect, pOrderBy, zType);
70633 ** Resolve names in the SELECT statement p and all of its descendents.
70635 static int resolveSelectStep(Walker *pWalker, Select *p){
70636 NameContext *pOuterNC; /* Context that contains this SELECT */
70637 NameContext sNC; /* Name context of this SELECT */
70638 int isCompound; /* True if p is a compound select */
70639 int nCompound; /* Number of compound terms processed so far */
70640 Parse *pParse; /* Parsing context */
70641 ExprList *pEList; /* Result set expression list */
70642 int i; /* Loop counter */
70643 ExprList *pGroupBy; /* The GROUP BY clause */
70644 Select *pLeftmost; /* Left-most of SELECT of a compound */
70645 sqlite3 *db; /* Database connection */
70648 assert( p!=0 );
70649 if( p->selFlags & SF_Resolved ){
70650 return WRC_Prune;
70652 pOuterNC = pWalker->u.pNC;
70653 pParse = pWalker->pParse;
70654 db = pParse->db;
70656 /* Normally sqlite3SelectExpand() will be called first and will have
70657 ** already expanded this SELECT. However, if this is a subquery within
70658 ** an expression, sqlite3ResolveExprNames() will be called without a
70659 ** prior call to sqlite3SelectExpand(). When that happens, let
70660 ** sqlite3SelectPrep() do all of the processing for this SELECT.
70661 ** sqlite3SelectPrep() will invoke both sqlite3SelectExpand() and
70662 ** this routine in the correct order.
70664 if( (p->selFlags & SF_Expanded)==0 ){
70665 sqlite3SelectPrep(pParse, p, pOuterNC);
70666 return (pParse->nErr || db->mallocFailed) ? WRC_Abort : WRC_Prune;
70669 isCompound = p->pPrior!=0;
70670 nCompound = 0;
70671 pLeftmost = p;
70672 while( p ){
70673 assert( (p->selFlags & SF_Expanded)!=0 );
70674 assert( (p->selFlags & SF_Resolved)==0 );
70675 p->selFlags |= SF_Resolved;
70677 /* Resolve the expressions in the LIMIT and OFFSET clauses. These
70678 ** are not allowed to refer to any names, so pass an empty NameContext.
70680 memset(&sNC, 0, sizeof(sNC));
70681 sNC.pParse = pParse;
70682 if( sqlite3ResolveExprNames(&sNC, p->pLimit) ||
70683 sqlite3ResolveExprNames(&sNC, p->pOffset) ){
70684 return WRC_Abort;
70687 /* Set up the local name-context to pass to sqlite3ResolveExprNames() to
70688 ** resolve the result-set expression list.
70690 sNC.allowAgg = 1;
70691 sNC.pSrcList = p->pSrc;
70692 sNC.pNext = pOuterNC;
70694 /* Resolve names in the result set. */
70695 pEList = p->pEList;
70696 assert( pEList!=0 );
70697 for(i=0; i<pEList->nExpr; i++){
70698 Expr *pX = pEList->a[i].pExpr;
70699 if( sqlite3ResolveExprNames(&sNC, pX) ){
70700 return WRC_Abort;
70704 /* Recursively resolve names in all subqueries
70706 for(i=0; i<p->pSrc->nSrc; i++){
70707 struct SrcList_item *pItem = &p->pSrc->a[i];
70708 if( pItem->pSelect ){
70709 const char *zSavedContext = pParse->zAuthContext;
70710 if( pItem->zName ) pParse->zAuthContext = pItem->zName;
70711 sqlite3ResolveSelectNames(pParse, pItem->pSelect, pOuterNC);
70712 pParse->zAuthContext = zSavedContext;
70713 if( pParse->nErr || db->mallocFailed ) return WRC_Abort;
70717 /* If there are no aggregate functions in the result-set, and no GROUP BY
70718 ** expression, do not allow aggregates in any of the other expressions.
70720 assert( (p->selFlags & SF_Aggregate)==0 );
70721 pGroupBy = p->pGroupBy;
70722 if( pGroupBy || sNC.hasAgg ){
70723 p->selFlags |= SF_Aggregate;
70724 }else{
70725 sNC.allowAgg = 0;
70728 /* If a HAVING clause is present, then there must be a GROUP BY clause.
70730 if( p->pHaving && !pGroupBy ){
70731 sqlite3ErrorMsg(pParse, "a GROUP BY clause is required before HAVING");
70732 return WRC_Abort;
70735 /* Add the expression list to the name-context before parsing the
70736 ** other expressions in the SELECT statement. This is so that
70737 ** expressions in the WHERE clause (etc.) can refer to expressions by
70738 ** aliases in the result set.
70740 ** Minor point: If this is the case, then the expression will be
70741 ** re-evaluated for each reference to it.
70743 sNC.pEList = p->pEList;
70744 if( sqlite3ResolveExprNames(&sNC, p->pWhere) ||
70745 sqlite3ResolveExprNames(&sNC, p->pHaving)
70747 return WRC_Abort;
70750 /* The ORDER BY and GROUP BY clauses may not refer to terms in
70751 ** outer queries
70753 sNC.pNext = 0;
70754 sNC.allowAgg = 1;
70756 /* Process the ORDER BY clause for singleton SELECT statements.
70757 ** The ORDER BY clause for compounds SELECT statements is handled
70758 ** below, after all of the result-sets for all of the elements of
70759 ** the compound have been resolved.
70761 if( !isCompound && resolveOrderGroupBy(&sNC, p, p->pOrderBy, "ORDER") ){
70762 return WRC_Abort;
70764 if( db->mallocFailed ){
70765 return WRC_Abort;
70768 /* Resolve the GROUP BY clause. At the same time, make sure
70769 ** the GROUP BY clause does not contain aggregate functions.
70771 if( pGroupBy ){
70772 struct ExprList_item *pItem;
70774 if( resolveOrderGroupBy(&sNC, p, pGroupBy, "GROUP") || db->mallocFailed ){
70775 return WRC_Abort;
70777 for(i=0, pItem=pGroupBy->a; i<pGroupBy->nExpr; i++, pItem++){
70778 if( ExprHasProperty(pItem->pExpr, EP_Agg) ){
70779 sqlite3ErrorMsg(pParse, "aggregate functions are not allowed in "
70780 "the GROUP BY clause");
70781 return WRC_Abort;
70786 /* Advance to the next term of the compound
70788 p = p->pPrior;
70789 nCompound++;
70792 /* Resolve the ORDER BY on a compound SELECT after all terms of
70793 ** the compound have been resolved.
70795 if( isCompound && resolveCompoundOrderBy(pParse, pLeftmost) ){
70796 return WRC_Abort;
70799 return WRC_Prune;
70803 ** This routine walks an expression tree and resolves references to
70804 ** table columns and result-set columns. At the same time, do error
70805 ** checking on function usage and set a flag if any aggregate functions
70806 ** are seen.
70808 ** To resolve table columns references we look for nodes (or subtrees) of the
70809 ** form X.Y.Z or Y.Z or just Z where
70811 ** X: The name of a database. Ex: "main" or "temp" or
70812 ** the symbolic name assigned to an ATTACH-ed database.
70814 ** Y: The name of a table in a FROM clause. Or in a trigger
70815 ** one of the special names "old" or "new".
70817 ** Z: The name of a column in table Y.
70819 ** The node at the root of the subtree is modified as follows:
70821 ** Expr.op Changed to TK_COLUMN
70822 ** Expr.pTab Points to the Table object for X.Y
70823 ** Expr.iColumn The column index in X.Y. -1 for the rowid.
70824 ** Expr.iTable The VDBE cursor number for X.Y
70827 ** To resolve result-set references, look for expression nodes of the
70828 ** form Z (with no X and Y prefix) where the Z matches the right-hand
70829 ** size of an AS clause in the result-set of a SELECT. The Z expression
70830 ** is replaced by a copy of the left-hand side of the result-set expression.
70831 ** Table-name and function resolution occurs on the substituted expression
70832 ** tree. For example, in:
70834 ** SELECT a+b AS x, c+d AS y FROM t1 ORDER BY x;
70836 ** The "x" term of the order by is replaced by "a+b" to render:
70838 ** SELECT a+b AS x, c+d AS y FROM t1 ORDER BY a+b;
70840 ** Function calls are checked to make sure that the function is
70841 ** defined and that the correct number of arguments are specified.
70842 ** If the function is an aggregate function, then the pNC->hasAgg is
70843 ** set and the opcode is changed from TK_FUNCTION to TK_AGG_FUNCTION.
70844 ** If an expression contains aggregate functions then the EP_Agg
70845 ** property on the expression is set.
70847 ** An error message is left in pParse if anything is amiss. The number
70848 ** if errors is returned.
70850 SQLITE_PRIVATE int sqlite3ResolveExprNames(
70851 NameContext *pNC, /* Namespace to resolve expressions in. */
70852 Expr *pExpr /* The expression to be analyzed. */
70854 int savedHasAgg;
70855 Walker w;
70857 if( pExpr==0 ) return 0;
70858 #if SQLITE_MAX_EXPR_DEPTH>0
70860 Parse *pParse = pNC->pParse;
70861 if( sqlite3ExprCheckHeight(pParse, pExpr->nHeight+pNC->pParse->nHeight) ){
70862 return 1;
70864 pParse->nHeight += pExpr->nHeight;
70866 #endif
70867 savedHasAgg = pNC->hasAgg;
70868 pNC->hasAgg = 0;
70869 w.xExprCallback = resolveExprStep;
70870 w.xSelectCallback = resolveSelectStep;
70871 w.pParse = pNC->pParse;
70872 w.u.pNC = pNC;
70873 sqlite3WalkExpr(&w, pExpr);
70874 #if SQLITE_MAX_EXPR_DEPTH>0
70875 pNC->pParse->nHeight -= pExpr->nHeight;
70876 #endif
70877 if( pNC->nErr>0 || w.pParse->nErr>0 ){
70878 ExprSetProperty(pExpr, EP_Error);
70880 if( pNC->hasAgg ){
70881 ExprSetProperty(pExpr, EP_Agg);
70882 }else if( savedHasAgg ){
70883 pNC->hasAgg = 1;
70885 return ExprHasProperty(pExpr, EP_Error);
70890 ** Resolve all names in all expressions of a SELECT and in all
70891 ** decendents of the SELECT, including compounds off of p->pPrior,
70892 ** subqueries in expressions, and subqueries used as FROM clause
70893 ** terms.
70895 ** See sqlite3ResolveExprNames() for a description of the kinds of
70896 ** transformations that occur.
70898 ** All SELECT statements should have been expanded using
70899 ** sqlite3SelectExpand() prior to invoking this routine.
70901 SQLITE_PRIVATE void sqlite3ResolveSelectNames(
70902 Parse *pParse, /* The parser context */
70903 Select *p, /* The SELECT statement being coded. */
70904 NameContext *pOuterNC /* Name context for parent SELECT statement */
70906 Walker w;
70908 assert( p!=0 );
70909 w.xExprCallback = resolveExprStep;
70910 w.xSelectCallback = resolveSelectStep;
70911 w.pParse = pParse;
70912 w.u.pNC = pOuterNC;
70913 sqlite3WalkSelect(&w, p);
70916 /************** End of resolve.c *********************************************/
70917 /************** Begin file expr.c ********************************************/
70919 ** 2001 September 15
70921 ** The author disclaims copyright to this source code. In place of
70922 ** a legal notice, here is a blessing:
70924 ** May you do good and not evil.
70925 ** May you find forgiveness for yourself and forgive others.
70926 ** May you share freely, never taking more than you give.
70928 *************************************************************************
70929 ** This file contains routines used for analyzing expressions and
70930 ** for generating VDBE code that evaluates expressions in SQLite.
70934 ** Return the 'affinity' of the expression pExpr if any.
70936 ** If pExpr is a column, a reference to a column via an 'AS' alias,
70937 ** or a sub-select with a column as the return value, then the
70938 ** affinity of that column is returned. Otherwise, 0x00 is returned,
70939 ** indicating no affinity for the expression.
70941 ** i.e. the WHERE clause expresssions in the following statements all
70942 ** have an affinity:
70944 ** CREATE TABLE t1(a);
70945 ** SELECT * FROM t1 WHERE a;
70946 ** SELECT a AS b FROM t1 WHERE b;
70947 ** SELECT * FROM t1 WHERE (select a from t1);
70949 SQLITE_PRIVATE char sqlite3ExprAffinity(Expr *pExpr){
70950 int op = pExpr->op;
70951 if( op==TK_SELECT ){
70952 assert( pExpr->flags&EP_xIsSelect );
70953 return sqlite3ExprAffinity(pExpr->x.pSelect->pEList->a[0].pExpr);
70955 #ifndef SQLITE_OMIT_CAST
70956 if( op==TK_CAST ){
70957 assert( !ExprHasProperty(pExpr, EP_IntValue) );
70958 return sqlite3AffinityType(pExpr->u.zToken);
70960 #endif
70961 if( (op==TK_AGG_COLUMN || op==TK_COLUMN || op==TK_REGISTER)
70962 && pExpr->pTab!=0
70964 /* op==TK_REGISTER && pExpr->pTab!=0 happens when pExpr was originally
70965 ** a TK_COLUMN but was previously evaluated and cached in a register */
70966 int j = pExpr->iColumn;
70967 if( j<0 ) return SQLITE_AFF_INTEGER;
70968 assert( pExpr->pTab && j<pExpr->pTab->nCol );
70969 return pExpr->pTab->aCol[j].affinity;
70971 return pExpr->affinity;
70975 ** Set the explicit collating sequence for an expression to the
70976 ** collating sequence supplied in the second argument.
70978 SQLITE_PRIVATE Expr *sqlite3ExprSetColl(Expr *pExpr, CollSeq *pColl){
70979 if( pExpr && pColl ){
70980 pExpr->pColl = pColl;
70981 pExpr->flags |= EP_ExpCollate;
70983 return pExpr;
70987 ** Set the collating sequence for expression pExpr to be the collating
70988 ** sequence named by pToken. Return a pointer to the revised expression.
70989 ** The collating sequence is marked as "explicit" using the EP_ExpCollate
70990 ** flag. An explicit collating sequence will override implicit
70991 ** collating sequences.
70993 SQLITE_PRIVATE Expr *sqlite3ExprSetCollByToken(Parse *pParse, Expr *pExpr, Token *pCollName){
70994 char *zColl = 0; /* Dequoted name of collation sequence */
70995 CollSeq *pColl;
70996 sqlite3 *db = pParse->db;
70997 zColl = sqlite3NameFromToken(db, pCollName);
70998 pColl = sqlite3LocateCollSeq(pParse, zColl);
70999 sqlite3ExprSetColl(pExpr, pColl);
71000 sqlite3DbFree(db, zColl);
71001 return pExpr;
71005 ** Return the default collation sequence for the expression pExpr. If
71006 ** there is no default collation type, return 0.
71008 SQLITE_PRIVATE CollSeq *sqlite3ExprCollSeq(Parse *pParse, Expr *pExpr){
71009 CollSeq *pColl = 0;
71010 Expr *p = pExpr;
71011 while( p ){
71012 int op;
71013 pColl = p->pColl;
71014 if( pColl ) break;
71015 op = p->op;
71016 if( p->pTab!=0 && (
71017 op==TK_AGG_COLUMN || op==TK_COLUMN || op==TK_REGISTER || op==TK_TRIGGER
71019 /* op==TK_REGISTER && p->pTab!=0 happens when pExpr was originally
71020 ** a TK_COLUMN but was previously evaluated and cached in a register */
71021 const char *zColl;
71022 int j = p->iColumn;
71023 if( j>=0 ){
71024 sqlite3 *db = pParse->db;
71025 zColl = p->pTab->aCol[j].zColl;
71026 pColl = sqlite3FindCollSeq(db, ENC(db), zColl, 0);
71027 pExpr->pColl = pColl;
71029 break;
71031 if( op!=TK_CAST && op!=TK_UPLUS ){
71032 break;
71034 p = p->pLeft;
71036 if( sqlite3CheckCollSeq(pParse, pColl) ){
71037 pColl = 0;
71039 return pColl;
71043 ** pExpr is an operand of a comparison operator. aff2 is the
71044 ** type affinity of the other operand. This routine returns the
71045 ** type affinity that should be used for the comparison operator.
71047 SQLITE_PRIVATE char sqlite3CompareAffinity(Expr *pExpr, char aff2){
71048 char aff1 = sqlite3ExprAffinity(pExpr);
71049 if( aff1 && aff2 ){
71050 /* Both sides of the comparison are columns. If one has numeric
71051 ** affinity, use that. Otherwise use no affinity.
71053 if( sqlite3IsNumericAffinity(aff1) || sqlite3IsNumericAffinity(aff2) ){
71054 return SQLITE_AFF_NUMERIC;
71055 }else{
71056 return SQLITE_AFF_NONE;
71058 }else if( !aff1 && !aff2 ){
71059 /* Neither side of the comparison is a column. Compare the
71060 ** results directly.
71062 return SQLITE_AFF_NONE;
71063 }else{
71064 /* One side is a column, the other is not. Use the columns affinity. */
71065 assert( aff1==0 || aff2==0 );
71066 return (aff1 + aff2);
71071 ** pExpr is a comparison operator. Return the type affinity that should
71072 ** be applied to both operands prior to doing the comparison.
71074 static char comparisonAffinity(Expr *pExpr){
71075 char aff;
71076 assert( pExpr->op==TK_EQ || pExpr->op==TK_IN || pExpr->op==TK_LT ||
71077 pExpr->op==TK_GT || pExpr->op==TK_GE || pExpr->op==TK_LE ||
71078 pExpr->op==TK_NE || pExpr->op==TK_IS || pExpr->op==TK_ISNOT );
71079 assert( pExpr->pLeft );
71080 aff = sqlite3ExprAffinity(pExpr->pLeft);
71081 if( pExpr->pRight ){
71082 aff = sqlite3CompareAffinity(pExpr->pRight, aff);
71083 }else if( ExprHasProperty(pExpr, EP_xIsSelect) ){
71084 aff = sqlite3CompareAffinity(pExpr->x.pSelect->pEList->a[0].pExpr, aff);
71085 }else if( !aff ){
71086 aff = SQLITE_AFF_NONE;
71088 return aff;
71092 ** pExpr is a comparison expression, eg. '=', '<', IN(...) etc.
71093 ** idx_affinity is the affinity of an indexed column. Return true
71094 ** if the index with affinity idx_affinity may be used to implement
71095 ** the comparison in pExpr.
71097 SQLITE_PRIVATE int sqlite3IndexAffinityOk(Expr *pExpr, char idx_affinity){
71098 char aff = comparisonAffinity(pExpr);
71099 switch( aff ){
71100 case SQLITE_AFF_NONE:
71101 return 1;
71102 case SQLITE_AFF_TEXT:
71103 return idx_affinity==SQLITE_AFF_TEXT;
71104 default:
71105 return sqlite3IsNumericAffinity(idx_affinity);
71110 ** Return the P5 value that should be used for a binary comparison
71111 ** opcode (OP_Eq, OP_Ge etc.) used to compare pExpr1 and pExpr2.
71113 static u8 binaryCompareP5(Expr *pExpr1, Expr *pExpr2, int jumpIfNull){
71114 u8 aff = (char)sqlite3ExprAffinity(pExpr2);
71115 aff = (u8)sqlite3CompareAffinity(pExpr1, aff) | (u8)jumpIfNull;
71116 return aff;
71120 ** Return a pointer to the collation sequence that should be used by
71121 ** a binary comparison operator comparing pLeft and pRight.
71123 ** If the left hand expression has a collating sequence type, then it is
71124 ** used. Otherwise the collation sequence for the right hand expression
71125 ** is used, or the default (BINARY) if neither expression has a collating
71126 ** type.
71128 ** Argument pRight (but not pLeft) may be a null pointer. In this case,
71129 ** it is not considered.
71131 SQLITE_PRIVATE CollSeq *sqlite3BinaryCompareCollSeq(
71132 Parse *pParse,
71133 Expr *pLeft,
71134 Expr *pRight
71136 CollSeq *pColl;
71137 assert( pLeft );
71138 if( pLeft->flags & EP_ExpCollate ){
71139 assert( pLeft->pColl );
71140 pColl = pLeft->pColl;
71141 }else if( pRight && pRight->flags & EP_ExpCollate ){
71142 assert( pRight->pColl );
71143 pColl = pRight->pColl;
71144 }else{
71145 pColl = sqlite3ExprCollSeq(pParse, pLeft);
71146 if( !pColl ){
71147 pColl = sqlite3ExprCollSeq(pParse, pRight);
71150 return pColl;
71154 ** Generate code for a comparison operator.
71156 static int codeCompare(
71157 Parse *pParse, /* The parsing (and code generating) context */
71158 Expr *pLeft, /* The left operand */
71159 Expr *pRight, /* The right operand */
71160 int opcode, /* The comparison opcode */
71161 int in1, int in2, /* Register holding operands */
71162 int dest, /* Jump here if true. */
71163 int jumpIfNull /* If true, jump if either operand is NULL */
71165 int p5;
71166 int addr;
71167 CollSeq *p4;
71169 p4 = sqlite3BinaryCompareCollSeq(pParse, pLeft, pRight);
71170 p5 = binaryCompareP5(pLeft, pRight, jumpIfNull);
71171 addr = sqlite3VdbeAddOp4(pParse->pVdbe, opcode, in2, dest, in1,
71172 (void*)p4, P4_COLLSEQ);
71173 sqlite3VdbeChangeP5(pParse->pVdbe, (u8)p5);
71174 return addr;
71177 #if SQLITE_MAX_EXPR_DEPTH>0
71179 ** Check that argument nHeight is less than or equal to the maximum
71180 ** expression depth allowed. If it is not, leave an error message in
71181 ** pParse.
71183 SQLITE_PRIVATE int sqlite3ExprCheckHeight(Parse *pParse, int nHeight){
71184 int rc = SQLITE_OK;
71185 int mxHeight = pParse->db->aLimit[SQLITE_LIMIT_EXPR_DEPTH];
71186 if( nHeight>mxHeight ){
71187 sqlite3ErrorMsg(pParse,
71188 "Expression tree is too large (maximum depth %d)", mxHeight
71190 rc = SQLITE_ERROR;
71192 return rc;
71195 /* The following three functions, heightOfExpr(), heightOfExprList()
71196 ** and heightOfSelect(), are used to determine the maximum height
71197 ** of any expression tree referenced by the structure passed as the
71198 ** first argument.
71200 ** If this maximum height is greater than the current value pointed
71201 ** to by pnHeight, the second parameter, then set *pnHeight to that
71202 ** value.
71204 static void heightOfExpr(Expr *p, int *pnHeight){
71205 if( p ){
71206 if( p->nHeight>*pnHeight ){
71207 *pnHeight = p->nHeight;
71211 static void heightOfExprList(ExprList *p, int *pnHeight){
71212 if( p ){
71213 int i;
71214 for(i=0; i<p->nExpr; i++){
71215 heightOfExpr(p->a[i].pExpr, pnHeight);
71219 static void heightOfSelect(Select *p, int *pnHeight){
71220 if( p ){
71221 heightOfExpr(p->pWhere, pnHeight);
71222 heightOfExpr(p->pHaving, pnHeight);
71223 heightOfExpr(p->pLimit, pnHeight);
71224 heightOfExpr(p->pOffset, pnHeight);
71225 heightOfExprList(p->pEList, pnHeight);
71226 heightOfExprList(p->pGroupBy, pnHeight);
71227 heightOfExprList(p->pOrderBy, pnHeight);
71228 heightOfSelect(p->pPrior, pnHeight);
71233 ** Set the Expr.nHeight variable in the structure passed as an
71234 ** argument. An expression with no children, Expr.pList or
71235 ** Expr.pSelect member has a height of 1. Any other expression
71236 ** has a height equal to the maximum height of any other
71237 ** referenced Expr plus one.
71239 static void exprSetHeight(Expr *p){
71240 int nHeight = 0;
71241 heightOfExpr(p->pLeft, &nHeight);
71242 heightOfExpr(p->pRight, &nHeight);
71243 if( ExprHasProperty(p, EP_xIsSelect) ){
71244 heightOfSelect(p->x.pSelect, &nHeight);
71245 }else{
71246 heightOfExprList(p->x.pList, &nHeight);
71248 p->nHeight = nHeight + 1;
71252 ** Set the Expr.nHeight variable using the exprSetHeight() function. If
71253 ** the height is greater than the maximum allowed expression depth,
71254 ** leave an error in pParse.
71256 SQLITE_PRIVATE void sqlite3ExprSetHeight(Parse *pParse, Expr *p){
71257 exprSetHeight(p);
71258 sqlite3ExprCheckHeight(pParse, p->nHeight);
71262 ** Return the maximum height of any expression tree referenced
71263 ** by the select statement passed as an argument.
71265 SQLITE_PRIVATE int sqlite3SelectExprHeight(Select *p){
71266 int nHeight = 0;
71267 heightOfSelect(p, &nHeight);
71268 return nHeight;
71270 #else
71271 #define exprSetHeight(y)
71272 #endif /* SQLITE_MAX_EXPR_DEPTH>0 */
71275 ** This routine is the core allocator for Expr nodes.
71277 ** Construct a new expression node and return a pointer to it. Memory
71278 ** for this node and for the pToken argument is a single allocation
71279 ** obtained from sqlite3DbMalloc(). The calling function
71280 ** is responsible for making sure the node eventually gets freed.
71282 ** If dequote is true, then the token (if it exists) is dequoted.
71283 ** If dequote is false, no dequoting is performance. The deQuote
71284 ** parameter is ignored if pToken is NULL or if the token does not
71285 ** appear to be quoted. If the quotes were of the form "..." (double-quotes)
71286 ** then the EP_DblQuoted flag is set on the expression node.
71288 ** Special case: If op==TK_INTEGER and pToken points to a string that
71289 ** can be translated into a 32-bit integer, then the token is not
71290 ** stored in u.zToken. Instead, the integer values is written
71291 ** into u.iValue and the EP_IntValue flag is set. No extra storage
71292 ** is allocated to hold the integer text and the dequote flag is ignored.
71294 SQLITE_PRIVATE Expr *sqlite3ExprAlloc(
71295 sqlite3 *db, /* Handle for sqlite3DbMallocZero() (may be null) */
71296 int op, /* Expression opcode */
71297 const Token *pToken, /* Token argument. Might be NULL */
71298 int dequote /* True to dequote */
71300 Expr *pNew;
71301 int nExtra = 0;
71302 int iValue = 0;
71304 if( pToken ){
71305 if( op!=TK_INTEGER || pToken->z==0
71306 || sqlite3GetInt32(pToken->z, &iValue)==0 ){
71307 nExtra = pToken->n+1;
71308 assert( iValue>=0 );
71311 pNew = sqlite3DbMallocZero(db, sizeof(Expr)+nExtra);
71312 if( pNew ){
71313 pNew->op = (u8)op;
71314 pNew->iAgg = -1;
71315 if( pToken ){
71316 if( nExtra==0 ){
71317 pNew->flags |= EP_IntValue;
71318 pNew->u.iValue = iValue;
71319 }else{
71320 int c;
71321 pNew->u.zToken = (char*)&pNew[1];
71322 memcpy(pNew->u.zToken, pToken->z, pToken->n);
71323 pNew->u.zToken[pToken->n] = 0;
71324 if( dequote && nExtra>=3
71325 && ((c = pToken->z[0])=='\'' || c=='"' || c=='[' || c=='`') ){
71326 sqlite3Dequote(pNew->u.zToken);
71327 if( c=='"' ) pNew->flags |= EP_DblQuoted;
71331 #if SQLITE_MAX_EXPR_DEPTH>0
71332 pNew->nHeight = 1;
71333 #endif
71335 return pNew;
71339 ** Allocate a new expression node from a zero-terminated token that has
71340 ** already been dequoted.
71342 SQLITE_PRIVATE Expr *sqlite3Expr(
71343 sqlite3 *db, /* Handle for sqlite3DbMallocZero() (may be null) */
71344 int op, /* Expression opcode */
71345 const char *zToken /* Token argument. Might be NULL */
71347 Token x;
71348 x.z = zToken;
71349 x.n = zToken ? sqlite3Strlen30(zToken) : 0;
71350 return sqlite3ExprAlloc(db, op, &x, 0);
71354 ** Attach subtrees pLeft and pRight to the Expr node pRoot.
71356 ** If pRoot==NULL that means that a memory allocation error has occurred.
71357 ** In that case, delete the subtrees pLeft and pRight.
71359 SQLITE_PRIVATE void sqlite3ExprAttachSubtrees(
71360 sqlite3 *db,
71361 Expr *pRoot,
71362 Expr *pLeft,
71363 Expr *pRight
71365 if( pRoot==0 ){
71366 assert( db->mallocFailed );
71367 sqlite3ExprDelete(db, pLeft);
71368 sqlite3ExprDelete(db, pRight);
71369 }else{
71370 if( pRight ){
71371 pRoot->pRight = pRight;
71372 if( pRight->flags & EP_ExpCollate ){
71373 pRoot->flags |= EP_ExpCollate;
71374 pRoot->pColl = pRight->pColl;
71377 if( pLeft ){
71378 pRoot->pLeft = pLeft;
71379 if( pLeft->flags & EP_ExpCollate ){
71380 pRoot->flags |= EP_ExpCollate;
71381 pRoot->pColl = pLeft->pColl;
71384 exprSetHeight(pRoot);
71389 ** Allocate a Expr node which joins as many as two subtrees.
71391 ** One or both of the subtrees can be NULL. Return a pointer to the new
71392 ** Expr node. Or, if an OOM error occurs, set pParse->db->mallocFailed,
71393 ** free the subtrees and return NULL.
71395 SQLITE_PRIVATE Expr *sqlite3PExpr(
71396 Parse *pParse, /* Parsing context */
71397 int op, /* Expression opcode */
71398 Expr *pLeft, /* Left operand */
71399 Expr *pRight, /* Right operand */
71400 const Token *pToken /* Argument token */
71402 Expr *p = sqlite3ExprAlloc(pParse->db, op, pToken, 1);
71403 sqlite3ExprAttachSubtrees(pParse->db, p, pLeft, pRight);
71404 if( p ) {
71405 sqlite3ExprCheckHeight(pParse, p->nHeight);
71407 return p;
71411 ** Join two expressions using an AND operator. If either expression is
71412 ** NULL, then just return the other expression.
71414 SQLITE_PRIVATE Expr *sqlite3ExprAnd(sqlite3 *db, Expr *pLeft, Expr *pRight){
71415 if( pLeft==0 ){
71416 return pRight;
71417 }else if( pRight==0 ){
71418 return pLeft;
71419 }else{
71420 Expr *pNew = sqlite3ExprAlloc(db, TK_AND, 0, 0);
71421 sqlite3ExprAttachSubtrees(db, pNew, pLeft, pRight);
71422 return pNew;
71427 ** Construct a new expression node for a function with multiple
71428 ** arguments.
71430 SQLITE_PRIVATE Expr *sqlite3ExprFunction(Parse *pParse, ExprList *pList, Token *pToken){
71431 Expr *pNew;
71432 sqlite3 *db = pParse->db;
71433 assert( pToken );
71434 pNew = sqlite3ExprAlloc(db, TK_FUNCTION, pToken, 1);
71435 if( pNew==0 ){
71436 sqlite3ExprListDelete(db, pList); /* Avoid memory leak when malloc fails */
71437 return 0;
71439 pNew->x.pList = pList;
71440 assert( !ExprHasProperty(pNew, EP_xIsSelect) );
71441 sqlite3ExprSetHeight(pParse, pNew);
71442 return pNew;
71446 ** Assign a variable number to an expression that encodes a wildcard
71447 ** in the original SQL statement.
71449 ** Wildcards consisting of a single "?" are assigned the next sequential
71450 ** variable number.
71452 ** Wildcards of the form "?nnn" are assigned the number "nnn". We make
71453 ** sure "nnn" is not too be to avoid a denial of service attack when
71454 ** the SQL statement comes from an external source.
71456 ** Wildcards of the form ":aaa", "@aaa", or "$aaa" are assigned the same number
71457 ** as the previous instance of the same wildcard. Or if this is the first
71458 ** instance of the wildcard, the next sequenial variable number is
71459 ** assigned.
71461 SQLITE_PRIVATE void sqlite3ExprAssignVarNumber(Parse *pParse, Expr *pExpr){
71462 sqlite3 *db = pParse->db;
71463 const char *z;
71465 if( pExpr==0 ) return;
71466 assert( !ExprHasAnyProperty(pExpr, EP_IntValue|EP_Reduced|EP_TokenOnly) );
71467 z = pExpr->u.zToken;
71468 assert( z!=0 );
71469 assert( z[0]!=0 );
71470 if( z[1]==0 ){
71471 /* Wildcard of the form "?". Assign the next variable number */
71472 assert( z[0]=='?' );
71473 pExpr->iColumn = (ynVar)(++pParse->nVar);
71474 }else if( z[0]=='?' ){
71475 /* Wildcard of the form "?nnn". Convert "nnn" to an integer and
71476 ** use it as the variable number */
71477 i64 i;
71478 int bOk = 0==sqlite3Atoi64(&z[1], &i, sqlite3Strlen30(&z[1]), SQLITE_UTF8);
71479 pExpr->iColumn = (ynVar)i;
71480 testcase( i==0 );
71481 testcase( i==1 );
71482 testcase( i==db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER]-1 );
71483 testcase( i==db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] );
71484 if( bOk==0 || i<1 || i>db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] ){
71485 sqlite3ErrorMsg(pParse, "variable number must be between ?1 and ?%d",
71486 db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER]);
71488 if( i>pParse->nVar ){
71489 pParse->nVar = (int)i;
71491 }else{
71492 /* Wildcards like ":aaa", "$aaa" or "@aaa". Reuse the same variable
71493 ** number as the prior appearance of the same name, or if the name
71494 ** has never appeared before, reuse the same variable number
71496 int i;
71497 for(i=0; i<pParse->nVarExpr; i++){
71498 Expr *pE = pParse->apVarExpr[i];
71499 assert( pE!=0 );
71500 if( strcmp(pE->u.zToken, z)==0 ){
71501 pExpr->iColumn = pE->iColumn;
71502 break;
71505 if( i>=pParse->nVarExpr ){
71506 pExpr->iColumn = (ynVar)(++pParse->nVar);
71507 if( pParse->nVarExpr>=pParse->nVarExprAlloc-1 ){
71508 pParse->nVarExprAlloc += pParse->nVarExprAlloc + 10;
71509 pParse->apVarExpr =
71510 sqlite3DbReallocOrFree(
71512 pParse->apVarExpr,
71513 pParse->nVarExprAlloc*sizeof(pParse->apVarExpr[0])
71516 if( !db->mallocFailed ){
71517 assert( pParse->apVarExpr!=0 );
71518 pParse->apVarExpr[pParse->nVarExpr++] = pExpr;
71522 if( !pParse->nErr && pParse->nVar>db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] ){
71523 sqlite3ErrorMsg(pParse, "too many SQL variables");
71528 ** Recursively delete an expression tree.
71530 SQLITE_PRIVATE void sqlite3ExprDelete(sqlite3 *db, Expr *p){
71531 if( p==0 ) return;
71532 /* Sanity check: Assert that the IntValue is non-negative if it exists */
71533 assert( !ExprHasProperty(p, EP_IntValue) || p->u.iValue>=0 );
71534 if( !ExprHasAnyProperty(p, EP_TokenOnly) ){
71535 sqlite3ExprDelete(db, p->pLeft);
71536 sqlite3ExprDelete(db, p->pRight);
71537 if( !ExprHasProperty(p, EP_Reduced) && (p->flags2 & EP2_MallocedToken)!=0 ){
71538 sqlite3DbFree(db, p->u.zToken);
71540 if( ExprHasProperty(p, EP_xIsSelect) ){
71541 sqlite3SelectDelete(db, p->x.pSelect);
71542 }else{
71543 sqlite3ExprListDelete(db, p->x.pList);
71546 if( !ExprHasProperty(p, EP_Static) ){
71547 sqlite3DbFree(db, p);
71552 ** Return the number of bytes allocated for the expression structure
71553 ** passed as the first argument. This is always one of EXPR_FULLSIZE,
71554 ** EXPR_REDUCEDSIZE or EXPR_TOKENONLYSIZE.
71556 static int exprStructSize(Expr *p){
71557 if( ExprHasProperty(p, EP_TokenOnly) ) return EXPR_TOKENONLYSIZE;
71558 if( ExprHasProperty(p, EP_Reduced) ) return EXPR_REDUCEDSIZE;
71559 return EXPR_FULLSIZE;
71563 ** The dupedExpr*Size() routines each return the number of bytes required
71564 ** to store a copy of an expression or expression tree. They differ in
71565 ** how much of the tree is measured.
71567 ** dupedExprStructSize() Size of only the Expr structure
71568 ** dupedExprNodeSize() Size of Expr + space for token
71569 ** dupedExprSize() Expr + token + subtree components
71571 ***************************************************************************
71573 ** The dupedExprStructSize() function returns two values OR-ed together:
71574 ** (1) the space required for a copy of the Expr structure only and
71575 ** (2) the EP_xxx flags that indicate what the structure size should be.
71576 ** The return values is always one of:
71578 ** EXPR_FULLSIZE
71579 ** EXPR_REDUCEDSIZE | EP_Reduced
71580 ** EXPR_TOKENONLYSIZE | EP_TokenOnly
71582 ** The size of the structure can be found by masking the return value
71583 ** of this routine with 0xfff. The flags can be found by masking the
71584 ** return value with EP_Reduced|EP_TokenOnly.
71586 ** Note that with flags==EXPRDUP_REDUCE, this routines works on full-size
71587 ** (unreduced) Expr objects as they or originally constructed by the parser.
71588 ** During expression analysis, extra information is computed and moved into
71589 ** later parts of teh Expr object and that extra information might get chopped
71590 ** off if the expression is reduced. Note also that it does not work to
71591 ** make a EXPRDUP_REDUCE copy of a reduced expression. It is only legal
71592 ** to reduce a pristine expression tree from the parser. The implementation
71593 ** of dupedExprStructSize() contain multiple assert() statements that attempt
71594 ** to enforce this constraint.
71596 static int dupedExprStructSize(Expr *p, int flags){
71597 int nSize;
71598 assert( flags==EXPRDUP_REDUCE || flags==0 ); /* Only one flag value allowed */
71599 if( 0==(flags&EXPRDUP_REDUCE) ){
71600 nSize = EXPR_FULLSIZE;
71601 }else{
71602 assert( !ExprHasAnyProperty(p, EP_TokenOnly|EP_Reduced) );
71603 assert( !ExprHasProperty(p, EP_FromJoin) );
71604 assert( (p->flags2 & EP2_MallocedToken)==0 );
71605 assert( (p->flags2 & EP2_Irreducible)==0 );
71606 if( p->pLeft || p->pRight || p->pColl || p->x.pList ){
71607 nSize = EXPR_REDUCEDSIZE | EP_Reduced;
71608 }else{
71609 nSize = EXPR_TOKENONLYSIZE | EP_TokenOnly;
71612 return nSize;
71616 ** This function returns the space in bytes required to store the copy
71617 ** of the Expr structure and a copy of the Expr.u.zToken string (if that
71618 ** string is defined.)
71620 static int dupedExprNodeSize(Expr *p, int flags){
71621 int nByte = dupedExprStructSize(p, flags) & 0xfff;
71622 if( !ExprHasProperty(p, EP_IntValue) && p->u.zToken ){
71623 nByte += sqlite3Strlen30(p->u.zToken)+1;
71625 return ROUND8(nByte);
71629 ** Return the number of bytes required to create a duplicate of the
71630 ** expression passed as the first argument. The second argument is a
71631 ** mask containing EXPRDUP_XXX flags.
71633 ** The value returned includes space to create a copy of the Expr struct
71634 ** itself and the buffer referred to by Expr.u.zToken, if any.
71636 ** If the EXPRDUP_REDUCE flag is set, then the return value includes
71637 ** space to duplicate all Expr nodes in the tree formed by Expr.pLeft
71638 ** and Expr.pRight variables (but not for any structures pointed to or
71639 ** descended from the Expr.x.pList or Expr.x.pSelect variables).
71641 static int dupedExprSize(Expr *p, int flags){
71642 int nByte = 0;
71643 if( p ){
71644 nByte = dupedExprNodeSize(p, flags);
71645 if( flags&EXPRDUP_REDUCE ){
71646 nByte += dupedExprSize(p->pLeft, flags) + dupedExprSize(p->pRight, flags);
71649 return nByte;
71653 ** This function is similar to sqlite3ExprDup(), except that if pzBuffer
71654 ** is not NULL then *pzBuffer is assumed to point to a buffer large enough
71655 ** to store the copy of expression p, the copies of p->u.zToken
71656 ** (if applicable), and the copies of the p->pLeft and p->pRight expressions,
71657 ** if any. Before returning, *pzBuffer is set to the first byte passed the
71658 ** portion of the buffer copied into by this function.
71660 static Expr *exprDup(sqlite3 *db, Expr *p, int flags, u8 **pzBuffer){
71661 Expr *pNew = 0; /* Value to return */
71662 if( p ){
71663 const int isReduced = (flags&EXPRDUP_REDUCE);
71664 u8 *zAlloc;
71665 u32 staticFlag = 0;
71667 assert( pzBuffer==0 || isReduced );
71669 /* Figure out where to write the new Expr structure. */
71670 if( pzBuffer ){
71671 zAlloc = *pzBuffer;
71672 staticFlag = EP_Static;
71673 }else{
71674 zAlloc = sqlite3DbMallocRaw(db, dupedExprSize(p, flags));
71676 pNew = (Expr *)zAlloc;
71678 if( pNew ){
71679 /* Set nNewSize to the size allocated for the structure pointed to
71680 ** by pNew. This is either EXPR_FULLSIZE, EXPR_REDUCEDSIZE or
71681 ** EXPR_TOKENONLYSIZE. nToken is set to the number of bytes consumed
71682 ** by the copy of the p->u.zToken string (if any).
71684 const unsigned nStructSize = dupedExprStructSize(p, flags);
71685 const int nNewSize = nStructSize & 0xfff;
71686 int nToken;
71687 if( !ExprHasProperty(p, EP_IntValue) && p->u.zToken ){
71688 nToken = sqlite3Strlen30(p->u.zToken) + 1;
71689 }else{
71690 nToken = 0;
71692 if( isReduced ){
71693 assert( ExprHasProperty(p, EP_Reduced)==0 );
71694 memcpy(zAlloc, p, nNewSize);
71695 }else{
71696 int nSize = exprStructSize(p);
71697 memcpy(zAlloc, p, nSize);
71698 if( EXPR_FULLSIZE>nSize ){
71699 memset(&zAlloc[nSize], 0, EXPR_FULLSIZE-nSize);
71703 /* Set the EP_Reduced, EP_TokenOnly, and EP_Static flags appropriately. */
71704 pNew->flags &= ~(EP_Reduced|EP_TokenOnly|EP_Static);
71705 pNew->flags |= nStructSize & (EP_Reduced|EP_TokenOnly);
71706 pNew->flags |= staticFlag;
71708 /* Copy the p->u.zToken string, if any. */
71709 if( nToken ){
71710 char *zToken = pNew->u.zToken = (char*)&zAlloc[nNewSize];
71711 memcpy(zToken, p->u.zToken, nToken);
71714 if( 0==((p->flags|pNew->flags) & EP_TokenOnly) ){
71715 /* Fill in the pNew->x.pSelect or pNew->x.pList member. */
71716 if( ExprHasProperty(p, EP_xIsSelect) ){
71717 pNew->x.pSelect = sqlite3SelectDup(db, p->x.pSelect, isReduced);
71718 }else{
71719 pNew->x.pList = sqlite3ExprListDup(db, p->x.pList, isReduced);
71723 /* Fill in pNew->pLeft and pNew->pRight. */
71724 if( ExprHasAnyProperty(pNew, EP_Reduced|EP_TokenOnly) ){
71725 zAlloc += dupedExprNodeSize(p, flags);
71726 if( ExprHasProperty(pNew, EP_Reduced) ){
71727 pNew->pLeft = exprDup(db, p->pLeft, EXPRDUP_REDUCE, &zAlloc);
71728 pNew->pRight = exprDup(db, p->pRight, EXPRDUP_REDUCE, &zAlloc);
71730 if( pzBuffer ){
71731 *pzBuffer = zAlloc;
71733 }else{
71734 pNew->flags2 = 0;
71735 if( !ExprHasAnyProperty(p, EP_TokenOnly) ){
71736 pNew->pLeft = sqlite3ExprDup(db, p->pLeft, 0);
71737 pNew->pRight = sqlite3ExprDup(db, p->pRight, 0);
71743 return pNew;
71747 ** The following group of routines make deep copies of expressions,
71748 ** expression lists, ID lists, and select statements. The copies can
71749 ** be deleted (by being passed to their respective ...Delete() routines)
71750 ** without effecting the originals.
71752 ** The expression list, ID, and source lists return by sqlite3ExprListDup(),
71753 ** sqlite3IdListDup(), and sqlite3SrcListDup() can not be further expanded
71754 ** by subsequent calls to sqlite*ListAppend() routines.
71756 ** Any tables that the SrcList might point to are not duplicated.
71758 ** The flags parameter contains a combination of the EXPRDUP_XXX flags.
71759 ** If the EXPRDUP_REDUCE flag is set, then the structure returned is a
71760 ** truncated version of the usual Expr structure that will be stored as
71761 ** part of the in-memory representation of the database schema.
71763 SQLITE_PRIVATE Expr *sqlite3ExprDup(sqlite3 *db, Expr *p, int flags){
71764 return exprDup(db, p, flags, 0);
71766 SQLITE_PRIVATE ExprList *sqlite3ExprListDup(sqlite3 *db, ExprList *p, int flags){
71767 ExprList *pNew;
71768 struct ExprList_item *pItem, *pOldItem;
71769 int i;
71770 if( p==0 ) return 0;
71771 pNew = sqlite3DbMallocRaw(db, sizeof(*pNew) );
71772 if( pNew==0 ) return 0;
71773 pNew->iECursor = 0;
71774 pNew->nExpr = pNew->nAlloc = p->nExpr;
71775 pNew->a = pItem = sqlite3DbMallocRaw(db, p->nExpr*sizeof(p->a[0]) );
71776 if( pItem==0 ){
71777 sqlite3DbFree(db, pNew);
71778 return 0;
71780 pOldItem = p->a;
71781 for(i=0; i<p->nExpr; i++, pItem++, pOldItem++){
71782 Expr *pOldExpr = pOldItem->pExpr;
71783 pItem->pExpr = sqlite3ExprDup(db, pOldExpr, flags);
71784 pItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
71785 pItem->zSpan = sqlite3DbStrDup(db, pOldItem->zSpan);
71786 pItem->sortOrder = pOldItem->sortOrder;
71787 pItem->done = 0;
71788 pItem->iCol = pOldItem->iCol;
71789 pItem->iAlias = pOldItem->iAlias;
71791 return pNew;
71795 ** If cursors, triggers, views and subqueries are all omitted from
71796 ** the build, then none of the following routines, except for
71797 ** sqlite3SelectDup(), can be called. sqlite3SelectDup() is sometimes
71798 ** called with a NULL argument.
71800 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER) \
71801 || !defined(SQLITE_OMIT_SUBQUERY)
71802 SQLITE_PRIVATE SrcList *sqlite3SrcListDup(sqlite3 *db, SrcList *p, int flags){
71803 SrcList *pNew;
71804 int i;
71805 int nByte;
71806 if( p==0 ) return 0;
71807 nByte = sizeof(*p) + (p->nSrc>0 ? sizeof(p->a[0]) * (p->nSrc-1) : 0);
71808 pNew = sqlite3DbMallocRaw(db, nByte );
71809 if( pNew==0 ) return 0;
71810 pNew->nSrc = pNew->nAlloc = p->nSrc;
71811 for(i=0; i<p->nSrc; i++){
71812 struct SrcList_item *pNewItem = &pNew->a[i];
71813 struct SrcList_item *pOldItem = &p->a[i];
71814 Table *pTab;
71815 pNewItem->zDatabase = sqlite3DbStrDup(db, pOldItem->zDatabase);
71816 pNewItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
71817 pNewItem->zAlias = sqlite3DbStrDup(db, pOldItem->zAlias);
71818 pNewItem->jointype = pOldItem->jointype;
71819 pNewItem->iCursor = pOldItem->iCursor;
71820 pNewItem->isPopulated = pOldItem->isPopulated;
71821 pNewItem->zIndex = sqlite3DbStrDup(db, pOldItem->zIndex);
71822 pNewItem->notIndexed = pOldItem->notIndexed;
71823 pNewItem->pIndex = pOldItem->pIndex;
71824 pTab = pNewItem->pTab = pOldItem->pTab;
71825 if( pTab ){
71826 pTab->nRef++;
71828 pNewItem->pSelect = sqlite3SelectDup(db, pOldItem->pSelect, flags);
71829 pNewItem->pOn = sqlite3ExprDup(db, pOldItem->pOn, flags);
71830 pNewItem->pUsing = sqlite3IdListDup(db, pOldItem->pUsing);
71831 pNewItem->colUsed = pOldItem->colUsed;
71833 return pNew;
71835 SQLITE_PRIVATE IdList *sqlite3IdListDup(sqlite3 *db, IdList *p){
71836 IdList *pNew;
71837 int i;
71838 if( p==0 ) return 0;
71839 pNew = sqlite3DbMallocRaw(db, sizeof(*pNew) );
71840 if( pNew==0 ) return 0;
71841 pNew->nId = pNew->nAlloc = p->nId;
71842 pNew->a = sqlite3DbMallocRaw(db, p->nId*sizeof(p->a[0]) );
71843 if( pNew->a==0 ){
71844 sqlite3DbFree(db, pNew);
71845 return 0;
71847 for(i=0; i<p->nId; i++){
71848 struct IdList_item *pNewItem = &pNew->a[i];
71849 struct IdList_item *pOldItem = &p->a[i];
71850 pNewItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
71851 pNewItem->idx = pOldItem->idx;
71853 return pNew;
71855 SQLITE_PRIVATE Select *sqlite3SelectDup(sqlite3 *db, Select *p, int flags){
71856 Select *pNew;
71857 if( p==0 ) return 0;
71858 pNew = sqlite3DbMallocRaw(db, sizeof(*p) );
71859 if( pNew==0 ) return 0;
71860 pNew->pEList = sqlite3ExprListDup(db, p->pEList, flags);
71861 pNew->pSrc = sqlite3SrcListDup(db, p->pSrc, flags);
71862 pNew->pWhere = sqlite3ExprDup(db, p->pWhere, flags);
71863 pNew->pGroupBy = sqlite3ExprListDup(db, p->pGroupBy, flags);
71864 pNew->pHaving = sqlite3ExprDup(db, p->pHaving, flags);
71865 pNew->pOrderBy = sqlite3ExprListDup(db, p->pOrderBy, flags);
71866 pNew->op = p->op;
71867 pNew->pPrior = sqlite3SelectDup(db, p->pPrior, flags);
71868 pNew->pLimit = sqlite3ExprDup(db, p->pLimit, flags);
71869 pNew->pOffset = sqlite3ExprDup(db, p->pOffset, flags);
71870 pNew->iLimit = 0;
71871 pNew->iOffset = 0;
71872 pNew->selFlags = p->selFlags & ~SF_UsesEphemeral;
71873 pNew->pRightmost = 0;
71874 pNew->addrOpenEphm[0] = -1;
71875 pNew->addrOpenEphm[1] = -1;
71876 pNew->addrOpenEphm[2] = -1;
71877 return pNew;
71879 #else
71880 SQLITE_PRIVATE Select *sqlite3SelectDup(sqlite3 *db, Select *p, int flags){
71881 assert( p==0 );
71882 return 0;
71884 #endif
71888 ** Add a new element to the end of an expression list. If pList is
71889 ** initially NULL, then create a new expression list.
71891 ** If a memory allocation error occurs, the entire list is freed and
71892 ** NULL is returned. If non-NULL is returned, then it is guaranteed
71893 ** that the new entry was successfully appended.
71895 SQLITE_PRIVATE ExprList *sqlite3ExprListAppend(
71896 Parse *pParse, /* Parsing context */
71897 ExprList *pList, /* List to which to append. Might be NULL */
71898 Expr *pExpr /* Expression to be appended. Might be NULL */
71900 sqlite3 *db = pParse->db;
71901 if( pList==0 ){
71902 pList = sqlite3DbMallocZero(db, sizeof(ExprList) );
71903 if( pList==0 ){
71904 goto no_mem;
71906 assert( pList->nAlloc==0 );
71908 if( pList->nAlloc<=pList->nExpr ){
71909 struct ExprList_item *a;
71910 int n = pList->nAlloc*2 + 4;
71911 a = sqlite3DbRealloc(db, pList->a, n*sizeof(pList->a[0]));
71912 if( a==0 ){
71913 goto no_mem;
71915 pList->a = a;
71916 pList->nAlloc = sqlite3DbMallocSize(db, a)/sizeof(a[0]);
71918 assert( pList->a!=0 );
71919 if( 1 ){
71920 struct ExprList_item *pItem = &pList->a[pList->nExpr++];
71921 memset(pItem, 0, sizeof(*pItem));
71922 pItem->pExpr = pExpr;
71924 return pList;
71926 no_mem:
71927 /* Avoid leaking memory if malloc has failed. */
71928 sqlite3ExprDelete(db, pExpr);
71929 sqlite3ExprListDelete(db, pList);
71930 return 0;
71934 ** Set the ExprList.a[].zName element of the most recently added item
71935 ** on the expression list.
71937 ** pList might be NULL following an OOM error. But pName should never be
71938 ** NULL. If a memory allocation fails, the pParse->db->mallocFailed flag
71939 ** is set.
71941 SQLITE_PRIVATE void sqlite3ExprListSetName(
71942 Parse *pParse, /* Parsing context */
71943 ExprList *pList, /* List to which to add the span. */
71944 Token *pName, /* Name to be added */
71945 int dequote /* True to cause the name to be dequoted */
71947 assert( pList!=0 || pParse->db->mallocFailed!=0 );
71948 if( pList ){
71949 struct ExprList_item *pItem;
71950 assert( pList->nExpr>0 );
71951 pItem = &pList->a[pList->nExpr-1];
71952 assert( pItem->zName==0 );
71953 pItem->zName = sqlite3DbStrNDup(pParse->db, pName->z, pName->n);
71954 if( dequote && pItem->zName ) sqlite3Dequote(pItem->zName);
71959 ** Set the ExprList.a[].zSpan element of the most recently added item
71960 ** on the expression list.
71962 ** pList might be NULL following an OOM error. But pSpan should never be
71963 ** NULL. If a memory allocation fails, the pParse->db->mallocFailed flag
71964 ** is set.
71966 SQLITE_PRIVATE void sqlite3ExprListSetSpan(
71967 Parse *pParse, /* Parsing context */
71968 ExprList *pList, /* List to which to add the span. */
71969 ExprSpan *pSpan /* The span to be added */
71971 sqlite3 *db = pParse->db;
71972 assert( pList!=0 || db->mallocFailed!=0 );
71973 if( pList ){
71974 struct ExprList_item *pItem = &pList->a[pList->nExpr-1];
71975 assert( pList->nExpr>0 );
71976 assert( db->mallocFailed || pItem->pExpr==pSpan->pExpr );
71977 sqlite3DbFree(db, pItem->zSpan);
71978 pItem->zSpan = sqlite3DbStrNDup(db, (char*)pSpan->zStart,
71979 (int)(pSpan->zEnd - pSpan->zStart));
71984 ** If the expression list pEList contains more than iLimit elements,
71985 ** leave an error message in pParse.
71987 SQLITE_PRIVATE void sqlite3ExprListCheckLength(
71988 Parse *pParse,
71989 ExprList *pEList,
71990 const char *zObject
71992 int mx = pParse->db->aLimit[SQLITE_LIMIT_COLUMN];
71993 testcase( pEList && pEList->nExpr==mx );
71994 testcase( pEList && pEList->nExpr==mx+1 );
71995 if( pEList && pEList->nExpr>mx ){
71996 sqlite3ErrorMsg(pParse, "too many columns in %s", zObject);
72001 ** Delete an entire expression list.
72003 SQLITE_PRIVATE void sqlite3ExprListDelete(sqlite3 *db, ExprList *pList){
72004 int i;
72005 struct ExprList_item *pItem;
72006 if( pList==0 ) return;
72007 assert( pList->a!=0 || (pList->nExpr==0 && pList->nAlloc==0) );
72008 assert( pList->nExpr<=pList->nAlloc );
72009 for(pItem=pList->a, i=0; i<pList->nExpr; i++, pItem++){
72010 sqlite3ExprDelete(db, pItem->pExpr);
72011 sqlite3DbFree(db, pItem->zName);
72012 sqlite3DbFree(db, pItem->zSpan);
72014 sqlite3DbFree(db, pList->a);
72015 sqlite3DbFree(db, pList);
72019 ** These routines are Walker callbacks. Walker.u.pi is a pointer
72020 ** to an integer. These routines are checking an expression to see
72021 ** if it is a constant. Set *Walker.u.pi to 0 if the expression is
72022 ** not constant.
72024 ** These callback routines are used to implement the following:
72026 ** sqlite3ExprIsConstant()
72027 ** sqlite3ExprIsConstantNotJoin()
72028 ** sqlite3ExprIsConstantOrFunction()
72031 static int exprNodeIsConstant(Walker *pWalker, Expr *pExpr){
72033 /* If pWalker->u.i is 3 then any term of the expression that comes from
72034 ** the ON or USING clauses of a join disqualifies the expression
72035 ** from being considered constant. */
72036 if( pWalker->u.i==3 && ExprHasAnyProperty(pExpr, EP_FromJoin) ){
72037 pWalker->u.i = 0;
72038 return WRC_Abort;
72041 switch( pExpr->op ){
72042 /* Consider functions to be constant if all their arguments are constant
72043 ** and pWalker->u.i==2 */
72044 case TK_FUNCTION:
72045 if( pWalker->u.i==2 ) return 0;
72046 /* Fall through */
72047 case TK_ID:
72048 case TK_COLUMN:
72049 case TK_AGG_FUNCTION:
72050 case TK_AGG_COLUMN:
72051 testcase( pExpr->op==TK_ID );
72052 testcase( pExpr->op==TK_COLUMN );
72053 testcase( pExpr->op==TK_AGG_FUNCTION );
72054 testcase( pExpr->op==TK_AGG_COLUMN );
72055 pWalker->u.i = 0;
72056 return WRC_Abort;
72057 default:
72058 testcase( pExpr->op==TK_SELECT ); /* selectNodeIsConstant will disallow */
72059 testcase( pExpr->op==TK_EXISTS ); /* selectNodeIsConstant will disallow */
72060 return WRC_Continue;
72063 static int selectNodeIsConstant(Walker *pWalker, Select *NotUsed){
72064 UNUSED_PARAMETER(NotUsed);
72065 pWalker->u.i = 0;
72066 return WRC_Abort;
72068 static int exprIsConst(Expr *p, int initFlag){
72069 Walker w;
72070 w.u.i = initFlag;
72071 w.xExprCallback = exprNodeIsConstant;
72072 w.xSelectCallback = selectNodeIsConstant;
72073 sqlite3WalkExpr(&w, p);
72074 return w.u.i;
72078 ** Walk an expression tree. Return 1 if the expression is constant
72079 ** and 0 if it involves variables or function calls.
72081 ** For the purposes of this function, a double-quoted string (ex: "abc")
72082 ** is considered a variable but a single-quoted string (ex: 'abc') is
72083 ** a constant.
72085 SQLITE_PRIVATE int sqlite3ExprIsConstant(Expr *p){
72086 return exprIsConst(p, 1);
72090 ** Walk an expression tree. Return 1 if the expression is constant
72091 ** that does no originate from the ON or USING clauses of a join.
72092 ** Return 0 if it involves variables or function calls or terms from
72093 ** an ON or USING clause.
72095 SQLITE_PRIVATE int sqlite3ExprIsConstantNotJoin(Expr *p){
72096 return exprIsConst(p, 3);
72100 ** Walk an expression tree. Return 1 if the expression is constant
72101 ** or a function call with constant arguments. Return and 0 if there
72102 ** are any variables.
72104 ** For the purposes of this function, a double-quoted string (ex: "abc")
72105 ** is considered a variable but a single-quoted string (ex: 'abc') is
72106 ** a constant.
72108 SQLITE_PRIVATE int sqlite3ExprIsConstantOrFunction(Expr *p){
72109 return exprIsConst(p, 2);
72113 ** If the expression p codes a constant integer that is small enough
72114 ** to fit in a 32-bit integer, return 1 and put the value of the integer
72115 ** in *pValue. If the expression is not an integer or if it is too big
72116 ** to fit in a signed 32-bit integer, return 0 and leave *pValue unchanged.
72118 SQLITE_PRIVATE int sqlite3ExprIsInteger(Expr *p, int *pValue){
72119 int rc = 0;
72121 /* If an expression is an integer literal that fits in a signed 32-bit
72122 ** integer, then the EP_IntValue flag will have already been set */
72123 assert( p->op!=TK_INTEGER || (p->flags & EP_IntValue)!=0
72124 || sqlite3GetInt32(p->u.zToken, &rc)==0 );
72126 if( p->flags & EP_IntValue ){
72127 *pValue = p->u.iValue;
72128 return 1;
72130 switch( p->op ){
72131 case TK_UPLUS: {
72132 rc = sqlite3ExprIsInteger(p->pLeft, pValue);
72133 break;
72135 case TK_UMINUS: {
72136 int v;
72137 if( sqlite3ExprIsInteger(p->pLeft, &v) ){
72138 *pValue = -v;
72139 rc = 1;
72141 break;
72143 default: break;
72145 return rc;
72149 ** Return FALSE if there is no chance that the expression can be NULL.
72151 ** If the expression might be NULL or if the expression is too complex
72152 ** to tell return TRUE.
72154 ** This routine is used as an optimization, to skip OP_IsNull opcodes
72155 ** when we know that a value cannot be NULL. Hence, a false positive
72156 ** (returning TRUE when in fact the expression can never be NULL) might
72157 ** be a small performance hit but is otherwise harmless. On the other
72158 ** hand, a false negative (returning FALSE when the result could be NULL)
72159 ** will likely result in an incorrect answer. So when in doubt, return
72160 ** TRUE.
72162 SQLITE_PRIVATE int sqlite3ExprCanBeNull(const Expr *p){
72163 u8 op;
72164 while( p->op==TK_UPLUS || p->op==TK_UMINUS ){ p = p->pLeft; }
72165 op = p->op;
72166 if( op==TK_REGISTER ) op = p->op2;
72167 switch( op ){
72168 case TK_INTEGER:
72169 case TK_STRING:
72170 case TK_FLOAT:
72171 case TK_BLOB:
72172 return 0;
72173 default:
72174 return 1;
72179 ** Generate an OP_IsNull instruction that tests register iReg and jumps
72180 ** to location iDest if the value in iReg is NULL. The value in iReg
72181 ** was computed by pExpr. If we can look at pExpr at compile-time and
72182 ** determine that it can never generate a NULL, then the OP_IsNull operation
72183 ** can be omitted.
72185 SQLITE_PRIVATE void sqlite3ExprCodeIsNullJump(
72186 Vdbe *v, /* The VDBE under construction */
72187 const Expr *pExpr, /* Only generate OP_IsNull if this expr can be NULL */
72188 int iReg, /* Test the value in this register for NULL */
72189 int iDest /* Jump here if the value is null */
72191 if( sqlite3ExprCanBeNull(pExpr) ){
72192 sqlite3VdbeAddOp2(v, OP_IsNull, iReg, iDest);
72197 ** Return TRUE if the given expression is a constant which would be
72198 ** unchanged by OP_Affinity with the affinity given in the second
72199 ** argument.
72201 ** This routine is used to determine if the OP_Affinity operation
72202 ** can be omitted. When in doubt return FALSE. A false negative
72203 ** is harmless. A false positive, however, can result in the wrong
72204 ** answer.
72206 SQLITE_PRIVATE int sqlite3ExprNeedsNoAffinityChange(const Expr *p, char aff){
72207 u8 op;
72208 if( aff==SQLITE_AFF_NONE ) return 1;
72209 while( p->op==TK_UPLUS || p->op==TK_UMINUS ){ p = p->pLeft; }
72210 op = p->op;
72211 if( op==TK_REGISTER ) op = p->op2;
72212 switch( op ){
72213 case TK_INTEGER: {
72214 return aff==SQLITE_AFF_INTEGER || aff==SQLITE_AFF_NUMERIC;
72216 case TK_FLOAT: {
72217 return aff==SQLITE_AFF_REAL || aff==SQLITE_AFF_NUMERIC;
72219 case TK_STRING: {
72220 return aff==SQLITE_AFF_TEXT;
72222 case TK_BLOB: {
72223 return 1;
72225 case TK_COLUMN: {
72226 assert( p->iTable>=0 ); /* p cannot be part of a CHECK constraint */
72227 return p->iColumn<0
72228 && (aff==SQLITE_AFF_INTEGER || aff==SQLITE_AFF_NUMERIC);
72230 default: {
72231 return 0;
72237 ** Return TRUE if the given string is a row-id column name.
72239 SQLITE_PRIVATE int sqlite3IsRowid(const char *z){
72240 if( sqlite3StrICmp(z, "_ROWID_")==0 ) return 1;
72241 if( sqlite3StrICmp(z, "ROWID")==0 ) return 1;
72242 if( sqlite3StrICmp(z, "OID")==0 ) return 1;
72243 return 0;
72247 ** Return true if we are able to the IN operator optimization on a
72248 ** query of the form
72250 ** x IN (SELECT ...)
72252 ** Where the SELECT... clause is as specified by the parameter to this
72253 ** routine.
72255 ** The Select object passed in has already been preprocessed and no
72256 ** errors have been found.
72258 #ifndef SQLITE_OMIT_SUBQUERY
72259 static int isCandidateForInOpt(Select *p){
72260 SrcList *pSrc;
72261 ExprList *pEList;
72262 Table *pTab;
72263 if( p==0 ) return 0; /* right-hand side of IN is SELECT */
72264 if( p->pPrior ) return 0; /* Not a compound SELECT */
72265 if( p->selFlags & (SF_Distinct|SF_Aggregate) ){
72266 testcase( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct );
72267 testcase( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Aggregate );
72268 return 0; /* No DISTINCT keyword and no aggregate functions */
72270 assert( p->pGroupBy==0 ); /* Has no GROUP BY clause */
72271 if( p->pLimit ) return 0; /* Has no LIMIT clause */
72272 assert( p->pOffset==0 ); /* No LIMIT means no OFFSET */
72273 if( p->pWhere ) return 0; /* Has no WHERE clause */
72274 pSrc = p->pSrc;
72275 assert( pSrc!=0 );
72276 if( pSrc->nSrc!=1 ) return 0; /* Single term in FROM clause */
72277 if( pSrc->a[0].pSelect ) return 0; /* FROM is not a subquery or view */
72278 pTab = pSrc->a[0].pTab;
72279 if( NEVER(pTab==0) ) return 0;
72280 assert( pTab->pSelect==0 ); /* FROM clause is not a view */
72281 if( IsVirtual(pTab) ) return 0; /* FROM clause not a virtual table */
72282 pEList = p->pEList;
72283 if( pEList->nExpr!=1 ) return 0; /* One column in the result set */
72284 if( pEList->a[0].pExpr->op!=TK_COLUMN ) return 0; /* Result is a column */
72285 return 1;
72287 #endif /* SQLITE_OMIT_SUBQUERY */
72290 ** This function is used by the implementation of the IN (...) operator.
72291 ** It's job is to find or create a b-tree structure that may be used
72292 ** either to test for membership of the (...) set or to iterate through
72293 ** its members, skipping duplicates.
72295 ** The index of the cursor opened on the b-tree (database table, database index
72296 ** or ephermal table) is stored in pX->iTable before this function returns.
72297 ** The returned value of this function indicates the b-tree type, as follows:
72299 ** IN_INDEX_ROWID - The cursor was opened on a database table.
72300 ** IN_INDEX_INDEX - The cursor was opened on a database index.
72301 ** IN_INDEX_EPH - The cursor was opened on a specially created and
72302 ** populated epheremal table.
72304 ** An existing b-tree may only be used if the SELECT is of the simple
72305 ** form:
72307 ** SELECT <column> FROM <table>
72309 ** If the prNotFound parameter is 0, then the b-tree will be used to iterate
72310 ** through the set members, skipping any duplicates. In this case an
72311 ** epheremal table must be used unless the selected <column> is guaranteed
72312 ** to be unique - either because it is an INTEGER PRIMARY KEY or it
72313 ** has a UNIQUE constraint or UNIQUE index.
72315 ** If the prNotFound parameter is not 0, then the b-tree will be used
72316 ** for fast set membership tests. In this case an epheremal table must
72317 ** be used unless <column> is an INTEGER PRIMARY KEY or an index can
72318 ** be found with <column> as its left-most column.
72320 ** When the b-tree is being used for membership tests, the calling function
72321 ** needs to know whether or not the structure contains an SQL NULL
72322 ** value in order to correctly evaluate expressions like "X IN (Y, Z)".
72323 ** If there is any chance that the (...) might contain a NULL value at
72324 ** runtime, then a register is allocated and the register number written
72325 ** to *prNotFound. If there is no chance that the (...) contains a
72326 ** NULL value, then *prNotFound is left unchanged.
72328 ** If a register is allocated and its location stored in *prNotFound, then
72329 ** its initial value is NULL. If the (...) does not remain constant
72330 ** for the duration of the query (i.e. the SELECT within the (...)
72331 ** is a correlated subquery) then the value of the allocated register is
72332 ** reset to NULL each time the subquery is rerun. This allows the
72333 ** caller to use vdbe code equivalent to the following:
72335 ** if( register==NULL ){
72336 ** has_null = <test if data structure contains null>
72337 ** register = 1
72338 ** }
72340 ** in order to avoid running the <test if data structure contains null>
72341 ** test more often than is necessary.
72343 #ifndef SQLITE_OMIT_SUBQUERY
72344 SQLITE_PRIVATE int sqlite3FindInIndex(Parse *pParse, Expr *pX, int *prNotFound){
72345 Select *p; /* SELECT to the right of IN operator */
72346 int eType = 0; /* Type of RHS table. IN_INDEX_* */
72347 int iTab = pParse->nTab++; /* Cursor of the RHS table */
72348 int mustBeUnique = (prNotFound==0); /* True if RHS must be unique */
72350 assert( pX->op==TK_IN );
72352 /* Check to see if an existing table or index can be used to
72353 ** satisfy the query. This is preferable to generating a new
72354 ** ephemeral table.
72356 p = (ExprHasProperty(pX, EP_xIsSelect) ? pX->x.pSelect : 0);
72357 if( ALWAYS(pParse->nErr==0) && isCandidateForInOpt(p) ){
72358 sqlite3 *db = pParse->db; /* Database connection */
72359 Expr *pExpr = p->pEList->a[0].pExpr; /* Expression <column> */
72360 int iCol = pExpr->iColumn; /* Index of column <column> */
72361 Vdbe *v = sqlite3GetVdbe(pParse); /* Virtual machine being coded */
72362 Table *pTab = p->pSrc->a[0].pTab; /* Table <table>. */
72363 int iDb; /* Database idx for pTab */
72365 /* Code an OP_VerifyCookie and OP_TableLock for <table>. */
72366 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
72367 sqlite3CodeVerifySchema(pParse, iDb);
72368 sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
72370 /* This function is only called from two places. In both cases the vdbe
72371 ** has already been allocated. So assume sqlite3GetVdbe() is always
72372 ** successful here.
72374 assert(v);
72375 if( iCol<0 ){
72376 int iMem = ++pParse->nMem;
72377 int iAddr;
72379 iAddr = sqlite3VdbeAddOp1(v, OP_If, iMem);
72380 sqlite3VdbeAddOp2(v, OP_Integer, 1, iMem);
72382 sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead);
72383 eType = IN_INDEX_ROWID;
72385 sqlite3VdbeJumpHere(v, iAddr);
72386 }else{
72387 Index *pIdx; /* Iterator variable */
72389 /* The collation sequence used by the comparison. If an index is to
72390 ** be used in place of a temp-table, it must be ordered according
72391 ** to this collation sequence. */
72392 CollSeq *pReq = sqlite3BinaryCompareCollSeq(pParse, pX->pLeft, pExpr);
72394 /* Check that the affinity that will be used to perform the
72395 ** comparison is the same as the affinity of the column. If
72396 ** it is not, it is not possible to use any index.
72398 char aff = comparisonAffinity(pX);
72399 int affinity_ok = (pTab->aCol[iCol].affinity==aff||aff==SQLITE_AFF_NONE);
72401 for(pIdx=pTab->pIndex; pIdx && eType==0 && affinity_ok; pIdx=pIdx->pNext){
72402 if( (pIdx->aiColumn[0]==iCol)
72403 && sqlite3FindCollSeq(db, ENC(db), pIdx->azColl[0], 0)==pReq
72404 && (!mustBeUnique || (pIdx->nColumn==1 && pIdx->onError!=OE_None))
72406 int iMem = ++pParse->nMem;
72407 int iAddr;
72408 char *pKey;
72410 pKey = (char *)sqlite3IndexKeyinfo(pParse, pIdx);
72411 iAddr = sqlite3VdbeAddOp1(v, OP_If, iMem);
72412 sqlite3VdbeAddOp2(v, OP_Integer, 1, iMem);
72414 sqlite3VdbeAddOp4(v, OP_OpenRead, iTab, pIdx->tnum, iDb,
72415 pKey,P4_KEYINFO_HANDOFF);
72416 VdbeComment((v, "%s", pIdx->zName));
72417 eType = IN_INDEX_INDEX;
72419 sqlite3VdbeJumpHere(v, iAddr);
72420 if( prNotFound && !pTab->aCol[iCol].notNull ){
72421 *prNotFound = ++pParse->nMem;
72428 if( eType==0 ){
72429 /* Could not found an existing table or index to use as the RHS b-tree.
72430 ** We will have to generate an ephemeral table to do the job.
72432 double savedNQueryLoop = pParse->nQueryLoop;
72433 int rMayHaveNull = 0;
72434 eType = IN_INDEX_EPH;
72435 if( prNotFound ){
72436 *prNotFound = rMayHaveNull = ++pParse->nMem;
72437 }else{
72438 testcase( pParse->nQueryLoop>(double)1 );
72439 pParse->nQueryLoop = (double)1;
72440 if( pX->pLeft->iColumn<0 && !ExprHasAnyProperty(pX, EP_xIsSelect) ){
72441 eType = IN_INDEX_ROWID;
72444 sqlite3CodeSubselect(pParse, pX, rMayHaveNull, eType==IN_INDEX_ROWID);
72445 pParse->nQueryLoop = savedNQueryLoop;
72446 }else{
72447 pX->iTable = iTab;
72449 return eType;
72451 #endif
72454 ** Generate code for scalar subqueries used as a subquery expression, EXISTS,
72455 ** or IN operators. Examples:
72457 ** (SELECT a FROM b) -- subquery
72458 ** EXISTS (SELECT a FROM b) -- EXISTS subquery
72459 ** x IN (4,5,11) -- IN operator with list on right-hand side
72460 ** x IN (SELECT a FROM b) -- IN operator with subquery on the right
72462 ** The pExpr parameter describes the expression that contains the IN
72463 ** operator or subquery.
72465 ** If parameter isRowid is non-zero, then expression pExpr is guaranteed
72466 ** to be of the form "<rowid> IN (?, ?, ?)", where <rowid> is a reference
72467 ** to some integer key column of a table B-Tree. In this case, use an
72468 ** intkey B-Tree to store the set of IN(...) values instead of the usual
72469 ** (slower) variable length keys B-Tree.
72471 ** If rMayHaveNull is non-zero, that means that the operation is an IN
72472 ** (not a SELECT or EXISTS) and that the RHS might contains NULLs.
72473 ** Furthermore, the IN is in a WHERE clause and that we really want
72474 ** to iterate over the RHS of the IN operator in order to quickly locate
72475 ** all corresponding LHS elements. All this routine does is initialize
72476 ** the register given by rMayHaveNull to NULL. Calling routines will take
72477 ** care of changing this register value to non-NULL if the RHS is NULL-free.
72479 ** If rMayHaveNull is zero, that means that the subquery is being used
72480 ** for membership testing only. There is no need to initialize any
72481 ** registers to indicate the presense or absence of NULLs on the RHS.
72483 ** For a SELECT or EXISTS operator, return the register that holds the
72484 ** result. For IN operators or if an error occurs, the return value is 0.
72486 #ifndef SQLITE_OMIT_SUBQUERY
72487 SQLITE_PRIVATE int sqlite3CodeSubselect(
72488 Parse *pParse, /* Parsing context */
72489 Expr *pExpr, /* The IN, SELECT, or EXISTS operator */
72490 int rMayHaveNull, /* Register that records whether NULLs exist in RHS */
72491 int isRowid /* If true, LHS of IN operator is a rowid */
72493 int testAddr = 0; /* One-time test address */
72494 int rReg = 0; /* Register storing resulting */
72495 Vdbe *v = sqlite3GetVdbe(pParse);
72496 if( NEVER(v==0) ) return 0;
72497 sqlite3ExprCachePush(pParse);
72499 /* This code must be run in its entirety every time it is encountered
72500 ** if any of the following is true:
72502 ** * The right-hand side is a correlated subquery
72503 ** * The right-hand side is an expression list containing variables
72504 ** * We are inside a trigger
72506 ** If all of the above are false, then we can run this code just once
72507 ** save the results, and reuse the same result on subsequent invocations.
72509 if( !ExprHasAnyProperty(pExpr, EP_VarSelect) && !pParse->pTriggerTab ){
72510 int mem = ++pParse->nMem;
72511 sqlite3VdbeAddOp1(v, OP_If, mem);
72512 testAddr = sqlite3VdbeAddOp2(v, OP_Integer, 1, mem);
72513 assert( testAddr>0 || pParse->db->mallocFailed );
72516 #ifndef SQLITE_OMIT_EXPLAIN
72517 if( pParse->explain==2 ){
72518 char *zMsg = sqlite3MPrintf(
72519 pParse->db, "EXECUTE %s%s SUBQUERY %d", testAddr?"":"CORRELATED ",
72520 pExpr->op==TK_IN?"LIST":"SCALAR", pParse->iNextSelectId
72522 sqlite3VdbeAddOp4(v, OP_Explain, pParse->iSelectId, 0, 0, zMsg, P4_DYNAMIC);
72524 #endif
72526 switch( pExpr->op ){
72527 case TK_IN: {
72528 char affinity; /* Affinity of the LHS of the IN */
72529 KeyInfo keyInfo; /* Keyinfo for the generated table */
72530 int addr; /* Address of OP_OpenEphemeral instruction */
72531 Expr *pLeft = pExpr->pLeft; /* the LHS of the IN operator */
72533 if( rMayHaveNull ){
72534 sqlite3VdbeAddOp2(v, OP_Null, 0, rMayHaveNull);
72537 affinity = sqlite3ExprAffinity(pLeft);
72539 /* Whether this is an 'x IN(SELECT...)' or an 'x IN(<exprlist>)'
72540 ** expression it is handled the same way. An ephemeral table is
72541 ** filled with single-field index keys representing the results
72542 ** from the SELECT or the <exprlist>.
72544 ** If the 'x' expression is a column value, or the SELECT...
72545 ** statement returns a column value, then the affinity of that
72546 ** column is used to build the index keys. If both 'x' and the
72547 ** SELECT... statement are columns, then numeric affinity is used
72548 ** if either column has NUMERIC or INTEGER affinity. If neither
72549 ** 'x' nor the SELECT... statement are columns, then numeric affinity
72550 ** is used.
72552 pExpr->iTable = pParse->nTab++;
72553 addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pExpr->iTable, !isRowid);
72554 if( rMayHaveNull==0 ) sqlite3VdbeChangeP5(v, BTREE_UNORDERED);
72555 memset(&keyInfo, 0, sizeof(keyInfo));
72556 keyInfo.nField = 1;
72558 if( ExprHasProperty(pExpr, EP_xIsSelect) ){
72559 /* Case 1: expr IN (SELECT ...)
72561 ** Generate code to write the results of the select into the temporary
72562 ** table allocated and opened above.
72564 SelectDest dest;
72565 ExprList *pEList;
72567 assert( !isRowid );
72568 sqlite3SelectDestInit(&dest, SRT_Set, pExpr->iTable);
72569 dest.affinity = (u8)affinity;
72570 assert( (pExpr->iTable&0x0000FFFF)==pExpr->iTable );
72571 pExpr->x.pSelect->iLimit = 0;
72572 if( sqlite3Select(pParse, pExpr->x.pSelect, &dest) ){
72573 return 0;
72575 pEList = pExpr->x.pSelect->pEList;
72576 if( ALWAYS(pEList!=0 && pEList->nExpr>0) ){
72577 keyInfo.aColl[0] = sqlite3BinaryCompareCollSeq(pParse, pExpr->pLeft,
72578 pEList->a[0].pExpr);
72580 }else if( ALWAYS(pExpr->x.pList!=0) ){
72581 /* Case 2: expr IN (exprlist)
72583 ** For each expression, build an index key from the evaluation and
72584 ** store it in the temporary table. If <expr> is a column, then use
72585 ** that columns affinity when building index keys. If <expr> is not
72586 ** a column, use numeric affinity.
72588 int i;
72589 ExprList *pList = pExpr->x.pList;
72590 struct ExprList_item *pItem;
72591 int r1, r2, r3;
72593 if( !affinity ){
72594 affinity = SQLITE_AFF_NONE;
72596 keyInfo.aColl[0] = sqlite3ExprCollSeq(pParse, pExpr->pLeft);
72598 /* Loop through each expression in <exprlist>. */
72599 r1 = sqlite3GetTempReg(pParse);
72600 r2 = sqlite3GetTempReg(pParse);
72601 sqlite3VdbeAddOp2(v, OP_Null, 0, r2);
72602 for(i=pList->nExpr, pItem=pList->a; i>0; i--, pItem++){
72603 Expr *pE2 = pItem->pExpr;
72604 int iValToIns;
72606 /* If the expression is not constant then we will need to
72607 ** disable the test that was generated above that makes sure
72608 ** this code only executes once. Because for a non-constant
72609 ** expression we need to rerun this code each time.
72611 if( testAddr && !sqlite3ExprIsConstant(pE2) ){
72612 sqlite3VdbeChangeToNoop(v, testAddr-1, 2);
72613 testAddr = 0;
72616 /* Evaluate the expression and insert it into the temp table */
72617 if( isRowid && sqlite3ExprIsInteger(pE2, &iValToIns) ){
72618 sqlite3VdbeAddOp3(v, OP_InsertInt, pExpr->iTable, r2, iValToIns);
72619 }else{
72620 r3 = sqlite3ExprCodeTarget(pParse, pE2, r1);
72621 if( isRowid ){
72622 sqlite3VdbeAddOp2(v, OP_MustBeInt, r3,
72623 sqlite3VdbeCurrentAddr(v)+2);
72624 sqlite3VdbeAddOp3(v, OP_Insert, pExpr->iTable, r2, r3);
72625 }else{
72626 sqlite3VdbeAddOp4(v, OP_MakeRecord, r3, 1, r2, &affinity, 1);
72627 sqlite3ExprCacheAffinityChange(pParse, r3, 1);
72628 sqlite3VdbeAddOp2(v, OP_IdxInsert, pExpr->iTable, r2);
72632 sqlite3ReleaseTempReg(pParse, r1);
72633 sqlite3ReleaseTempReg(pParse, r2);
72635 if( !isRowid ){
72636 sqlite3VdbeChangeP4(v, addr, (void *)&keyInfo, P4_KEYINFO);
72638 break;
72641 case TK_EXISTS:
72642 case TK_SELECT:
72643 default: {
72644 /* If this has to be a scalar SELECT. Generate code to put the
72645 ** value of this select in a memory cell and record the number
72646 ** of the memory cell in iColumn. If this is an EXISTS, write
72647 ** an integer 0 (not exists) or 1 (exists) into a memory cell
72648 ** and record that memory cell in iColumn.
72650 Select *pSel; /* SELECT statement to encode */
72651 SelectDest dest; /* How to deal with SELECt result */
72653 testcase( pExpr->op==TK_EXISTS );
72654 testcase( pExpr->op==TK_SELECT );
72655 assert( pExpr->op==TK_EXISTS || pExpr->op==TK_SELECT );
72657 assert( ExprHasProperty(pExpr, EP_xIsSelect) );
72658 pSel = pExpr->x.pSelect;
72659 sqlite3SelectDestInit(&dest, 0, ++pParse->nMem);
72660 if( pExpr->op==TK_SELECT ){
72661 dest.eDest = SRT_Mem;
72662 sqlite3VdbeAddOp2(v, OP_Null, 0, dest.iParm);
72663 VdbeComment((v, "Init subquery result"));
72664 }else{
72665 dest.eDest = SRT_Exists;
72666 sqlite3VdbeAddOp2(v, OP_Integer, 0, dest.iParm);
72667 VdbeComment((v, "Init EXISTS result"));
72669 sqlite3ExprDelete(pParse->db, pSel->pLimit);
72670 pSel->pLimit = sqlite3PExpr(pParse, TK_INTEGER, 0, 0,
72671 &sqlite3IntTokens[1]);
72672 pSel->iLimit = 0;
72673 if( sqlite3Select(pParse, pSel, &dest) ){
72674 return 0;
72676 rReg = dest.iParm;
72677 ExprSetIrreducible(pExpr);
72678 break;
72682 if( testAddr ){
72683 sqlite3VdbeJumpHere(v, testAddr-1);
72685 sqlite3ExprCachePop(pParse, 1);
72687 return rReg;
72689 #endif /* SQLITE_OMIT_SUBQUERY */
72691 #ifndef SQLITE_OMIT_SUBQUERY
72693 ** Generate code for an IN expression.
72695 ** x IN (SELECT ...)
72696 ** x IN (value, value, ...)
72698 ** The left-hand side (LHS) is a scalar expression. The right-hand side (RHS)
72699 ** is an array of zero or more values. The expression is true if the LHS is
72700 ** contained within the RHS. The value of the expression is unknown (NULL)
72701 ** if the LHS is NULL or if the LHS is not contained within the RHS and the
72702 ** RHS contains one or more NULL values.
72704 ** This routine generates code will jump to destIfFalse if the LHS is not
72705 ** contained within the RHS. If due to NULLs we cannot determine if the LHS
72706 ** is contained in the RHS then jump to destIfNull. If the LHS is contained
72707 ** within the RHS then fall through.
72709 static void sqlite3ExprCodeIN(
72710 Parse *pParse, /* Parsing and code generating context */
72711 Expr *pExpr, /* The IN expression */
72712 int destIfFalse, /* Jump here if LHS is not contained in the RHS */
72713 int destIfNull /* Jump here if the results are unknown due to NULLs */
72715 int rRhsHasNull = 0; /* Register that is true if RHS contains NULL values */
72716 char affinity; /* Comparison affinity to use */
72717 int eType; /* Type of the RHS */
72718 int r1; /* Temporary use register */
72719 Vdbe *v; /* Statement under construction */
72721 /* Compute the RHS. After this step, the table with cursor
72722 ** pExpr->iTable will contains the values that make up the RHS.
72724 v = pParse->pVdbe;
72725 assert( v!=0 ); /* OOM detected prior to this routine */
72726 VdbeNoopComment((v, "begin IN expr"));
72727 eType = sqlite3FindInIndex(pParse, pExpr, &rRhsHasNull);
72729 /* Figure out the affinity to use to create a key from the results
72730 ** of the expression. affinityStr stores a static string suitable for
72731 ** P4 of OP_MakeRecord.
72733 affinity = comparisonAffinity(pExpr);
72735 /* Code the LHS, the <expr> from "<expr> IN (...)".
72737 sqlite3ExprCachePush(pParse);
72738 r1 = sqlite3GetTempReg(pParse);
72739 sqlite3ExprCode(pParse, pExpr->pLeft, r1);
72741 /* If the LHS is NULL, then the result is either false or NULL depending
72742 ** on whether the RHS is empty or not, respectively.
72744 if( destIfNull==destIfFalse ){
72745 /* Shortcut for the common case where the false and NULL outcomes are
72746 ** the same. */
72747 sqlite3VdbeAddOp2(v, OP_IsNull, r1, destIfNull);
72748 }else{
72749 int addr1 = sqlite3VdbeAddOp1(v, OP_NotNull, r1);
72750 sqlite3VdbeAddOp2(v, OP_Rewind, pExpr->iTable, destIfFalse);
72751 sqlite3VdbeAddOp2(v, OP_Goto, 0, destIfNull);
72752 sqlite3VdbeJumpHere(v, addr1);
72755 if( eType==IN_INDEX_ROWID ){
72756 /* In this case, the RHS is the ROWID of table b-tree
72758 sqlite3VdbeAddOp2(v, OP_MustBeInt, r1, destIfFalse);
72759 sqlite3VdbeAddOp3(v, OP_NotExists, pExpr->iTable, destIfFalse, r1);
72760 }else{
72761 /* In this case, the RHS is an index b-tree.
72763 sqlite3VdbeAddOp4(v, OP_Affinity, r1, 1, 0, &affinity, 1);
72765 /* If the set membership test fails, then the result of the
72766 ** "x IN (...)" expression must be either 0 or NULL. If the set
72767 ** contains no NULL values, then the result is 0. If the set
72768 ** contains one or more NULL values, then the result of the
72769 ** expression is also NULL.
72771 if( rRhsHasNull==0 || destIfFalse==destIfNull ){
72772 /* This branch runs if it is known at compile time that the RHS
72773 ** cannot contain NULL values. This happens as the result
72774 ** of a "NOT NULL" constraint in the database schema.
72776 ** Also run this branch if NULL is equivalent to FALSE
72777 ** for this particular IN operator.
72779 sqlite3VdbeAddOp4Int(v, OP_NotFound, pExpr->iTable, destIfFalse, r1, 1);
72781 }else{
72782 /* In this branch, the RHS of the IN might contain a NULL and
72783 ** the presence of a NULL on the RHS makes a difference in the
72784 ** outcome.
72786 int j1, j2, j3;
72788 /* First check to see if the LHS is contained in the RHS. If so,
72789 ** then the presence of NULLs in the RHS does not matter, so jump
72790 ** over all of the code that follows.
72792 j1 = sqlite3VdbeAddOp4Int(v, OP_Found, pExpr->iTable, 0, r1, 1);
72794 /* Here we begin generating code that runs if the LHS is not
72795 ** contained within the RHS. Generate additional code that
72796 ** tests the RHS for NULLs. If the RHS contains a NULL then
72797 ** jump to destIfNull. If there are no NULLs in the RHS then
72798 ** jump to destIfFalse.
72800 j2 = sqlite3VdbeAddOp1(v, OP_NotNull, rRhsHasNull);
72801 j3 = sqlite3VdbeAddOp4Int(v, OP_Found, pExpr->iTable, 0, rRhsHasNull, 1);
72802 sqlite3VdbeAddOp2(v, OP_Integer, -1, rRhsHasNull);
72803 sqlite3VdbeJumpHere(v, j3);
72804 sqlite3VdbeAddOp2(v, OP_AddImm, rRhsHasNull, 1);
72805 sqlite3VdbeJumpHere(v, j2);
72807 /* Jump to the appropriate target depending on whether or not
72808 ** the RHS contains a NULL
72810 sqlite3VdbeAddOp2(v, OP_If, rRhsHasNull, destIfNull);
72811 sqlite3VdbeAddOp2(v, OP_Goto, 0, destIfFalse);
72813 /* The OP_Found at the top of this branch jumps here when true,
72814 ** causing the overall IN expression evaluation to fall through.
72816 sqlite3VdbeJumpHere(v, j1);
72819 sqlite3ReleaseTempReg(pParse, r1);
72820 sqlite3ExprCachePop(pParse, 1);
72821 VdbeComment((v, "end IN expr"));
72823 #endif /* SQLITE_OMIT_SUBQUERY */
72826 ** Duplicate an 8-byte value
72828 static char *dup8bytes(Vdbe *v, const char *in){
72829 char *out = sqlite3DbMallocRaw(sqlite3VdbeDb(v), 8);
72830 if( out ){
72831 memcpy(out, in, 8);
72833 return out;
72836 #ifndef SQLITE_OMIT_FLOATING_POINT
72838 ** Generate an instruction that will put the floating point
72839 ** value described by z[0..n-1] into register iMem.
72841 ** The z[] string will probably not be zero-terminated. But the
72842 ** z[n] character is guaranteed to be something that does not look
72843 ** like the continuation of the number.
72845 static void codeReal(Vdbe *v, const char *z, int negateFlag, int iMem){
72846 if( ALWAYS(z!=0) ){
72847 double value;
72848 char *zV;
72849 sqlite3AtoF(z, &value, sqlite3Strlen30(z), SQLITE_UTF8);
72850 assert( !sqlite3IsNaN(value) ); /* The new AtoF never returns NaN */
72851 if( negateFlag ) value = -value;
72852 zV = dup8bytes(v, (char*)&value);
72853 sqlite3VdbeAddOp4(v, OP_Real, 0, iMem, 0, zV, P4_REAL);
72856 #endif
72860 ** Generate an instruction that will put the integer describe by
72861 ** text z[0..n-1] into register iMem.
72863 ** Expr.u.zToken is always UTF8 and zero-terminated.
72865 static void codeInteger(Parse *pParse, Expr *pExpr, int negFlag, int iMem){
72866 Vdbe *v = pParse->pVdbe;
72867 if( pExpr->flags & EP_IntValue ){
72868 int i = pExpr->u.iValue;
72869 assert( i>=0 );
72870 if( negFlag ) i = -i;
72871 sqlite3VdbeAddOp2(v, OP_Integer, i, iMem);
72872 }else{
72873 int c;
72874 i64 value;
72875 const char *z = pExpr->u.zToken;
72876 assert( z!=0 );
72877 c = sqlite3Atoi64(z, &value, sqlite3Strlen30(z), SQLITE_UTF8);
72878 if( c==0 || (c==2 && negFlag) ){
72879 char *zV;
72880 if( negFlag ){ value = c==2 ? SMALLEST_INT64 : -value; }
72881 zV = dup8bytes(v, (char*)&value);
72882 sqlite3VdbeAddOp4(v, OP_Int64, 0, iMem, 0, zV, P4_INT64);
72883 }else{
72884 #ifdef SQLITE_OMIT_FLOATING_POINT
72885 sqlite3ErrorMsg(pParse, "oversized integer: %s%s", negFlag ? "-" : "", z);
72886 #else
72887 codeReal(v, z, negFlag, iMem);
72888 #endif
72894 ** Clear a cache entry.
72896 static void cacheEntryClear(Parse *pParse, struct yColCache *p){
72897 if( p->tempReg ){
72898 if( pParse->nTempReg<ArraySize(pParse->aTempReg) ){
72899 pParse->aTempReg[pParse->nTempReg++] = p->iReg;
72901 p->tempReg = 0;
72907 ** Record in the column cache that a particular column from a
72908 ** particular table is stored in a particular register.
72910 SQLITE_PRIVATE void sqlite3ExprCacheStore(Parse *pParse, int iTab, int iCol, int iReg){
72911 int i;
72912 int minLru;
72913 int idxLru;
72914 struct yColCache *p;
72916 assert( iReg>0 ); /* Register numbers are always positive */
72917 assert( iCol>=-1 && iCol<32768 ); /* Finite column numbers */
72919 /* The SQLITE_ColumnCache flag disables the column cache. This is used
72920 ** for testing only - to verify that SQLite always gets the same answer
72921 ** with and without the column cache.
72923 if( pParse->db->flags & SQLITE_ColumnCache ) return;
72925 /* First replace any existing entry.
72927 ** Actually, the way the column cache is currently used, we are guaranteed
72928 ** that the object will never already be in cache. Verify this guarantee.
72930 #ifndef NDEBUG
72931 for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
72932 #if 0 /* This code wold remove the entry from the cache if it existed */
72933 if( p->iReg && p->iTable==iTab && p->iColumn==iCol ){
72934 cacheEntryClear(pParse, p);
72935 p->iLevel = pParse->iCacheLevel;
72936 p->iReg = iReg;
72937 p->lru = pParse->iCacheCnt++;
72938 return;
72940 #endif
72941 assert( p->iReg==0 || p->iTable!=iTab || p->iColumn!=iCol );
72943 #endif
72945 /* Find an empty slot and replace it */
72946 for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
72947 if( p->iReg==0 ){
72948 p->iLevel = pParse->iCacheLevel;
72949 p->iTable = iTab;
72950 p->iColumn = iCol;
72951 p->iReg = iReg;
72952 p->tempReg = 0;
72953 p->lru = pParse->iCacheCnt++;
72954 return;
72958 /* Replace the last recently used */
72959 minLru = 0x7fffffff;
72960 idxLru = -1;
72961 for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
72962 if( p->lru<minLru ){
72963 idxLru = i;
72964 minLru = p->lru;
72967 if( ALWAYS(idxLru>=0) ){
72968 p = &pParse->aColCache[idxLru];
72969 p->iLevel = pParse->iCacheLevel;
72970 p->iTable = iTab;
72971 p->iColumn = iCol;
72972 p->iReg = iReg;
72973 p->tempReg = 0;
72974 p->lru = pParse->iCacheCnt++;
72975 return;
72980 ** Indicate that registers between iReg..iReg+nReg-1 are being overwritten.
72981 ** Purge the range of registers from the column cache.
72983 SQLITE_PRIVATE void sqlite3ExprCacheRemove(Parse *pParse, int iReg, int nReg){
72984 int i;
72985 int iLast = iReg + nReg - 1;
72986 struct yColCache *p;
72987 for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
72988 int r = p->iReg;
72989 if( r>=iReg && r<=iLast ){
72990 cacheEntryClear(pParse, p);
72991 p->iReg = 0;
72997 ** Remember the current column cache context. Any new entries added
72998 ** added to the column cache after this call are removed when the
72999 ** corresponding pop occurs.
73001 SQLITE_PRIVATE void sqlite3ExprCachePush(Parse *pParse){
73002 pParse->iCacheLevel++;
73006 ** Remove from the column cache any entries that were added since the
73007 ** the previous N Push operations. In other words, restore the cache
73008 ** to the state it was in N Pushes ago.
73010 SQLITE_PRIVATE void sqlite3ExprCachePop(Parse *pParse, int N){
73011 int i;
73012 struct yColCache *p;
73013 assert( N>0 );
73014 assert( pParse->iCacheLevel>=N );
73015 pParse->iCacheLevel -= N;
73016 for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
73017 if( p->iReg && p->iLevel>pParse->iCacheLevel ){
73018 cacheEntryClear(pParse, p);
73019 p->iReg = 0;
73025 ** When a cached column is reused, make sure that its register is
73026 ** no longer available as a temp register. ticket #3879: that same
73027 ** register might be in the cache in multiple places, so be sure to
73028 ** get them all.
73030 static void sqlite3ExprCachePinRegister(Parse *pParse, int iReg){
73031 int i;
73032 struct yColCache *p;
73033 for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
73034 if( p->iReg==iReg ){
73035 p->tempReg = 0;
73041 ** Generate code to extract the value of the iCol-th column of a table.
73043 SQLITE_PRIVATE void sqlite3ExprCodeGetColumnOfTable(
73044 Vdbe *v, /* The VDBE under construction */
73045 Table *pTab, /* The table containing the value */
73046 int iTabCur, /* The cursor for this table */
73047 int iCol, /* Index of the column to extract */
73048 int regOut /* Extract the valud into this register */
73050 if( iCol<0 || iCol==pTab->iPKey ){
73051 sqlite3VdbeAddOp2(v, OP_Rowid, iTabCur, regOut);
73052 }else{
73053 int op = IsVirtual(pTab) ? OP_VColumn : OP_Column;
73054 sqlite3VdbeAddOp3(v, op, iTabCur, iCol, regOut);
73056 if( iCol>=0 ){
73057 sqlite3ColumnDefault(v, pTab, iCol, regOut);
73062 ** Generate code that will extract the iColumn-th column from
73063 ** table pTab and store the column value in a register. An effort
73064 ** is made to store the column value in register iReg, but this is
73065 ** not guaranteed. The location of the column value is returned.
73067 ** There must be an open cursor to pTab in iTable when this routine
73068 ** is called. If iColumn<0 then code is generated that extracts the rowid.
73070 SQLITE_PRIVATE int sqlite3ExprCodeGetColumn(
73071 Parse *pParse, /* Parsing and code generating context */
73072 Table *pTab, /* Description of the table we are reading from */
73073 int iColumn, /* Index of the table column */
73074 int iTable, /* The cursor pointing to the table */
73075 int iReg /* Store results here */
73077 Vdbe *v = pParse->pVdbe;
73078 int i;
73079 struct yColCache *p;
73081 for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
73082 if( p->iReg>0 && p->iTable==iTable && p->iColumn==iColumn ){
73083 p->lru = pParse->iCacheCnt++;
73084 sqlite3ExprCachePinRegister(pParse, p->iReg);
73085 return p->iReg;
73088 assert( v!=0 );
73089 sqlite3ExprCodeGetColumnOfTable(v, pTab, iTable, iColumn, iReg);
73090 sqlite3ExprCacheStore(pParse, iTable, iColumn, iReg);
73091 return iReg;
73095 ** Clear all column cache entries.
73097 SQLITE_PRIVATE void sqlite3ExprCacheClear(Parse *pParse){
73098 int i;
73099 struct yColCache *p;
73101 for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
73102 if( p->iReg ){
73103 cacheEntryClear(pParse, p);
73104 p->iReg = 0;
73110 ** Record the fact that an affinity change has occurred on iCount
73111 ** registers starting with iStart.
73113 SQLITE_PRIVATE void sqlite3ExprCacheAffinityChange(Parse *pParse, int iStart, int iCount){
73114 sqlite3ExprCacheRemove(pParse, iStart, iCount);
73118 ** Generate code to move content from registers iFrom...iFrom+nReg-1
73119 ** over to iTo..iTo+nReg-1. Keep the column cache up-to-date.
73121 SQLITE_PRIVATE void sqlite3ExprCodeMove(Parse *pParse, int iFrom, int iTo, int nReg){
73122 int i;
73123 struct yColCache *p;
73124 if( NEVER(iFrom==iTo) ) return;
73125 sqlite3VdbeAddOp3(pParse->pVdbe, OP_Move, iFrom, iTo, nReg);
73126 for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
73127 int x = p->iReg;
73128 if( x>=iFrom && x<iFrom+nReg ){
73129 p->iReg += iTo-iFrom;
73135 ** Generate code to copy content from registers iFrom...iFrom+nReg-1
73136 ** over to iTo..iTo+nReg-1.
73138 SQLITE_PRIVATE void sqlite3ExprCodeCopy(Parse *pParse, int iFrom, int iTo, int nReg){
73139 int i;
73140 if( NEVER(iFrom==iTo) ) return;
73141 for(i=0; i<nReg; i++){
73142 sqlite3VdbeAddOp2(pParse->pVdbe, OP_Copy, iFrom+i, iTo+i);
73146 #if defined(SQLITE_DEBUG) || defined(SQLITE_COVERAGE_TEST)
73148 ** Return true if any register in the range iFrom..iTo (inclusive)
73149 ** is used as part of the column cache.
73151 ** This routine is used within assert() and testcase() macros only
73152 ** and does not appear in a normal build.
73154 static int usedAsColumnCache(Parse *pParse, int iFrom, int iTo){
73155 int i;
73156 struct yColCache *p;
73157 for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
73158 int r = p->iReg;
73159 if( r>=iFrom && r<=iTo ) return 1; /*NO_TEST*/
73161 return 0;
73163 #endif /* SQLITE_DEBUG || SQLITE_COVERAGE_TEST */
73166 ** Generate code into the current Vdbe to evaluate the given
73167 ** expression. Attempt to store the results in register "target".
73168 ** Return the register where results are stored.
73170 ** With this routine, there is no guarantee that results will
73171 ** be stored in target. The result might be stored in some other
73172 ** register if it is convenient to do so. The calling function
73173 ** must check the return code and move the results to the desired
73174 ** register.
73176 SQLITE_PRIVATE int sqlite3ExprCodeTarget(Parse *pParse, Expr *pExpr, int target){
73177 Vdbe *v = pParse->pVdbe; /* The VM under construction */
73178 int op; /* The opcode being coded */
73179 int inReg = target; /* Results stored in register inReg */
73180 int regFree1 = 0; /* If non-zero free this temporary register */
73181 int regFree2 = 0; /* If non-zero free this temporary register */
73182 int r1, r2, r3, r4; /* Various register numbers */
73183 sqlite3 *db = pParse->db; /* The database connection */
73185 assert( target>0 && target<=pParse->nMem );
73186 if( v==0 ){
73187 assert( pParse->db->mallocFailed );
73188 return 0;
73191 if( pExpr==0 ){
73192 op = TK_NULL;
73193 }else{
73194 op = pExpr->op;
73196 switch( op ){
73197 case TK_AGG_COLUMN: {
73198 AggInfo *pAggInfo = pExpr->pAggInfo;
73199 struct AggInfo_col *pCol = &pAggInfo->aCol[pExpr->iAgg];
73200 if( !pAggInfo->directMode ){
73201 assert( pCol->iMem>0 );
73202 inReg = pCol->iMem;
73203 break;
73204 }else if( pAggInfo->useSortingIdx ){
73205 sqlite3VdbeAddOp3(v, OP_Column, pAggInfo->sortingIdx,
73206 pCol->iSorterColumn, target);
73207 break;
73209 /* Otherwise, fall thru into the TK_COLUMN case */
73211 case TK_COLUMN: {
73212 if( pExpr->iTable<0 ){
73213 /* This only happens when coding check constraints */
73214 assert( pParse->ckBase>0 );
73215 inReg = pExpr->iColumn + pParse->ckBase;
73216 }else{
73217 inReg = sqlite3ExprCodeGetColumn(pParse, pExpr->pTab,
73218 pExpr->iColumn, pExpr->iTable, target);
73220 break;
73222 case TK_INTEGER: {
73223 codeInteger(pParse, pExpr, 0, target);
73224 break;
73226 #ifndef SQLITE_OMIT_FLOATING_POINT
73227 case TK_FLOAT: {
73228 assert( !ExprHasProperty(pExpr, EP_IntValue) );
73229 codeReal(v, pExpr->u.zToken, 0, target);
73230 break;
73232 #endif
73233 case TK_STRING: {
73234 assert( !ExprHasProperty(pExpr, EP_IntValue) );
73235 sqlite3VdbeAddOp4(v, OP_String8, 0, target, 0, pExpr->u.zToken, 0);
73236 break;
73238 case TK_NULL: {
73239 sqlite3VdbeAddOp2(v, OP_Null, 0, target);
73240 break;
73242 #ifndef SQLITE_OMIT_BLOB_LITERAL
73243 case TK_BLOB: {
73244 int n;
73245 const char *z;
73246 char *zBlob;
73247 assert( !ExprHasProperty(pExpr, EP_IntValue) );
73248 assert( pExpr->u.zToken[0]=='x' || pExpr->u.zToken[0]=='X' );
73249 assert( pExpr->u.zToken[1]=='\'' );
73250 z = &pExpr->u.zToken[2];
73251 n = sqlite3Strlen30(z) - 1;
73252 assert( z[n]=='\'' );
73253 zBlob = sqlite3HexToBlob(sqlite3VdbeDb(v), z, n);
73254 sqlite3VdbeAddOp4(v, OP_Blob, n/2, target, 0, zBlob, P4_DYNAMIC);
73255 break;
73257 #endif
73258 case TK_VARIABLE: {
73259 assert( !ExprHasProperty(pExpr, EP_IntValue) );
73260 assert( pExpr->u.zToken!=0 );
73261 assert( pExpr->u.zToken[0]!=0 );
73262 sqlite3VdbeAddOp2(v, OP_Variable, pExpr->iColumn, target);
73263 if( pExpr->u.zToken[1]!=0 ){
73264 sqlite3VdbeChangeP4(v, -1, pExpr->u.zToken, P4_TRANSIENT);
73266 break;
73268 case TK_REGISTER: {
73269 inReg = pExpr->iTable;
73270 break;
73272 case TK_AS: {
73273 inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
73274 break;
73276 #ifndef SQLITE_OMIT_CAST
73277 case TK_CAST: {
73278 /* Expressions of the form: CAST(pLeft AS token) */
73279 int aff, to_op;
73280 inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
73281 assert( !ExprHasProperty(pExpr, EP_IntValue) );
73282 aff = sqlite3AffinityType(pExpr->u.zToken);
73283 to_op = aff - SQLITE_AFF_TEXT + OP_ToText;
73284 assert( to_op==OP_ToText || aff!=SQLITE_AFF_TEXT );
73285 assert( to_op==OP_ToBlob || aff!=SQLITE_AFF_NONE );
73286 assert( to_op==OP_ToNumeric || aff!=SQLITE_AFF_NUMERIC );
73287 assert( to_op==OP_ToInt || aff!=SQLITE_AFF_INTEGER );
73288 assert( to_op==OP_ToReal || aff!=SQLITE_AFF_REAL );
73289 testcase( to_op==OP_ToText );
73290 testcase( to_op==OP_ToBlob );
73291 testcase( to_op==OP_ToNumeric );
73292 testcase( to_op==OP_ToInt );
73293 testcase( to_op==OP_ToReal );
73294 if( inReg!=target ){
73295 sqlite3VdbeAddOp2(v, OP_SCopy, inReg, target);
73296 inReg = target;
73298 sqlite3VdbeAddOp1(v, to_op, inReg);
73299 testcase( usedAsColumnCache(pParse, inReg, inReg) );
73300 sqlite3ExprCacheAffinityChange(pParse, inReg, 1);
73301 break;
73303 #endif /* SQLITE_OMIT_CAST */
73304 case TK_LT:
73305 case TK_LE:
73306 case TK_GT:
73307 case TK_GE:
73308 case TK_NE:
73309 case TK_EQ: {
73310 assert( TK_LT==OP_Lt );
73311 assert( TK_LE==OP_Le );
73312 assert( TK_GT==OP_Gt );
73313 assert( TK_GE==OP_Ge );
73314 assert( TK_EQ==OP_Eq );
73315 assert( TK_NE==OP_Ne );
73316 testcase( op==TK_LT );
73317 testcase( op==TK_LE );
73318 testcase( op==TK_GT );
73319 testcase( op==TK_GE );
73320 testcase( op==TK_EQ );
73321 testcase( op==TK_NE );
73322 r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
73323 r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
73324 codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
73325 r1, r2, inReg, SQLITE_STOREP2);
73326 testcase( regFree1==0 );
73327 testcase( regFree2==0 );
73328 break;
73330 case TK_IS:
73331 case TK_ISNOT: {
73332 testcase( op==TK_IS );
73333 testcase( op==TK_ISNOT );
73334 r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
73335 r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
73336 op = (op==TK_IS) ? TK_EQ : TK_NE;
73337 codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
73338 r1, r2, inReg, SQLITE_STOREP2 | SQLITE_NULLEQ);
73339 testcase( regFree1==0 );
73340 testcase( regFree2==0 );
73341 break;
73343 case TK_AND:
73344 case TK_OR:
73345 case TK_PLUS:
73346 case TK_STAR:
73347 case TK_MINUS:
73348 case TK_REM:
73349 case TK_BITAND:
73350 case TK_BITOR:
73351 case TK_SLASH:
73352 case TK_LSHIFT:
73353 case TK_RSHIFT:
73354 case TK_CONCAT: {
73355 assert( TK_AND==OP_And );
73356 assert( TK_OR==OP_Or );
73357 assert( TK_PLUS==OP_Add );
73358 assert( TK_MINUS==OP_Subtract );
73359 assert( TK_REM==OP_Remainder );
73360 assert( TK_BITAND==OP_BitAnd );
73361 assert( TK_BITOR==OP_BitOr );
73362 assert( TK_SLASH==OP_Divide );
73363 assert( TK_LSHIFT==OP_ShiftLeft );
73364 assert( TK_RSHIFT==OP_ShiftRight );
73365 assert( TK_CONCAT==OP_Concat );
73366 testcase( op==TK_AND );
73367 testcase( op==TK_OR );
73368 testcase( op==TK_PLUS );
73369 testcase( op==TK_MINUS );
73370 testcase( op==TK_REM );
73371 testcase( op==TK_BITAND );
73372 testcase( op==TK_BITOR );
73373 testcase( op==TK_SLASH );
73374 testcase( op==TK_LSHIFT );
73375 testcase( op==TK_RSHIFT );
73376 testcase( op==TK_CONCAT );
73377 r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
73378 r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
73379 sqlite3VdbeAddOp3(v, op, r2, r1, target);
73380 testcase( regFree1==0 );
73381 testcase( regFree2==0 );
73382 break;
73384 case TK_UMINUS: {
73385 Expr *pLeft = pExpr->pLeft;
73386 assert( pLeft );
73387 if( pLeft->op==TK_INTEGER ){
73388 codeInteger(pParse, pLeft, 1, target);
73389 #ifndef SQLITE_OMIT_FLOATING_POINT
73390 }else if( pLeft->op==TK_FLOAT ){
73391 assert( !ExprHasProperty(pExpr, EP_IntValue) );
73392 codeReal(v, pLeft->u.zToken, 1, target);
73393 #endif
73394 }else{
73395 regFree1 = r1 = sqlite3GetTempReg(pParse);
73396 sqlite3VdbeAddOp2(v, OP_Integer, 0, r1);
73397 r2 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree2);
73398 sqlite3VdbeAddOp3(v, OP_Subtract, r2, r1, target);
73399 testcase( regFree2==0 );
73401 inReg = target;
73402 break;
73404 case TK_BITNOT:
73405 case TK_NOT: {
73406 assert( TK_BITNOT==OP_BitNot );
73407 assert( TK_NOT==OP_Not );
73408 testcase( op==TK_BITNOT );
73409 testcase( op==TK_NOT );
73410 r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
73411 testcase( regFree1==0 );
73412 inReg = target;
73413 sqlite3VdbeAddOp2(v, op, r1, inReg);
73414 break;
73416 case TK_ISNULL:
73417 case TK_NOTNULL: {
73418 int addr;
73419 assert( TK_ISNULL==OP_IsNull );
73420 assert( TK_NOTNULL==OP_NotNull );
73421 testcase( op==TK_ISNULL );
73422 testcase( op==TK_NOTNULL );
73423 sqlite3VdbeAddOp2(v, OP_Integer, 1, target);
73424 r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
73425 testcase( regFree1==0 );
73426 addr = sqlite3VdbeAddOp1(v, op, r1);
73427 sqlite3VdbeAddOp2(v, OP_AddImm, target, -1);
73428 sqlite3VdbeJumpHere(v, addr);
73429 break;
73431 case TK_AGG_FUNCTION: {
73432 AggInfo *pInfo = pExpr->pAggInfo;
73433 if( pInfo==0 ){
73434 assert( !ExprHasProperty(pExpr, EP_IntValue) );
73435 sqlite3ErrorMsg(pParse, "misuse of aggregate: %s()", pExpr->u.zToken);
73436 }else{
73437 inReg = pInfo->aFunc[pExpr->iAgg].iMem;
73439 break;
73441 case TK_CONST_FUNC:
73442 case TK_FUNCTION: {
73443 ExprList *pFarg; /* List of function arguments */
73444 int nFarg; /* Number of function arguments */
73445 FuncDef *pDef; /* The function definition object */
73446 int nId; /* Length of the function name in bytes */
73447 const char *zId; /* The function name */
73448 int constMask = 0; /* Mask of function arguments that are constant */
73449 int i; /* Loop counter */
73450 u8 enc = ENC(db); /* The text encoding used by this database */
73451 CollSeq *pColl = 0; /* A collating sequence */
73453 assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
73454 testcase( op==TK_CONST_FUNC );
73455 testcase( op==TK_FUNCTION );
73456 if( ExprHasAnyProperty(pExpr, EP_TokenOnly) ){
73457 pFarg = 0;
73458 }else{
73459 pFarg = pExpr->x.pList;
73461 nFarg = pFarg ? pFarg->nExpr : 0;
73462 assert( !ExprHasProperty(pExpr, EP_IntValue) );
73463 zId = pExpr->u.zToken;
73464 nId = sqlite3Strlen30(zId);
73465 pDef = sqlite3FindFunction(db, zId, nId, nFarg, enc, 0);
73466 if( pDef==0 ){
73467 sqlite3ErrorMsg(pParse, "unknown function: %.*s()", nId, zId);
73468 break;
73471 /* Attempt a direct implementation of the built-in COALESCE() and
73472 ** IFNULL() functions. This avoids unnecessary evalation of
73473 ** arguments past the first non-NULL argument.
73475 if( pDef->flags & SQLITE_FUNC_COALESCE ){
73476 int endCoalesce = sqlite3VdbeMakeLabel(v);
73477 assert( nFarg>=2 );
73478 sqlite3ExprCode(pParse, pFarg->a[0].pExpr, target);
73479 for(i=1; i<nFarg; i++){
73480 sqlite3VdbeAddOp2(v, OP_NotNull, target, endCoalesce);
73481 sqlite3ExprCacheRemove(pParse, target, 1);
73482 sqlite3ExprCachePush(pParse);
73483 sqlite3ExprCode(pParse, pFarg->a[i].pExpr, target);
73484 sqlite3ExprCachePop(pParse, 1);
73486 sqlite3VdbeResolveLabel(v, endCoalesce);
73487 break;
73491 if( pFarg ){
73492 r1 = sqlite3GetTempRange(pParse, nFarg);
73493 sqlite3ExprCachePush(pParse); /* Ticket 2ea2425d34be */
73494 sqlite3ExprCodeExprList(pParse, pFarg, r1, 1);
73495 sqlite3ExprCachePop(pParse, 1); /* Ticket 2ea2425d34be */
73496 }else{
73497 r1 = 0;
73499 #ifndef SQLITE_OMIT_VIRTUALTABLE
73500 /* Possibly overload the function if the first argument is
73501 ** a virtual table column.
73503 ** For infix functions (LIKE, GLOB, REGEXP, and MATCH) use the
73504 ** second argument, not the first, as the argument to test to
73505 ** see if it is a column in a virtual table. This is done because
73506 ** the left operand of infix functions (the operand we want to
73507 ** control overloading) ends up as the second argument to the
73508 ** function. The expression "A glob B" is equivalent to
73509 ** "glob(B,A). We want to use the A in "A glob B" to test
73510 ** for function overloading. But we use the B term in "glob(B,A)".
73512 if( nFarg>=2 && (pExpr->flags & EP_InfixFunc) ){
73513 pDef = sqlite3VtabOverloadFunction(db, pDef, nFarg, pFarg->a[1].pExpr);
73514 }else if( nFarg>0 ){
73515 pDef = sqlite3VtabOverloadFunction(db, pDef, nFarg, pFarg->a[0].pExpr);
73517 #endif
73518 for(i=0; i<nFarg; i++){
73519 if( i<32 && sqlite3ExprIsConstant(pFarg->a[i].pExpr) ){
73520 constMask |= (1<<i);
73522 if( (pDef->flags & SQLITE_FUNC_NEEDCOLL)!=0 && !pColl ){
73523 pColl = sqlite3ExprCollSeq(pParse, pFarg->a[i].pExpr);
73526 if( pDef->flags & SQLITE_FUNC_NEEDCOLL ){
73527 if( !pColl ) pColl = db->pDfltColl;
73528 sqlite3VdbeAddOp4(v, OP_CollSeq, 0, 0, 0, (char *)pColl, P4_COLLSEQ);
73530 sqlite3VdbeAddOp4(v, OP_Function, constMask, r1, target,
73531 (char*)pDef, P4_FUNCDEF);
73532 sqlite3VdbeChangeP5(v, (u8)nFarg);
73533 if( nFarg ){
73534 sqlite3ReleaseTempRange(pParse, r1, nFarg);
73536 break;
73538 #ifndef SQLITE_OMIT_SUBQUERY
73539 case TK_EXISTS:
73540 case TK_SELECT: {
73541 testcase( op==TK_EXISTS );
73542 testcase( op==TK_SELECT );
73543 inReg = sqlite3CodeSubselect(pParse, pExpr, 0, 0);
73544 break;
73546 case TK_IN: {
73547 int destIfFalse = sqlite3VdbeMakeLabel(v);
73548 int destIfNull = sqlite3VdbeMakeLabel(v);
73549 sqlite3VdbeAddOp2(v, OP_Null, 0, target);
73550 sqlite3ExprCodeIN(pParse, pExpr, destIfFalse, destIfNull);
73551 sqlite3VdbeAddOp2(v, OP_Integer, 1, target);
73552 sqlite3VdbeResolveLabel(v, destIfFalse);
73553 sqlite3VdbeAddOp2(v, OP_AddImm, target, 0);
73554 sqlite3VdbeResolveLabel(v, destIfNull);
73555 break;
73557 #endif /* SQLITE_OMIT_SUBQUERY */
73561 ** x BETWEEN y AND z
73563 ** This is equivalent to
73565 ** x>=y AND x<=z
73567 ** X is stored in pExpr->pLeft.
73568 ** Y is stored in pExpr->pList->a[0].pExpr.
73569 ** Z is stored in pExpr->pList->a[1].pExpr.
73571 case TK_BETWEEN: {
73572 Expr *pLeft = pExpr->pLeft;
73573 struct ExprList_item *pLItem = pExpr->x.pList->a;
73574 Expr *pRight = pLItem->pExpr;
73576 r1 = sqlite3ExprCodeTemp(pParse, pLeft, &regFree1);
73577 r2 = sqlite3ExprCodeTemp(pParse, pRight, &regFree2);
73578 testcase( regFree1==0 );
73579 testcase( regFree2==0 );
73580 r3 = sqlite3GetTempReg(pParse);
73581 r4 = sqlite3GetTempReg(pParse);
73582 codeCompare(pParse, pLeft, pRight, OP_Ge,
73583 r1, r2, r3, SQLITE_STOREP2);
73584 pLItem++;
73585 pRight = pLItem->pExpr;
73586 sqlite3ReleaseTempReg(pParse, regFree2);
73587 r2 = sqlite3ExprCodeTemp(pParse, pRight, &regFree2);
73588 testcase( regFree2==0 );
73589 codeCompare(pParse, pLeft, pRight, OP_Le, r1, r2, r4, SQLITE_STOREP2);
73590 sqlite3VdbeAddOp3(v, OP_And, r3, r4, target);
73591 sqlite3ReleaseTempReg(pParse, r3);
73592 sqlite3ReleaseTempReg(pParse, r4);
73593 break;
73595 case TK_UPLUS: {
73596 inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
73597 break;
73600 case TK_TRIGGER: {
73601 /* If the opcode is TK_TRIGGER, then the expression is a reference
73602 ** to a column in the new.* or old.* pseudo-tables available to
73603 ** trigger programs. In this case Expr.iTable is set to 1 for the
73604 ** new.* pseudo-table, or 0 for the old.* pseudo-table. Expr.iColumn
73605 ** is set to the column of the pseudo-table to read, or to -1 to
73606 ** read the rowid field.
73608 ** The expression is implemented using an OP_Param opcode. The p1
73609 ** parameter is set to 0 for an old.rowid reference, or to (i+1)
73610 ** to reference another column of the old.* pseudo-table, where
73611 ** i is the index of the column. For a new.rowid reference, p1 is
73612 ** set to (n+1), where n is the number of columns in each pseudo-table.
73613 ** For a reference to any other column in the new.* pseudo-table, p1
73614 ** is set to (n+2+i), where n and i are as defined previously. For
73615 ** example, if the table on which triggers are being fired is
73616 ** declared as:
73618 ** CREATE TABLE t1(a, b);
73620 ** Then p1 is interpreted as follows:
73622 ** p1==0 -> old.rowid p1==3 -> new.rowid
73623 ** p1==1 -> old.a p1==4 -> new.a
73624 ** p1==2 -> old.b p1==5 -> new.b
73626 Table *pTab = pExpr->pTab;
73627 int p1 = pExpr->iTable * (pTab->nCol+1) + 1 + pExpr->iColumn;
73629 assert( pExpr->iTable==0 || pExpr->iTable==1 );
73630 assert( pExpr->iColumn>=-1 && pExpr->iColumn<pTab->nCol );
73631 assert( pTab->iPKey<0 || pExpr->iColumn!=pTab->iPKey );
73632 assert( p1>=0 && p1<(pTab->nCol*2+2) );
73634 sqlite3VdbeAddOp2(v, OP_Param, p1, target);
73635 VdbeComment((v, "%s.%s -> $%d",
73636 (pExpr->iTable ? "new" : "old"),
73637 (pExpr->iColumn<0 ? "rowid" : pExpr->pTab->aCol[pExpr->iColumn].zName),
73638 target
73641 #ifndef SQLITE_OMIT_FLOATING_POINT
73642 /* If the column has REAL affinity, it may currently be stored as an
73643 ** integer. Use OP_RealAffinity to make sure it is really real. */
73644 if( pExpr->iColumn>=0
73645 && pTab->aCol[pExpr->iColumn].affinity==SQLITE_AFF_REAL
73647 sqlite3VdbeAddOp1(v, OP_RealAffinity, target);
73649 #endif
73650 break;
73655 ** Form A:
73656 ** CASE x WHEN e1 THEN r1 WHEN e2 THEN r2 ... WHEN eN THEN rN ELSE y END
73658 ** Form B:
73659 ** CASE WHEN e1 THEN r1 WHEN e2 THEN r2 ... WHEN eN THEN rN ELSE y END
73661 ** Form A is can be transformed into the equivalent form B as follows:
73662 ** CASE WHEN x=e1 THEN r1 WHEN x=e2 THEN r2 ...
73663 ** WHEN x=eN THEN rN ELSE y END
73665 ** X (if it exists) is in pExpr->pLeft.
73666 ** Y is in pExpr->pRight. The Y is also optional. If there is no
73667 ** ELSE clause and no other term matches, then the result of the
73668 ** exprssion is NULL.
73669 ** Ei is in pExpr->pList->a[i*2] and Ri is pExpr->pList->a[i*2+1].
73671 ** The result of the expression is the Ri for the first matching Ei,
73672 ** or if there is no matching Ei, the ELSE term Y, or if there is
73673 ** no ELSE term, NULL.
73675 default: assert( op==TK_CASE ); {
73676 int endLabel; /* GOTO label for end of CASE stmt */
73677 int nextCase; /* GOTO label for next WHEN clause */
73678 int nExpr; /* 2x number of WHEN terms */
73679 int i; /* Loop counter */
73680 ExprList *pEList; /* List of WHEN terms */
73681 struct ExprList_item *aListelem; /* Array of WHEN terms */
73682 Expr opCompare; /* The X==Ei expression */
73683 Expr cacheX; /* Cached expression X */
73684 Expr *pX; /* The X expression */
73685 Expr *pTest = 0; /* X==Ei (form A) or just Ei (form B) */
73686 VVA_ONLY( int iCacheLevel = pParse->iCacheLevel; )
73688 assert( !ExprHasProperty(pExpr, EP_xIsSelect) && pExpr->x.pList );
73689 assert((pExpr->x.pList->nExpr % 2) == 0);
73690 assert(pExpr->x.pList->nExpr > 0);
73691 pEList = pExpr->x.pList;
73692 aListelem = pEList->a;
73693 nExpr = pEList->nExpr;
73694 endLabel = sqlite3VdbeMakeLabel(v);
73695 if( (pX = pExpr->pLeft)!=0 ){
73696 cacheX = *pX;
73697 testcase( pX->op==TK_COLUMN );
73698 testcase( pX->op==TK_REGISTER );
73699 cacheX.iTable = sqlite3ExprCodeTemp(pParse, pX, &regFree1);
73700 testcase( regFree1==0 );
73701 cacheX.op = TK_REGISTER;
73702 opCompare.op = TK_EQ;
73703 opCompare.pLeft = &cacheX;
73704 pTest = &opCompare;
73705 /* Ticket b351d95f9cd5ef17e9d9dbae18f5ca8611190001:
73706 ** The value in regFree1 might get SCopy-ed into the file result.
73707 ** So make sure that the regFree1 register is not reused for other
73708 ** purposes and possibly overwritten. */
73709 regFree1 = 0;
73711 for(i=0; i<nExpr; i=i+2){
73712 sqlite3ExprCachePush(pParse);
73713 if( pX ){
73714 assert( pTest!=0 );
73715 opCompare.pRight = aListelem[i].pExpr;
73716 }else{
73717 pTest = aListelem[i].pExpr;
73719 nextCase = sqlite3VdbeMakeLabel(v);
73720 testcase( pTest->op==TK_COLUMN );
73721 sqlite3ExprIfFalse(pParse, pTest, nextCase, SQLITE_JUMPIFNULL);
73722 testcase( aListelem[i+1].pExpr->op==TK_COLUMN );
73723 testcase( aListelem[i+1].pExpr->op==TK_REGISTER );
73724 sqlite3ExprCode(pParse, aListelem[i+1].pExpr, target);
73725 sqlite3VdbeAddOp2(v, OP_Goto, 0, endLabel);
73726 sqlite3ExprCachePop(pParse, 1);
73727 sqlite3VdbeResolveLabel(v, nextCase);
73729 if( pExpr->pRight ){
73730 sqlite3ExprCachePush(pParse);
73731 sqlite3ExprCode(pParse, pExpr->pRight, target);
73732 sqlite3ExprCachePop(pParse, 1);
73733 }else{
73734 sqlite3VdbeAddOp2(v, OP_Null, 0, target);
73736 assert( db->mallocFailed || pParse->nErr>0
73737 || pParse->iCacheLevel==iCacheLevel );
73738 sqlite3VdbeResolveLabel(v, endLabel);
73739 break;
73741 #ifndef SQLITE_OMIT_TRIGGER
73742 case TK_RAISE: {
73743 assert( pExpr->affinity==OE_Rollback
73744 || pExpr->affinity==OE_Abort
73745 || pExpr->affinity==OE_Fail
73746 || pExpr->affinity==OE_Ignore
73748 if( !pParse->pTriggerTab ){
73749 sqlite3ErrorMsg(pParse,
73750 "RAISE() may only be used within a trigger-program");
73751 return 0;
73753 if( pExpr->affinity==OE_Abort ){
73754 sqlite3MayAbort(pParse);
73756 assert( !ExprHasProperty(pExpr, EP_IntValue) );
73757 if( pExpr->affinity==OE_Ignore ){
73758 sqlite3VdbeAddOp4(
73759 v, OP_Halt, SQLITE_OK, OE_Ignore, 0, pExpr->u.zToken,0);
73760 }else{
73761 sqlite3HaltConstraint(pParse, pExpr->affinity, pExpr->u.zToken, 0);
73764 break;
73766 #endif
73768 sqlite3ReleaseTempReg(pParse, regFree1);
73769 sqlite3ReleaseTempReg(pParse, regFree2);
73770 return inReg;
73774 ** Generate code to evaluate an expression and store the results
73775 ** into a register. Return the register number where the results
73776 ** are stored.
73778 ** If the register is a temporary register that can be deallocated,
73779 ** then write its number into *pReg. If the result register is not
73780 ** a temporary, then set *pReg to zero.
73782 SQLITE_PRIVATE int sqlite3ExprCodeTemp(Parse *pParse, Expr *pExpr, int *pReg){
73783 int r1 = sqlite3GetTempReg(pParse);
73784 int r2 = sqlite3ExprCodeTarget(pParse, pExpr, r1);
73785 if( r2==r1 ){
73786 *pReg = r1;
73787 }else{
73788 sqlite3ReleaseTempReg(pParse, r1);
73789 *pReg = 0;
73791 return r2;
73795 ** Generate code that will evaluate expression pExpr and store the
73796 ** results in register target. The results are guaranteed to appear
73797 ** in register target.
73799 SQLITE_PRIVATE int sqlite3ExprCode(Parse *pParse, Expr *pExpr, int target){
73800 int inReg;
73802 assert( target>0 && target<=pParse->nMem );
73803 if( pExpr && pExpr->op==TK_REGISTER ){
73804 sqlite3VdbeAddOp2(pParse->pVdbe, OP_Copy, pExpr->iTable, target);
73805 }else{
73806 inReg = sqlite3ExprCodeTarget(pParse, pExpr, target);
73807 assert( pParse->pVdbe || pParse->db->mallocFailed );
73808 if( inReg!=target && pParse->pVdbe ){
73809 sqlite3VdbeAddOp2(pParse->pVdbe, OP_SCopy, inReg, target);
73812 return target;
73816 ** Generate code that evalutes the given expression and puts the result
73817 ** in register target.
73819 ** Also make a copy of the expression results into another "cache" register
73820 ** and modify the expression so that the next time it is evaluated,
73821 ** the result is a copy of the cache register.
73823 ** This routine is used for expressions that are used multiple
73824 ** times. They are evaluated once and the results of the expression
73825 ** are reused.
73827 SQLITE_PRIVATE int sqlite3ExprCodeAndCache(Parse *pParse, Expr *pExpr, int target){
73828 Vdbe *v = pParse->pVdbe;
73829 int inReg;
73830 inReg = sqlite3ExprCode(pParse, pExpr, target);
73831 assert( target>0 );
73832 /* This routine is called for terms to INSERT or UPDATE. And the only
73833 ** other place where expressions can be converted into TK_REGISTER is
73834 ** in WHERE clause processing. So as currently implemented, there is
73835 ** no way for a TK_REGISTER to exist here. But it seems prudent to
73836 ** keep the ALWAYS() in case the conditions above change with future
73837 ** modifications or enhancements. */
73838 if( ALWAYS(pExpr->op!=TK_REGISTER) ){
73839 int iMem;
73840 iMem = ++pParse->nMem;
73841 sqlite3VdbeAddOp2(v, OP_Copy, inReg, iMem);
73842 pExpr->iTable = iMem;
73843 pExpr->op2 = pExpr->op;
73844 pExpr->op = TK_REGISTER;
73846 return inReg;
73850 ** Return TRUE if pExpr is an constant expression that is appropriate
73851 ** for factoring out of a loop. Appropriate expressions are:
73853 ** * Any expression that evaluates to two or more opcodes.
73855 ** * Any OP_Integer, OP_Real, OP_String, OP_Blob, OP_Null,
73856 ** or OP_Variable that does not need to be placed in a
73857 ** specific register.
73859 ** There is no point in factoring out single-instruction constant
73860 ** expressions that need to be placed in a particular register.
73861 ** We could factor them out, but then we would end up adding an
73862 ** OP_SCopy instruction to move the value into the correct register
73863 ** later. We might as well just use the original instruction and
73864 ** avoid the OP_SCopy.
73866 static int isAppropriateForFactoring(Expr *p){
73867 if( !sqlite3ExprIsConstantNotJoin(p) ){
73868 return 0; /* Only constant expressions are appropriate for factoring */
73870 if( (p->flags & EP_FixedDest)==0 ){
73871 return 1; /* Any constant without a fixed destination is appropriate */
73873 while( p->op==TK_UPLUS ) p = p->pLeft;
73874 switch( p->op ){
73875 #ifndef SQLITE_OMIT_BLOB_LITERAL
73876 case TK_BLOB:
73877 #endif
73878 case TK_VARIABLE:
73879 case TK_INTEGER:
73880 case TK_FLOAT:
73881 case TK_NULL:
73882 case TK_STRING: {
73883 testcase( p->op==TK_BLOB );
73884 testcase( p->op==TK_VARIABLE );
73885 testcase( p->op==TK_INTEGER );
73886 testcase( p->op==TK_FLOAT );
73887 testcase( p->op==TK_NULL );
73888 testcase( p->op==TK_STRING );
73889 /* Single-instruction constants with a fixed destination are
73890 ** better done in-line. If we factor them, they will just end
73891 ** up generating an OP_SCopy to move the value to the destination
73892 ** register. */
73893 return 0;
73895 case TK_UMINUS: {
73896 if( p->pLeft->op==TK_FLOAT || p->pLeft->op==TK_INTEGER ){
73897 return 0;
73899 break;
73901 default: {
73902 break;
73905 return 1;
73909 ** If pExpr is a constant expression that is appropriate for
73910 ** factoring out of a loop, then evaluate the expression
73911 ** into a register and convert the expression into a TK_REGISTER
73912 ** expression.
73914 static int evalConstExpr(Walker *pWalker, Expr *pExpr){
73915 Parse *pParse = pWalker->pParse;
73916 switch( pExpr->op ){
73917 case TK_IN:
73918 case TK_REGISTER: {
73919 return WRC_Prune;
73921 case TK_FUNCTION:
73922 case TK_AGG_FUNCTION:
73923 case TK_CONST_FUNC: {
73924 /* The arguments to a function have a fixed destination.
73925 ** Mark them this way to avoid generated unneeded OP_SCopy
73926 ** instructions.
73928 ExprList *pList = pExpr->x.pList;
73929 assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
73930 if( pList ){
73931 int i = pList->nExpr;
73932 struct ExprList_item *pItem = pList->a;
73933 for(; i>0; i--, pItem++){
73934 if( ALWAYS(pItem->pExpr) ) pItem->pExpr->flags |= EP_FixedDest;
73937 break;
73940 if( isAppropriateForFactoring(pExpr) ){
73941 int r1 = ++pParse->nMem;
73942 int r2;
73943 r2 = sqlite3ExprCodeTarget(pParse, pExpr, r1);
73944 if( NEVER(r1!=r2) ) sqlite3ReleaseTempReg(pParse, r1);
73945 pExpr->op2 = pExpr->op;
73946 pExpr->op = TK_REGISTER;
73947 pExpr->iTable = r2;
73948 return WRC_Prune;
73950 return WRC_Continue;
73954 ** Preevaluate constant subexpressions within pExpr and store the
73955 ** results in registers. Modify pExpr so that the constant subexpresions
73956 ** are TK_REGISTER opcodes that refer to the precomputed values.
73958 ** This routine is a no-op if the jump to the cookie-check code has
73959 ** already occur. Since the cookie-check jump is generated prior to
73960 ** any other serious processing, this check ensures that there is no
73961 ** way to accidently bypass the constant initializations.
73963 ** This routine is also a no-op if the SQLITE_FactorOutConst optimization
73964 ** is disabled via the sqlite3_test_control(SQLITE_TESTCTRL_OPTIMIZATIONS)
73965 ** interface. This allows test logic to verify that the same answer is
73966 ** obtained for queries regardless of whether or not constants are
73967 ** precomputed into registers or if they are inserted in-line.
73969 SQLITE_PRIVATE void sqlite3ExprCodeConstants(Parse *pParse, Expr *pExpr){
73970 Walker w;
73971 if( pParse->cookieGoto ) return;
73972 if( (pParse->db->flags & SQLITE_FactorOutConst)!=0 ) return;
73973 w.xExprCallback = evalConstExpr;
73974 w.xSelectCallback = 0;
73975 w.pParse = pParse;
73976 sqlite3WalkExpr(&w, pExpr);
73981 ** Generate code that pushes the value of every element of the given
73982 ** expression list into a sequence of registers beginning at target.
73984 ** Return the number of elements evaluated.
73986 SQLITE_PRIVATE int sqlite3ExprCodeExprList(
73987 Parse *pParse, /* Parsing context */
73988 ExprList *pList, /* The expression list to be coded */
73989 int target, /* Where to write results */
73990 int doHardCopy /* Make a hard copy of every element */
73992 struct ExprList_item *pItem;
73993 int i, n;
73994 assert( pList!=0 );
73995 assert( target>0 );
73996 assert( pParse->pVdbe!=0 ); /* Never gets this far otherwise */
73997 n = pList->nExpr;
73998 for(pItem=pList->a, i=0; i<n; i++, pItem++){
73999 Expr *pExpr = pItem->pExpr;
74000 int inReg = sqlite3ExprCodeTarget(pParse, pExpr, target+i);
74001 if( inReg!=target+i ){
74002 sqlite3VdbeAddOp2(pParse->pVdbe, doHardCopy ? OP_Copy : OP_SCopy,
74003 inReg, target+i);
74006 return n;
74010 ** Generate code for a BETWEEN operator.
74012 ** x BETWEEN y AND z
74014 ** The above is equivalent to
74016 ** x>=y AND x<=z
74018 ** Code it as such, taking care to do the common subexpression
74019 ** elementation of x.
74021 static void exprCodeBetween(
74022 Parse *pParse, /* Parsing and code generating context */
74023 Expr *pExpr, /* The BETWEEN expression */
74024 int dest, /* Jump here if the jump is taken */
74025 int jumpIfTrue, /* Take the jump if the BETWEEN is true */
74026 int jumpIfNull /* Take the jump if the BETWEEN is NULL */
74028 Expr exprAnd; /* The AND operator in x>=y AND x<=z */
74029 Expr compLeft; /* The x>=y term */
74030 Expr compRight; /* The x<=z term */
74031 Expr exprX; /* The x subexpression */
74032 int regFree1 = 0; /* Temporary use register */
74034 assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
74035 exprX = *pExpr->pLeft;
74036 exprAnd.op = TK_AND;
74037 exprAnd.pLeft = &compLeft;
74038 exprAnd.pRight = &compRight;
74039 compLeft.op = TK_GE;
74040 compLeft.pLeft = &exprX;
74041 compLeft.pRight = pExpr->x.pList->a[0].pExpr;
74042 compRight.op = TK_LE;
74043 compRight.pLeft = &exprX;
74044 compRight.pRight = pExpr->x.pList->a[1].pExpr;
74045 exprX.iTable = sqlite3ExprCodeTemp(pParse, &exprX, &regFree1);
74046 exprX.op = TK_REGISTER;
74047 if( jumpIfTrue ){
74048 sqlite3ExprIfTrue(pParse, &exprAnd, dest, jumpIfNull);
74049 }else{
74050 sqlite3ExprIfFalse(pParse, &exprAnd, dest, jumpIfNull);
74052 sqlite3ReleaseTempReg(pParse, regFree1);
74054 /* Ensure adequate test coverage */
74055 testcase( jumpIfTrue==0 && jumpIfNull==0 && regFree1==0 );
74056 testcase( jumpIfTrue==0 && jumpIfNull==0 && regFree1!=0 );
74057 testcase( jumpIfTrue==0 && jumpIfNull!=0 && regFree1==0 );
74058 testcase( jumpIfTrue==0 && jumpIfNull!=0 && regFree1!=0 );
74059 testcase( jumpIfTrue!=0 && jumpIfNull==0 && regFree1==0 );
74060 testcase( jumpIfTrue!=0 && jumpIfNull==0 && regFree1!=0 );
74061 testcase( jumpIfTrue!=0 && jumpIfNull!=0 && regFree1==0 );
74062 testcase( jumpIfTrue!=0 && jumpIfNull!=0 && regFree1!=0 );
74066 ** Generate code for a boolean expression such that a jump is made
74067 ** to the label "dest" if the expression is true but execution
74068 ** continues straight thru if the expression is false.
74070 ** If the expression evaluates to NULL (neither true nor false), then
74071 ** take the jump if the jumpIfNull flag is SQLITE_JUMPIFNULL.
74073 ** This code depends on the fact that certain token values (ex: TK_EQ)
74074 ** are the same as opcode values (ex: OP_Eq) that implement the corresponding
74075 ** operation. Special comments in vdbe.c and the mkopcodeh.awk script in
74076 ** the make process cause these values to align. Assert()s in the code
74077 ** below verify that the numbers are aligned correctly.
74079 SQLITE_PRIVATE void sqlite3ExprIfTrue(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){
74080 Vdbe *v = pParse->pVdbe;
74081 int op = 0;
74082 int regFree1 = 0;
74083 int regFree2 = 0;
74084 int r1, r2;
74086 assert( jumpIfNull==SQLITE_JUMPIFNULL || jumpIfNull==0 );
74087 if( NEVER(v==0) ) return; /* Existance of VDBE checked by caller */
74088 if( NEVER(pExpr==0) ) return; /* No way this can happen */
74089 op = pExpr->op;
74090 switch( op ){
74091 case TK_AND: {
74092 int d2 = sqlite3VdbeMakeLabel(v);
74093 testcase( jumpIfNull==0 );
74094 sqlite3ExprCachePush(pParse);
74095 sqlite3ExprIfFalse(pParse, pExpr->pLeft, d2,jumpIfNull^SQLITE_JUMPIFNULL);
74096 sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);
74097 sqlite3VdbeResolveLabel(v, d2);
74098 sqlite3ExprCachePop(pParse, 1);
74099 break;
74101 case TK_OR: {
74102 testcase( jumpIfNull==0 );
74103 sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);
74104 sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);
74105 break;
74107 case TK_NOT: {
74108 testcase( jumpIfNull==0 );
74109 sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);
74110 break;
74112 case TK_LT:
74113 case TK_LE:
74114 case TK_GT:
74115 case TK_GE:
74116 case TK_NE:
74117 case TK_EQ: {
74118 assert( TK_LT==OP_Lt );
74119 assert( TK_LE==OP_Le );
74120 assert( TK_GT==OP_Gt );
74121 assert( TK_GE==OP_Ge );
74122 assert( TK_EQ==OP_Eq );
74123 assert( TK_NE==OP_Ne );
74124 testcase( op==TK_LT );
74125 testcase( op==TK_LE );
74126 testcase( op==TK_GT );
74127 testcase( op==TK_GE );
74128 testcase( op==TK_EQ );
74129 testcase( op==TK_NE );
74130 testcase( jumpIfNull==0 );
74131 r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
74132 r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
74133 codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
74134 r1, r2, dest, jumpIfNull);
74135 testcase( regFree1==0 );
74136 testcase( regFree2==0 );
74137 break;
74139 case TK_IS:
74140 case TK_ISNOT: {
74141 testcase( op==TK_IS );
74142 testcase( op==TK_ISNOT );
74143 r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
74144 r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
74145 op = (op==TK_IS) ? TK_EQ : TK_NE;
74146 codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
74147 r1, r2, dest, SQLITE_NULLEQ);
74148 testcase( regFree1==0 );
74149 testcase( regFree2==0 );
74150 break;
74152 case TK_ISNULL:
74153 case TK_NOTNULL: {
74154 assert( TK_ISNULL==OP_IsNull );
74155 assert( TK_NOTNULL==OP_NotNull );
74156 testcase( op==TK_ISNULL );
74157 testcase( op==TK_NOTNULL );
74158 r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
74159 sqlite3VdbeAddOp2(v, op, r1, dest);
74160 testcase( regFree1==0 );
74161 break;
74163 case TK_BETWEEN: {
74164 testcase( jumpIfNull==0 );
74165 exprCodeBetween(pParse, pExpr, dest, 1, jumpIfNull);
74166 break;
74168 #ifndef SQLITE_OMIT_SUBQUERY
74169 case TK_IN: {
74170 int destIfFalse = sqlite3VdbeMakeLabel(v);
74171 int destIfNull = jumpIfNull ? dest : destIfFalse;
74172 sqlite3ExprCodeIN(pParse, pExpr, destIfFalse, destIfNull);
74173 sqlite3VdbeAddOp2(v, OP_Goto, 0, dest);
74174 sqlite3VdbeResolveLabel(v, destIfFalse);
74175 break;
74177 #endif
74178 default: {
74179 r1 = sqlite3ExprCodeTemp(pParse, pExpr, &regFree1);
74180 sqlite3VdbeAddOp3(v, OP_If, r1, dest, jumpIfNull!=0);
74181 testcase( regFree1==0 );
74182 testcase( jumpIfNull==0 );
74183 break;
74186 sqlite3ReleaseTempReg(pParse, regFree1);
74187 sqlite3ReleaseTempReg(pParse, regFree2);
74191 ** Generate code for a boolean expression such that a jump is made
74192 ** to the label "dest" if the expression is false but execution
74193 ** continues straight thru if the expression is true.
74195 ** If the expression evaluates to NULL (neither true nor false) then
74196 ** jump if jumpIfNull is SQLITE_JUMPIFNULL or fall through if jumpIfNull
74197 ** is 0.
74199 SQLITE_PRIVATE void sqlite3ExprIfFalse(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){
74200 Vdbe *v = pParse->pVdbe;
74201 int op = 0;
74202 int regFree1 = 0;
74203 int regFree2 = 0;
74204 int r1, r2;
74206 assert( jumpIfNull==SQLITE_JUMPIFNULL || jumpIfNull==0 );
74207 if( NEVER(v==0) ) return; /* Existance of VDBE checked by caller */
74208 if( pExpr==0 ) return;
74210 /* The value of pExpr->op and op are related as follows:
74212 ** pExpr->op op
74213 ** --------- ----------
74214 ** TK_ISNULL OP_NotNull
74215 ** TK_NOTNULL OP_IsNull
74216 ** TK_NE OP_Eq
74217 ** TK_EQ OP_Ne
74218 ** TK_GT OP_Le
74219 ** TK_LE OP_Gt
74220 ** TK_GE OP_Lt
74221 ** TK_LT OP_Ge
74223 ** For other values of pExpr->op, op is undefined and unused.
74224 ** The value of TK_ and OP_ constants are arranged such that we
74225 ** can compute the mapping above using the following expression.
74226 ** Assert()s verify that the computation is correct.
74228 op = ((pExpr->op+(TK_ISNULL&1))^1)-(TK_ISNULL&1);
74230 /* Verify correct alignment of TK_ and OP_ constants
74232 assert( pExpr->op!=TK_ISNULL || op==OP_NotNull );
74233 assert( pExpr->op!=TK_NOTNULL || op==OP_IsNull );
74234 assert( pExpr->op!=TK_NE || op==OP_Eq );
74235 assert( pExpr->op!=TK_EQ || op==OP_Ne );
74236 assert( pExpr->op!=TK_LT || op==OP_Ge );
74237 assert( pExpr->op!=TK_LE || op==OP_Gt );
74238 assert( pExpr->op!=TK_GT || op==OP_Le );
74239 assert( pExpr->op!=TK_GE || op==OP_Lt );
74241 switch( pExpr->op ){
74242 case TK_AND: {
74243 testcase( jumpIfNull==0 );
74244 sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);
74245 sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull);
74246 break;
74248 case TK_OR: {
74249 int d2 = sqlite3VdbeMakeLabel(v);
74250 testcase( jumpIfNull==0 );
74251 sqlite3ExprCachePush(pParse);
74252 sqlite3ExprIfTrue(pParse, pExpr->pLeft, d2, jumpIfNull^SQLITE_JUMPIFNULL);
74253 sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull);
74254 sqlite3VdbeResolveLabel(v, d2);
74255 sqlite3ExprCachePop(pParse, 1);
74256 break;
74258 case TK_NOT: {
74259 testcase( jumpIfNull==0 );
74260 sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);
74261 break;
74263 case TK_LT:
74264 case TK_LE:
74265 case TK_GT:
74266 case TK_GE:
74267 case TK_NE:
74268 case TK_EQ: {
74269 testcase( op==TK_LT );
74270 testcase( op==TK_LE );
74271 testcase( op==TK_GT );
74272 testcase( op==TK_GE );
74273 testcase( op==TK_EQ );
74274 testcase( op==TK_NE );
74275 testcase( jumpIfNull==0 );
74276 r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
74277 r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
74278 codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
74279 r1, r2, dest, jumpIfNull);
74280 testcase( regFree1==0 );
74281 testcase( regFree2==0 );
74282 break;
74284 case TK_IS:
74285 case TK_ISNOT: {
74286 testcase( pExpr->op==TK_IS );
74287 testcase( pExpr->op==TK_ISNOT );
74288 r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
74289 r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
74290 op = (pExpr->op==TK_IS) ? TK_NE : TK_EQ;
74291 codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
74292 r1, r2, dest, SQLITE_NULLEQ);
74293 testcase( regFree1==0 );
74294 testcase( regFree2==0 );
74295 break;
74297 case TK_ISNULL:
74298 case TK_NOTNULL: {
74299 testcase( op==TK_ISNULL );
74300 testcase( op==TK_NOTNULL );
74301 r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
74302 sqlite3VdbeAddOp2(v, op, r1, dest);
74303 testcase( regFree1==0 );
74304 break;
74306 case TK_BETWEEN: {
74307 testcase( jumpIfNull==0 );
74308 exprCodeBetween(pParse, pExpr, dest, 0, jumpIfNull);
74309 break;
74311 #ifndef SQLITE_OMIT_SUBQUERY
74312 case TK_IN: {
74313 if( jumpIfNull ){
74314 sqlite3ExprCodeIN(pParse, pExpr, dest, dest);
74315 }else{
74316 int destIfNull = sqlite3VdbeMakeLabel(v);
74317 sqlite3ExprCodeIN(pParse, pExpr, dest, destIfNull);
74318 sqlite3VdbeResolveLabel(v, destIfNull);
74320 break;
74322 #endif
74323 default: {
74324 r1 = sqlite3ExprCodeTemp(pParse, pExpr, &regFree1);
74325 sqlite3VdbeAddOp3(v, OP_IfNot, r1, dest, jumpIfNull!=0);
74326 testcase( regFree1==0 );
74327 testcase( jumpIfNull==0 );
74328 break;
74331 sqlite3ReleaseTempReg(pParse, regFree1);
74332 sqlite3ReleaseTempReg(pParse, regFree2);
74336 ** Do a deep comparison of two expression trees. Return 0 if the two
74337 ** expressions are completely identical. Return 1 if they differ only
74338 ** by a COLLATE operator at the top level. Return 2 if there are differences
74339 ** other than the top-level COLLATE operator.
74341 ** Sometimes this routine will return 2 even if the two expressions
74342 ** really are equivalent. If we cannot prove that the expressions are
74343 ** identical, we return 2 just to be safe. So if this routine
74344 ** returns 2, then you do not really know for certain if the two
74345 ** expressions are the same. But if you get a 0 or 1 return, then you
74346 ** can be sure the expressions are the same. In the places where
74347 ** this routine is used, it does not hurt to get an extra 2 - that
74348 ** just might result in some slightly slower code. But returning
74349 ** an incorrect 0 or 1 could lead to a malfunction.
74351 SQLITE_PRIVATE int sqlite3ExprCompare(Expr *pA, Expr *pB){
74352 if( pA==0||pB==0 ){
74353 return pB==pA ? 0 : 2;
74355 assert( !ExprHasAnyProperty(pA, EP_TokenOnly|EP_Reduced) );
74356 assert( !ExprHasAnyProperty(pB, EP_TokenOnly|EP_Reduced) );
74357 if( ExprHasProperty(pA, EP_xIsSelect) || ExprHasProperty(pB, EP_xIsSelect) ){
74358 return 2;
74360 if( (pA->flags & EP_Distinct)!=(pB->flags & EP_Distinct) ) return 2;
74361 if( pA->op!=pB->op ) return 2;
74362 if( sqlite3ExprCompare(pA->pLeft, pB->pLeft) ) return 2;
74363 if( sqlite3ExprCompare(pA->pRight, pB->pRight) ) return 2;
74364 if( sqlite3ExprListCompare(pA->x.pList, pB->x.pList) ) return 2;
74365 if( pA->iTable!=pB->iTable || pA->iColumn!=pB->iColumn ) return 2;
74366 if( ExprHasProperty(pA, EP_IntValue) ){
74367 if( !ExprHasProperty(pB, EP_IntValue) || pA->u.iValue!=pB->u.iValue ){
74368 return 2;
74370 }else if( pA->op!=TK_COLUMN && pA->u.zToken ){
74371 if( ExprHasProperty(pB, EP_IntValue) || NEVER(pB->u.zToken==0) ) return 2;
74372 if( sqlite3StrICmp(pA->u.zToken,pB->u.zToken)!=0 ){
74373 return 2;
74376 if( (pA->flags & EP_ExpCollate)!=(pB->flags & EP_ExpCollate) ) return 1;
74377 if( (pA->flags & EP_ExpCollate)!=0 && pA->pColl!=pB->pColl ) return 2;
74378 return 0;
74382 ** Compare two ExprList objects. Return 0 if they are identical and
74383 ** non-zero if they differ in any way.
74385 ** This routine might return non-zero for equivalent ExprLists. The
74386 ** only consequence will be disabled optimizations. But this routine
74387 ** must never return 0 if the two ExprList objects are different, or
74388 ** a malfunction will result.
74390 ** Two NULL pointers are considered to be the same. But a NULL pointer
74391 ** always differs from a non-NULL pointer.
74393 SQLITE_PRIVATE int sqlite3ExprListCompare(ExprList *pA, ExprList *pB){
74394 int i;
74395 if( pA==0 && pB==0 ) return 0;
74396 if( pA==0 || pB==0 ) return 1;
74397 if( pA->nExpr!=pB->nExpr ) return 1;
74398 for(i=0; i<pA->nExpr; i++){
74399 Expr *pExprA = pA->a[i].pExpr;
74400 Expr *pExprB = pB->a[i].pExpr;
74401 if( pA->a[i].sortOrder!=pB->a[i].sortOrder ) return 1;
74402 if( sqlite3ExprCompare(pExprA, pExprB) ) return 1;
74404 return 0;
74408 ** Add a new element to the pAggInfo->aCol[] array. Return the index of
74409 ** the new element. Return a negative number if malloc fails.
74411 static int addAggInfoColumn(sqlite3 *db, AggInfo *pInfo){
74412 int i;
74413 pInfo->aCol = sqlite3ArrayAllocate(
74415 pInfo->aCol,
74416 sizeof(pInfo->aCol[0]),
74418 &pInfo->nColumn,
74419 &pInfo->nColumnAlloc,
74422 return i;
74426 ** Add a new element to the pAggInfo->aFunc[] array. Return the index of
74427 ** the new element. Return a negative number if malloc fails.
74429 static int addAggInfoFunc(sqlite3 *db, AggInfo *pInfo){
74430 int i;
74431 pInfo->aFunc = sqlite3ArrayAllocate(
74432 db,
74433 pInfo->aFunc,
74434 sizeof(pInfo->aFunc[0]),
74436 &pInfo->nFunc,
74437 &pInfo->nFuncAlloc,
74440 return i;
74444 ** This is the xExprCallback for a tree walker. It is used to
74445 ** implement sqlite3ExprAnalyzeAggregates(). See sqlite3ExprAnalyzeAggregates
74446 ** for additional information.
74448 static int analyzeAggregate(Walker *pWalker, Expr *pExpr){
74449 int i;
74450 NameContext *pNC = pWalker->u.pNC;
74451 Parse *pParse = pNC->pParse;
74452 SrcList *pSrcList = pNC->pSrcList;
74453 AggInfo *pAggInfo = pNC->pAggInfo;
74455 switch( pExpr->op ){
74456 case TK_AGG_COLUMN:
74457 case TK_COLUMN: {
74458 testcase( pExpr->op==TK_AGG_COLUMN );
74459 testcase( pExpr->op==TK_COLUMN );
74460 /* Check to see if the column is in one of the tables in the FROM
74461 ** clause of the aggregate query */
74462 if( ALWAYS(pSrcList!=0) ){
74463 struct SrcList_item *pItem = pSrcList->a;
74464 for(i=0; i<pSrcList->nSrc; i++, pItem++){
74465 struct AggInfo_col *pCol;
74466 assert( !ExprHasAnyProperty(pExpr, EP_TokenOnly|EP_Reduced) );
74467 if( pExpr->iTable==pItem->iCursor ){
74468 /* If we reach this point, it means that pExpr refers to a table
74469 ** that is in the FROM clause of the aggregate query.
74471 ** Make an entry for the column in pAggInfo->aCol[] if there
74472 ** is not an entry there already.
74474 int k;
74475 pCol = pAggInfo->aCol;
74476 for(k=0; k<pAggInfo->nColumn; k++, pCol++){
74477 if( pCol->iTable==pExpr->iTable &&
74478 pCol->iColumn==pExpr->iColumn ){
74479 break;
74482 if( (k>=pAggInfo->nColumn)
74483 && (k = addAggInfoColumn(pParse->db, pAggInfo))>=0
74485 pCol = &pAggInfo->aCol[k];
74486 pCol->pTab = pExpr->pTab;
74487 pCol->iTable = pExpr->iTable;
74488 pCol->iColumn = pExpr->iColumn;
74489 pCol->iMem = ++pParse->nMem;
74490 pCol->iSorterColumn = -1;
74491 pCol->pExpr = pExpr;
74492 if( pAggInfo->pGroupBy ){
74493 int j, n;
74494 ExprList *pGB = pAggInfo->pGroupBy;
74495 struct ExprList_item *pTerm = pGB->a;
74496 n = pGB->nExpr;
74497 for(j=0; j<n; j++, pTerm++){
74498 Expr *pE = pTerm->pExpr;
74499 if( pE->op==TK_COLUMN && pE->iTable==pExpr->iTable &&
74500 pE->iColumn==pExpr->iColumn ){
74501 pCol->iSorterColumn = j;
74502 break;
74506 if( pCol->iSorterColumn<0 ){
74507 pCol->iSorterColumn = pAggInfo->nSortingColumn++;
74510 /* There is now an entry for pExpr in pAggInfo->aCol[] (either
74511 ** because it was there before or because we just created it).
74512 ** Convert the pExpr to be a TK_AGG_COLUMN referring to that
74513 ** pAggInfo->aCol[] entry.
74515 ExprSetIrreducible(pExpr);
74516 pExpr->pAggInfo = pAggInfo;
74517 pExpr->op = TK_AGG_COLUMN;
74518 pExpr->iAgg = (i16)k;
74519 break;
74520 } /* endif pExpr->iTable==pItem->iCursor */
74521 } /* end loop over pSrcList */
74523 return WRC_Prune;
74525 case TK_AGG_FUNCTION: {
74526 /* The pNC->nDepth==0 test causes aggregate functions in subqueries
74527 ** to be ignored */
74528 if( pNC->nDepth==0 ){
74529 /* Check to see if pExpr is a duplicate of another aggregate
74530 ** function that is already in the pAggInfo structure
74532 struct AggInfo_func *pItem = pAggInfo->aFunc;
74533 for(i=0; i<pAggInfo->nFunc; i++, pItem++){
74534 if( sqlite3ExprCompare(pItem->pExpr, pExpr)==0 ){
74535 break;
74538 if( i>=pAggInfo->nFunc ){
74539 /* pExpr is original. Make a new entry in pAggInfo->aFunc[]
74541 u8 enc = ENC(pParse->db);
74542 i = addAggInfoFunc(pParse->db, pAggInfo);
74543 if( i>=0 ){
74544 assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
74545 pItem = &pAggInfo->aFunc[i];
74546 pItem->pExpr = pExpr;
74547 pItem->iMem = ++pParse->nMem;
74548 assert( !ExprHasProperty(pExpr, EP_IntValue) );
74549 pItem->pFunc = sqlite3FindFunction(pParse->db,
74550 pExpr->u.zToken, sqlite3Strlen30(pExpr->u.zToken),
74551 pExpr->x.pList ? pExpr->x.pList->nExpr : 0, enc, 0);
74552 if( pExpr->flags & EP_Distinct ){
74553 pItem->iDistinct = pParse->nTab++;
74554 }else{
74555 pItem->iDistinct = -1;
74559 /* Make pExpr point to the appropriate pAggInfo->aFunc[] entry
74561 assert( !ExprHasAnyProperty(pExpr, EP_TokenOnly|EP_Reduced) );
74562 ExprSetIrreducible(pExpr);
74563 pExpr->iAgg = (i16)i;
74564 pExpr->pAggInfo = pAggInfo;
74565 return WRC_Prune;
74569 return WRC_Continue;
74571 static int analyzeAggregatesInSelect(Walker *pWalker, Select *pSelect){
74572 NameContext *pNC = pWalker->u.pNC;
74573 if( pNC->nDepth==0 ){
74574 pNC->nDepth++;
74575 sqlite3WalkSelect(pWalker, pSelect);
74576 pNC->nDepth--;
74577 return WRC_Prune;
74578 }else{
74579 return WRC_Continue;
74584 ** Analyze the given expression looking for aggregate functions and
74585 ** for variables that need to be added to the pParse->aAgg[] array.
74586 ** Make additional entries to the pParse->aAgg[] array as necessary.
74588 ** This routine should only be called after the expression has been
74589 ** analyzed by sqlite3ResolveExprNames().
74591 SQLITE_PRIVATE void sqlite3ExprAnalyzeAggregates(NameContext *pNC, Expr *pExpr){
74592 Walker w;
74593 w.xExprCallback = analyzeAggregate;
74594 w.xSelectCallback = analyzeAggregatesInSelect;
74595 w.u.pNC = pNC;
74596 assert( pNC->pSrcList!=0 );
74597 sqlite3WalkExpr(&w, pExpr);
74601 ** Call sqlite3ExprAnalyzeAggregates() for every expression in an
74602 ** expression list. Return the number of errors.
74604 ** If an error is found, the analysis is cut short.
74606 SQLITE_PRIVATE void sqlite3ExprAnalyzeAggList(NameContext *pNC, ExprList *pList){
74607 struct ExprList_item *pItem;
74608 int i;
74609 if( pList ){
74610 for(pItem=pList->a, i=0; i<pList->nExpr; i++, pItem++){
74611 sqlite3ExprAnalyzeAggregates(pNC, pItem->pExpr);
74617 ** Allocate a single new register for use to hold some intermediate result.
74619 SQLITE_PRIVATE int sqlite3GetTempReg(Parse *pParse){
74620 if( pParse->nTempReg==0 ){
74621 return ++pParse->nMem;
74623 return pParse->aTempReg[--pParse->nTempReg];
74627 ** Deallocate a register, making available for reuse for some other
74628 ** purpose.
74630 ** If a register is currently being used by the column cache, then
74631 ** the dallocation is deferred until the column cache line that uses
74632 ** the register becomes stale.
74634 SQLITE_PRIVATE void sqlite3ReleaseTempReg(Parse *pParse, int iReg){
74635 if( iReg && pParse->nTempReg<ArraySize(pParse->aTempReg) ){
74636 int i;
74637 struct yColCache *p;
74638 for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
74639 if( p->iReg==iReg ){
74640 p->tempReg = 1;
74641 return;
74644 pParse->aTempReg[pParse->nTempReg++] = iReg;
74649 ** Allocate or deallocate a block of nReg consecutive registers
74651 SQLITE_PRIVATE int sqlite3GetTempRange(Parse *pParse, int nReg){
74652 int i, n;
74653 i = pParse->iRangeReg;
74654 n = pParse->nRangeReg;
74655 if( nReg<=n ){
74656 assert( !usedAsColumnCache(pParse, i, i+n-1) );
74657 pParse->iRangeReg += nReg;
74658 pParse->nRangeReg -= nReg;
74659 }else{
74660 i = pParse->nMem+1;
74661 pParse->nMem += nReg;
74663 return i;
74665 SQLITE_PRIVATE void sqlite3ReleaseTempRange(Parse *pParse, int iReg, int nReg){
74666 sqlite3ExprCacheRemove(pParse, iReg, nReg);
74667 if( nReg>pParse->nRangeReg ){
74668 pParse->nRangeReg = nReg;
74669 pParse->iRangeReg = iReg;
74673 /************** End of expr.c ************************************************/
74674 /************** Begin file alter.c *******************************************/
74676 ** 2005 February 15
74678 ** The author disclaims copyright to this source code. In place of
74679 ** a legal notice, here is a blessing:
74681 ** May you do good and not evil.
74682 ** May you find forgiveness for yourself and forgive others.
74683 ** May you share freely, never taking more than you give.
74685 *************************************************************************
74686 ** This file contains C code routines that used to generate VDBE code
74687 ** that implements the ALTER TABLE command.
74691 ** The code in this file only exists if we are not omitting the
74692 ** ALTER TABLE logic from the build.
74694 #ifndef SQLITE_OMIT_ALTERTABLE
74698 ** This function is used by SQL generated to implement the
74699 ** ALTER TABLE command. The first argument is the text of a CREATE TABLE or
74700 ** CREATE INDEX command. The second is a table name. The table name in
74701 ** the CREATE TABLE or CREATE INDEX statement is replaced with the third
74702 ** argument and the result returned. Examples:
74704 ** sqlite_rename_table('CREATE TABLE abc(a, b, c)', 'def')
74705 ** -> 'CREATE TABLE def(a, b, c)'
74707 ** sqlite_rename_table('CREATE INDEX i ON abc(a)', 'def')
74708 ** -> 'CREATE INDEX i ON def(a, b, c)'
74710 static void renameTableFunc(
74711 sqlite3_context *context,
74712 int NotUsed,
74713 sqlite3_value **argv
74715 unsigned char const *zSql = sqlite3_value_text(argv[0]);
74716 unsigned char const *zTableName = sqlite3_value_text(argv[1]);
74718 int token;
74719 Token tname;
74720 unsigned char const *zCsr = zSql;
74721 int len = 0;
74722 char *zRet;
74724 sqlite3 *db = sqlite3_context_db_handle(context);
74726 UNUSED_PARAMETER(NotUsed);
74728 /* The principle used to locate the table name in the CREATE TABLE
74729 ** statement is that the table name is the first non-space token that
74730 ** is immediately followed by a TK_LP or TK_USING token.
74732 if( zSql ){
74733 do {
74734 if( !*zCsr ){
74735 /* Ran out of input before finding an opening bracket. Return NULL. */
74736 return;
74739 /* Store the token that zCsr points to in tname. */
74740 tname.z = (char*)zCsr;
74741 tname.n = len;
74743 /* Advance zCsr to the next token. Store that token type in 'token',
74744 ** and its length in 'len' (to be used next iteration of this loop).
74746 do {
74747 zCsr += len;
74748 len = sqlite3GetToken(zCsr, &token);
74749 } while( token==TK_SPACE );
74750 assert( len>0 );
74751 } while( token!=TK_LP && token!=TK_USING );
74753 zRet = sqlite3MPrintf(db, "%.*s\"%w\"%s", ((u8*)tname.z) - zSql, zSql,
74754 zTableName, tname.z+tname.n);
74755 sqlite3_result_text(context, zRet, -1, SQLITE_DYNAMIC);
74760 ** This C function implements an SQL user function that is used by SQL code
74761 ** generated by the ALTER TABLE ... RENAME command to modify the definition
74762 ** of any foreign key constraints that use the table being renamed as the
74763 ** parent table. It is passed three arguments:
74765 ** 1) The complete text of the CREATE TABLE statement being modified,
74766 ** 2) The old name of the table being renamed, and
74767 ** 3) The new name of the table being renamed.
74769 ** It returns the new CREATE TABLE statement. For example:
74771 ** sqlite_rename_parent('CREATE TABLE t1(a REFERENCES t2)', 't2', 't3')
74772 ** -> 'CREATE TABLE t1(a REFERENCES t3)'
74774 #ifndef SQLITE_OMIT_FOREIGN_KEY
74775 static void renameParentFunc(
74776 sqlite3_context *context,
74777 int NotUsed,
74778 sqlite3_value **argv
74780 sqlite3 *db = sqlite3_context_db_handle(context);
74781 char *zOutput = 0;
74782 char *zResult;
74783 unsigned char const *zInput = sqlite3_value_text(argv[0]);
74784 unsigned char const *zOld = sqlite3_value_text(argv[1]);
74785 unsigned char const *zNew = sqlite3_value_text(argv[2]);
74787 unsigned const char *z; /* Pointer to token */
74788 int n; /* Length of token z */
74789 int token; /* Type of token */
74791 UNUSED_PARAMETER(NotUsed);
74792 for(z=zInput; *z; z=z+n){
74793 n = sqlite3GetToken(z, &token);
74794 if( token==TK_REFERENCES ){
74795 char *zParent;
74796 do {
74797 z += n;
74798 n = sqlite3GetToken(z, &token);
74799 }while( token==TK_SPACE );
74801 zParent = sqlite3DbStrNDup(db, (const char *)z, n);
74802 if( zParent==0 ) break;
74803 sqlite3Dequote(zParent);
74804 if( 0==sqlite3StrICmp((const char *)zOld, zParent) ){
74805 char *zOut = sqlite3MPrintf(db, "%s%.*s\"%w\"",
74806 (zOutput?zOutput:""), z-zInput, zInput, (const char *)zNew
74808 sqlite3DbFree(db, zOutput);
74809 zOutput = zOut;
74810 zInput = &z[n];
74812 sqlite3DbFree(db, zParent);
74816 zResult = sqlite3MPrintf(db, "%s%s", (zOutput?zOutput:""), zInput),
74817 sqlite3_result_text(context, zResult, -1, SQLITE_DYNAMIC);
74818 sqlite3DbFree(db, zOutput);
74820 #endif
74822 #ifndef SQLITE_OMIT_TRIGGER
74823 /* This function is used by SQL generated to implement the
74824 ** ALTER TABLE command. The first argument is the text of a CREATE TRIGGER
74825 ** statement. The second is a table name. The table name in the CREATE
74826 ** TRIGGER statement is replaced with the third argument and the result
74827 ** returned. This is analagous to renameTableFunc() above, except for CREATE
74828 ** TRIGGER, not CREATE INDEX and CREATE TABLE.
74830 static void renameTriggerFunc(
74831 sqlite3_context *context,
74832 int NotUsed,
74833 sqlite3_value **argv
74835 unsigned char const *zSql = sqlite3_value_text(argv[0]);
74836 unsigned char const *zTableName = sqlite3_value_text(argv[1]);
74838 int token;
74839 Token tname;
74840 int dist = 3;
74841 unsigned char const *zCsr = zSql;
74842 int len = 0;
74843 char *zRet;
74844 sqlite3 *db = sqlite3_context_db_handle(context);
74846 UNUSED_PARAMETER(NotUsed);
74848 /* The principle used to locate the table name in the CREATE TRIGGER
74849 ** statement is that the table name is the first token that is immediatedly
74850 ** preceded by either TK_ON or TK_DOT and immediatedly followed by one
74851 ** of TK_WHEN, TK_BEGIN or TK_FOR.
74853 if( zSql ){
74854 do {
74856 if( !*zCsr ){
74857 /* Ran out of input before finding the table name. Return NULL. */
74858 return;
74861 /* Store the token that zCsr points to in tname. */
74862 tname.z = (char*)zCsr;
74863 tname.n = len;
74865 /* Advance zCsr to the next token. Store that token type in 'token',
74866 ** and its length in 'len' (to be used next iteration of this loop).
74868 do {
74869 zCsr += len;
74870 len = sqlite3GetToken(zCsr, &token);
74871 }while( token==TK_SPACE );
74872 assert( len>0 );
74874 /* Variable 'dist' stores the number of tokens read since the most
74875 ** recent TK_DOT or TK_ON. This means that when a WHEN, FOR or BEGIN
74876 ** token is read and 'dist' equals 2, the condition stated above
74877 ** to be met.
74879 ** Note that ON cannot be a database, table or column name, so
74880 ** there is no need to worry about syntax like
74881 ** "CREATE TRIGGER ... ON ON.ON BEGIN ..." etc.
74883 dist++;
74884 if( token==TK_DOT || token==TK_ON ){
74885 dist = 0;
74887 } while( dist!=2 || (token!=TK_WHEN && token!=TK_FOR && token!=TK_BEGIN) );
74889 /* Variable tname now contains the token that is the old table-name
74890 ** in the CREATE TRIGGER statement.
74892 zRet = sqlite3MPrintf(db, "%.*s\"%w\"%s", ((u8*)tname.z) - zSql, zSql,
74893 zTableName, tname.z+tname.n);
74894 sqlite3_result_text(context, zRet, -1, SQLITE_DYNAMIC);
74897 #endif /* !SQLITE_OMIT_TRIGGER */
74900 ** Register built-in functions used to help implement ALTER TABLE
74902 SQLITE_PRIVATE void sqlite3AlterFunctions(void){
74903 static SQLITE_WSD FuncDef aAlterTableFuncs[] = {
74904 FUNCTION(sqlite_rename_table, 2, 0, 0, renameTableFunc),
74905 #ifndef SQLITE_OMIT_TRIGGER
74906 FUNCTION(sqlite_rename_trigger, 2, 0, 0, renameTriggerFunc),
74907 #endif
74908 #ifndef SQLITE_OMIT_FOREIGN_KEY
74909 FUNCTION(sqlite_rename_parent, 3, 0, 0, renameParentFunc),
74910 #endif
74912 int i;
74913 FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
74914 FuncDef *aFunc = (FuncDef*)&GLOBAL(FuncDef, aAlterTableFuncs);
74916 for(i=0; i<ArraySize(aAlterTableFuncs); i++){
74917 sqlite3FuncDefInsert(pHash, &aFunc[i]);
74922 ** This function is used to create the text of expressions of the form:
74924 ** name=<constant1> OR name=<constant2> OR ...
74926 ** If argument zWhere is NULL, then a pointer string containing the text
74927 ** "name=<constant>" is returned, where <constant> is the quoted version
74928 ** of the string passed as argument zConstant. The returned buffer is
74929 ** allocated using sqlite3DbMalloc(). It is the responsibility of the
74930 ** caller to ensure that it is eventually freed.
74932 ** If argument zWhere is not NULL, then the string returned is
74933 ** "<where> OR name=<constant>", where <where> is the contents of zWhere.
74934 ** In this case zWhere is passed to sqlite3DbFree() before returning.
74937 static char *whereOrName(sqlite3 *db, char *zWhere, char *zConstant){
74938 char *zNew;
74939 if( !zWhere ){
74940 zNew = sqlite3MPrintf(db, "name=%Q", zConstant);
74941 }else{
74942 zNew = sqlite3MPrintf(db, "%s OR name=%Q", zWhere, zConstant);
74943 sqlite3DbFree(db, zWhere);
74945 return zNew;
74948 #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
74950 ** Generate the text of a WHERE expression which can be used to select all
74951 ** tables that have foreign key constraints that refer to table pTab (i.e.
74952 ** constraints for which pTab is the parent table) from the sqlite_master
74953 ** table.
74955 static char *whereForeignKeys(Parse *pParse, Table *pTab){
74956 FKey *p;
74957 char *zWhere = 0;
74958 for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
74959 zWhere = whereOrName(pParse->db, zWhere, p->pFrom->zName);
74961 return zWhere;
74963 #endif
74966 ** Generate the text of a WHERE expression which can be used to select all
74967 ** temporary triggers on table pTab from the sqlite_temp_master table. If
74968 ** table pTab has no temporary triggers, or is itself stored in the
74969 ** temporary database, NULL is returned.
74971 static char *whereTempTriggers(Parse *pParse, Table *pTab){
74972 Trigger *pTrig;
74973 char *zWhere = 0;
74974 const Schema *pTempSchema = pParse->db->aDb[1].pSchema; /* Temp db schema */
74976 /* If the table is not located in the temp-db (in which case NULL is
74977 ** returned, loop through the tables list of triggers. For each trigger
74978 ** that is not part of the temp-db schema, add a clause to the WHERE
74979 ** expression being built up in zWhere.
74981 if( pTab->pSchema!=pTempSchema ){
74982 sqlite3 *db = pParse->db;
74983 for(pTrig=sqlite3TriggerList(pParse, pTab); pTrig; pTrig=pTrig->pNext){
74984 if( pTrig->pSchema==pTempSchema ){
74985 zWhere = whereOrName(db, zWhere, pTrig->zName);
74989 if( zWhere ){
74990 char *zNew = sqlite3MPrintf(pParse->db, "type='trigger' AND (%s)", zWhere);
74991 sqlite3DbFree(pParse->db, zWhere);
74992 zWhere = zNew;
74994 return zWhere;
74998 ** Generate code to drop and reload the internal representation of table
74999 ** pTab from the database, including triggers and temporary triggers.
75000 ** Argument zName is the name of the table in the database schema at
75001 ** the time the generated code is executed. This can be different from
75002 ** pTab->zName if this function is being called to code part of an
75003 ** "ALTER TABLE RENAME TO" statement.
75005 static void reloadTableSchema(Parse *pParse, Table *pTab, const char *zName){
75006 Vdbe *v;
75007 char *zWhere;
75008 int iDb; /* Index of database containing pTab */
75009 #ifndef SQLITE_OMIT_TRIGGER
75010 Trigger *pTrig;
75011 #endif
75013 v = sqlite3GetVdbe(pParse);
75014 if( NEVER(v==0) ) return;
75015 assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
75016 iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
75017 assert( iDb>=0 );
75019 #ifndef SQLITE_OMIT_TRIGGER
75020 /* Drop any table triggers from the internal schema. */
75021 for(pTrig=sqlite3TriggerList(pParse, pTab); pTrig; pTrig=pTrig->pNext){
75022 int iTrigDb = sqlite3SchemaToIndex(pParse->db, pTrig->pSchema);
75023 assert( iTrigDb==iDb || iTrigDb==1 );
75024 sqlite3VdbeAddOp4(v, OP_DropTrigger, iTrigDb, 0, 0, pTrig->zName, 0);
75026 #endif
75028 /* Drop the table and index from the internal schema. */
75029 sqlite3VdbeAddOp4(v, OP_DropTable, iDb, 0, 0, pTab->zName, 0);
75031 /* Reload the table, index and permanent trigger schemas. */
75032 zWhere = sqlite3MPrintf(pParse->db, "tbl_name=%Q", zName);
75033 if( !zWhere ) return;
75034 sqlite3VdbeAddOp4(v, OP_ParseSchema, iDb, 0, 0, zWhere, P4_DYNAMIC);
75036 #ifndef SQLITE_OMIT_TRIGGER
75037 /* Now, if the table is not stored in the temp database, reload any temp
75038 ** triggers. Don't use IN(...) in case SQLITE_OMIT_SUBQUERY is defined.
75040 if( (zWhere=whereTempTriggers(pParse, pTab))!=0 ){
75041 sqlite3VdbeAddOp4(v, OP_ParseSchema, 1, 0, 0, zWhere, P4_DYNAMIC);
75043 #endif
75047 ** Parameter zName is the name of a table that is about to be altered
75048 ** (either with ALTER TABLE ... RENAME TO or ALTER TABLE ... ADD COLUMN).
75049 ** If the table is a system table, this function leaves an error message
75050 ** in pParse->zErr (system tables may not be altered) and returns non-zero.
75052 ** Or, if zName is not a system table, zero is returned.
75054 static int isSystemTable(Parse *pParse, const char *zName){
75055 if( sqlite3Strlen30(zName)>6 && 0==sqlite3StrNICmp(zName, "sqlite_", 7) ){
75056 sqlite3ErrorMsg(pParse, "table %s may not be altered", zName);
75057 return 1;
75059 return 0;
75063 ** Generate code to implement the "ALTER TABLE xxx RENAME TO yyy"
75064 ** command.
75066 SQLITE_PRIVATE void sqlite3AlterRenameTable(
75067 Parse *pParse, /* Parser context. */
75068 SrcList *pSrc, /* The table to rename. */
75069 Token *pName /* The new table name. */
75071 int iDb; /* Database that contains the table */
75072 char *zDb; /* Name of database iDb */
75073 Table *pTab; /* Table being renamed */
75074 char *zName = 0; /* NULL-terminated version of pName */
75075 sqlite3 *db = pParse->db; /* Database connection */
75076 int nTabName; /* Number of UTF-8 characters in zTabName */
75077 const char *zTabName; /* Original name of the table */
75078 Vdbe *v;
75079 #ifndef SQLITE_OMIT_TRIGGER
75080 char *zWhere = 0; /* Where clause to locate temp triggers */
75081 #endif
75082 VTable *pVTab = 0; /* Non-zero if this is a v-tab with an xRename() */
75083 int savedDbFlags; /* Saved value of db->flags */
75085 savedDbFlags = db->flags;
75086 if( NEVER(db->mallocFailed) ) goto exit_rename_table;
75087 assert( pSrc->nSrc==1 );
75088 assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
75090 pTab = sqlite3LocateTable(pParse, 0, pSrc->a[0].zName, pSrc->a[0].zDatabase);
75091 if( !pTab ) goto exit_rename_table;
75092 iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
75093 zDb = db->aDb[iDb].zName;
75094 db->flags |= SQLITE_PreferBuiltin;
75096 /* Get a NULL terminated version of the new table name. */
75097 zName = sqlite3NameFromToken(db, pName);
75098 if( !zName ) goto exit_rename_table;
75100 /* Check that a table or index named 'zName' does not already exist
75101 ** in database iDb. If so, this is an error.
75103 if( sqlite3FindTable(db, zName, zDb) || sqlite3FindIndex(db, zName, zDb) ){
75104 sqlite3ErrorMsg(pParse,
75105 "there is already another table or index with this name: %s", zName);
75106 goto exit_rename_table;
75109 /* Make sure it is not a system table being altered, or a reserved name
75110 ** that the table is being renamed to.
75112 if( SQLITE_OK!=isSystemTable(pParse, pTab->zName) ){
75113 goto exit_rename_table;
75115 if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){ goto
75116 exit_rename_table;
75119 #ifndef SQLITE_OMIT_VIEW
75120 if( pTab->pSelect ){
75121 sqlite3ErrorMsg(pParse, "view %s may not be altered", pTab->zName);
75122 goto exit_rename_table;
75124 #endif
75126 #ifndef SQLITE_OMIT_AUTHORIZATION
75127 /* Invoke the authorization callback. */
75128 if( sqlite3AuthCheck(pParse, SQLITE_ALTER_TABLE, zDb, pTab->zName, 0) ){
75129 goto exit_rename_table;
75131 #endif
75133 #ifndef SQLITE_OMIT_VIRTUALTABLE
75134 if( sqlite3ViewGetColumnNames(pParse, pTab) ){
75135 goto exit_rename_table;
75137 if( IsVirtual(pTab) ){
75138 pVTab = sqlite3GetVTable(db, pTab);
75139 if( pVTab->pVtab->pModule->xRename==0 ){
75140 pVTab = 0;
75143 #endif
75145 /* Begin a transaction and code the VerifyCookie for database iDb.
75146 ** Then modify the schema cookie (since the ALTER TABLE modifies the
75147 ** schema). Open a statement transaction if the table is a virtual
75148 ** table.
75150 v = sqlite3GetVdbe(pParse);
75151 if( v==0 ){
75152 goto exit_rename_table;
75154 sqlite3BeginWriteOperation(pParse, pVTab!=0, iDb);
75155 sqlite3ChangeCookie(pParse, iDb);
75157 /* If this is a virtual table, invoke the xRename() function if
75158 ** one is defined. The xRename() callback will modify the names
75159 ** of any resources used by the v-table implementation (including other
75160 ** SQLite tables) that are identified by the name of the virtual table.
75162 #ifndef SQLITE_OMIT_VIRTUALTABLE
75163 if( pVTab ){
75164 int i = ++pParse->nMem;
75165 sqlite3VdbeAddOp4(v, OP_String8, 0, i, 0, zName, 0);
75166 sqlite3VdbeAddOp4(v, OP_VRename, i, 0, 0,(const char*)pVTab, P4_VTAB);
75167 sqlite3MayAbort(pParse);
75169 #endif
75171 /* figure out how many UTF-8 characters are in zName */
75172 zTabName = pTab->zName;
75173 nTabName = sqlite3Utf8CharLen(zTabName, -1);
75175 #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
75176 if( db->flags&SQLITE_ForeignKeys ){
75177 /* If foreign-key support is enabled, rewrite the CREATE TABLE
75178 ** statements corresponding to all child tables of foreign key constraints
75179 ** for which the renamed table is the parent table. */
75180 if( (zWhere=whereForeignKeys(pParse, pTab))!=0 ){
75181 sqlite3NestedParse(pParse,
75182 "UPDATE \"%w\".%s SET "
75183 "sql = sqlite_rename_parent(sql, %Q, %Q) "
75184 "WHERE %s;", zDb, SCHEMA_TABLE(iDb), zTabName, zName, zWhere);
75185 sqlite3DbFree(db, zWhere);
75188 #endif
75190 /* Modify the sqlite_master table to use the new table name. */
75191 sqlite3NestedParse(pParse,
75192 "UPDATE %Q.%s SET "
75193 #ifdef SQLITE_OMIT_TRIGGER
75194 "sql = sqlite_rename_table(sql, %Q), "
75195 #else
75196 "sql = CASE "
75197 "WHEN type = 'trigger' THEN sqlite_rename_trigger(sql, %Q)"
75198 "ELSE sqlite_rename_table(sql, %Q) END, "
75199 #endif
75200 "tbl_name = %Q, "
75201 "name = CASE "
75202 "WHEN type='table' THEN %Q "
75203 "WHEN name LIKE 'sqlite_autoindex%%' AND type='index' THEN "
75204 "'sqlite_autoindex_' || %Q || substr(name,%d+18) "
75205 "ELSE name END "
75206 "WHERE tbl_name=%Q AND "
75207 "(type='table' OR type='index' OR type='trigger');",
75208 zDb, SCHEMA_TABLE(iDb), zName, zName, zName,
75209 #ifndef SQLITE_OMIT_TRIGGER
75210 zName,
75211 #endif
75212 zName, nTabName, zTabName
75215 #ifndef SQLITE_OMIT_AUTOINCREMENT
75216 /* If the sqlite_sequence table exists in this database, then update
75217 ** it with the new table name.
75219 if( sqlite3FindTable(db, "sqlite_sequence", zDb) ){
75220 sqlite3NestedParse(pParse,
75221 "UPDATE \"%w\".sqlite_sequence set name = %Q WHERE name = %Q",
75222 zDb, zName, pTab->zName);
75224 #endif
75226 #ifndef SQLITE_OMIT_TRIGGER
75227 /* If there are TEMP triggers on this table, modify the sqlite_temp_master
75228 ** table. Don't do this if the table being ALTERed is itself located in
75229 ** the temp database.
75231 if( (zWhere=whereTempTriggers(pParse, pTab))!=0 ){
75232 sqlite3NestedParse(pParse,
75233 "UPDATE sqlite_temp_master SET "
75234 "sql = sqlite_rename_trigger(sql, %Q), "
75235 "tbl_name = %Q "
75236 "WHERE %s;", zName, zName, zWhere);
75237 sqlite3DbFree(db, zWhere);
75239 #endif
75241 #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
75242 if( db->flags&SQLITE_ForeignKeys ){
75243 FKey *p;
75244 for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
75245 Table *pFrom = p->pFrom;
75246 if( pFrom!=pTab ){
75247 reloadTableSchema(pParse, p->pFrom, pFrom->zName);
75251 #endif
75253 /* Drop and reload the internal table schema. */
75254 reloadTableSchema(pParse, pTab, zName);
75256 exit_rename_table:
75257 sqlite3SrcListDelete(db, pSrc);
75258 sqlite3DbFree(db, zName);
75259 db->flags = savedDbFlags;
75264 ** Generate code to make sure the file format number is at least minFormat.
75265 ** The generated code will increase the file format number if necessary.
75267 SQLITE_PRIVATE void sqlite3MinimumFileFormat(Parse *pParse, int iDb, int minFormat){
75268 Vdbe *v;
75269 v = sqlite3GetVdbe(pParse);
75270 /* The VDBE should have been allocated before this routine is called.
75271 ** If that allocation failed, we would have quit before reaching this
75272 ** point */
75273 if( ALWAYS(v) ){
75274 int r1 = sqlite3GetTempReg(pParse);
75275 int r2 = sqlite3GetTempReg(pParse);
75276 int j1;
75277 sqlite3VdbeAddOp3(v, OP_ReadCookie, iDb, r1, BTREE_FILE_FORMAT);
75278 sqlite3VdbeUsesBtree(v, iDb);
75279 sqlite3VdbeAddOp2(v, OP_Integer, minFormat, r2);
75280 j1 = sqlite3VdbeAddOp3(v, OP_Ge, r2, 0, r1);
75281 sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_FILE_FORMAT, r2);
75282 sqlite3VdbeJumpHere(v, j1);
75283 sqlite3ReleaseTempReg(pParse, r1);
75284 sqlite3ReleaseTempReg(pParse, r2);
75289 ** This function is called after an "ALTER TABLE ... ADD" statement
75290 ** has been parsed. Argument pColDef contains the text of the new
75291 ** column definition.
75293 ** The Table structure pParse->pNewTable was extended to include
75294 ** the new column during parsing.
75296 SQLITE_PRIVATE void sqlite3AlterFinishAddColumn(Parse *pParse, Token *pColDef){
75297 Table *pNew; /* Copy of pParse->pNewTable */
75298 Table *pTab; /* Table being altered */
75299 int iDb; /* Database number */
75300 const char *zDb; /* Database name */
75301 const char *zTab; /* Table name */
75302 char *zCol; /* Null-terminated column definition */
75303 Column *pCol; /* The new column */
75304 Expr *pDflt; /* Default value for the new column */
75305 sqlite3 *db; /* The database connection; */
75307 db = pParse->db;
75308 if( pParse->nErr || db->mallocFailed ) return;
75309 pNew = pParse->pNewTable;
75310 assert( pNew );
75312 assert( sqlite3BtreeHoldsAllMutexes(db) );
75313 iDb = sqlite3SchemaToIndex(db, pNew->pSchema);
75314 zDb = db->aDb[iDb].zName;
75315 zTab = &pNew->zName[16]; /* Skip the "sqlite_altertab_" prefix on the name */
75316 pCol = &pNew->aCol[pNew->nCol-1];
75317 pDflt = pCol->pDflt;
75318 pTab = sqlite3FindTable(db, zTab, zDb);
75319 assert( pTab );
75321 #ifndef SQLITE_OMIT_AUTHORIZATION
75322 /* Invoke the authorization callback. */
75323 if( sqlite3AuthCheck(pParse, SQLITE_ALTER_TABLE, zDb, pTab->zName, 0) ){
75324 return;
75326 #endif
75328 /* If the default value for the new column was specified with a
75329 ** literal NULL, then set pDflt to 0. This simplifies checking
75330 ** for an SQL NULL default below.
75332 if( pDflt && pDflt->op==TK_NULL ){
75333 pDflt = 0;
75336 /* Check that the new column is not specified as PRIMARY KEY or UNIQUE.
75337 ** If there is a NOT NULL constraint, then the default value for the
75338 ** column must not be NULL.
75340 if( pCol->isPrimKey ){
75341 sqlite3ErrorMsg(pParse, "Cannot add a PRIMARY KEY column");
75342 return;
75344 if( pNew->pIndex ){
75345 sqlite3ErrorMsg(pParse, "Cannot add a UNIQUE column");
75346 return;
75348 if( (db->flags&SQLITE_ForeignKeys) && pNew->pFKey && pDflt ){
75349 sqlite3ErrorMsg(pParse,
75350 "Cannot add a REFERENCES column with non-NULL default value");
75351 return;
75353 if( pCol->notNull && !pDflt ){
75354 sqlite3ErrorMsg(pParse,
75355 "Cannot add a NOT NULL column with default value NULL");
75356 return;
75359 /* Ensure the default expression is something that sqlite3ValueFromExpr()
75360 ** can handle (i.e. not CURRENT_TIME etc.)
75362 if( pDflt ){
75363 sqlite3_value *pVal;
75364 if( sqlite3ValueFromExpr(db, pDflt, SQLITE_UTF8, SQLITE_AFF_NONE, &pVal) ){
75365 db->mallocFailed = 1;
75366 return;
75368 if( !pVal ){
75369 sqlite3ErrorMsg(pParse, "Cannot add a column with non-constant default");
75370 return;
75372 sqlite3ValueFree(pVal);
75375 /* Modify the CREATE TABLE statement. */
75376 zCol = sqlite3DbStrNDup(db, (char*)pColDef->z, pColDef->n);
75377 if( zCol ){
75378 char *zEnd = &zCol[pColDef->n-1];
75379 int savedDbFlags = db->flags;
75380 while( zEnd>zCol && (*zEnd==';' || sqlite3Isspace(*zEnd)) ){
75381 *zEnd-- = '\0';
75383 db->flags |= SQLITE_PreferBuiltin;
75384 sqlite3NestedParse(pParse,
75385 "UPDATE \"%w\".%s SET "
75386 "sql = substr(sql,1,%d) || ', ' || %Q || substr(sql,%d) "
75387 "WHERE type = 'table' AND name = %Q",
75388 zDb, SCHEMA_TABLE(iDb), pNew->addColOffset, zCol, pNew->addColOffset+1,
75389 zTab
75391 sqlite3DbFree(db, zCol);
75392 db->flags = savedDbFlags;
75395 /* If the default value of the new column is NULL, then set the file
75396 ** format to 2. If the default value of the new column is not NULL,
75397 ** the file format becomes 3.
75399 sqlite3MinimumFileFormat(pParse, iDb, pDflt ? 3 : 2);
75401 /* Reload the schema of the modified table. */
75402 reloadTableSchema(pParse, pTab, pTab->zName);
75406 ** This function is called by the parser after the table-name in
75407 ** an "ALTER TABLE <table-name> ADD" statement is parsed. Argument
75408 ** pSrc is the full-name of the table being altered.
75410 ** This routine makes a (partial) copy of the Table structure
75411 ** for the table being altered and sets Parse.pNewTable to point
75412 ** to it. Routines called by the parser as the column definition
75413 ** is parsed (i.e. sqlite3AddColumn()) add the new Column data to
75414 ** the copy. The copy of the Table structure is deleted by tokenize.c
75415 ** after parsing is finished.
75417 ** Routine sqlite3AlterFinishAddColumn() will be called to complete
75418 ** coding the "ALTER TABLE ... ADD" statement.
75420 SQLITE_PRIVATE void sqlite3AlterBeginAddColumn(Parse *pParse, SrcList *pSrc){
75421 Table *pNew;
75422 Table *pTab;
75423 Vdbe *v;
75424 int iDb;
75425 int i;
75426 int nAlloc;
75427 sqlite3 *db = pParse->db;
75429 /* Look up the table being altered. */
75430 assert( pParse->pNewTable==0 );
75431 assert( sqlite3BtreeHoldsAllMutexes(db) );
75432 if( db->mallocFailed ) goto exit_begin_add_column;
75433 pTab = sqlite3LocateTable(pParse, 0, pSrc->a[0].zName, pSrc->a[0].zDatabase);
75434 if( !pTab ) goto exit_begin_add_column;
75436 #ifndef SQLITE_OMIT_VIRTUALTABLE
75437 if( IsVirtual(pTab) ){
75438 sqlite3ErrorMsg(pParse, "virtual tables may not be altered");
75439 goto exit_begin_add_column;
75441 #endif
75443 /* Make sure this is not an attempt to ALTER a view. */
75444 if( pTab->pSelect ){
75445 sqlite3ErrorMsg(pParse, "Cannot add a column to a view");
75446 goto exit_begin_add_column;
75448 if( SQLITE_OK!=isSystemTable(pParse, pTab->zName) ){
75449 goto exit_begin_add_column;
75452 assert( pTab->addColOffset>0 );
75453 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
75455 /* Put a copy of the Table struct in Parse.pNewTable for the
75456 ** sqlite3AddColumn() function and friends to modify. But modify
75457 ** the name by adding an "sqlite_altertab_" prefix. By adding this
75458 ** prefix, we insure that the name will not collide with an existing
75459 ** table because user table are not allowed to have the "sqlite_"
75460 ** prefix on their name.
75462 pNew = (Table*)sqlite3DbMallocZero(db, sizeof(Table));
75463 if( !pNew ) goto exit_begin_add_column;
75464 pParse->pNewTable = pNew;
75465 pNew->nRef = 1;
75466 pNew->nCol = pTab->nCol;
75467 assert( pNew->nCol>0 );
75468 nAlloc = (((pNew->nCol-1)/8)*8)+8;
75469 assert( nAlloc>=pNew->nCol && nAlloc%8==0 && nAlloc-pNew->nCol<8 );
75470 pNew->aCol = (Column*)sqlite3DbMallocZero(db, sizeof(Column)*nAlloc);
75471 pNew->zName = sqlite3MPrintf(db, "sqlite_altertab_%s", pTab->zName);
75472 if( !pNew->aCol || !pNew->zName ){
75473 db->mallocFailed = 1;
75474 goto exit_begin_add_column;
75476 memcpy(pNew->aCol, pTab->aCol, sizeof(Column)*pNew->nCol);
75477 for(i=0; i<pNew->nCol; i++){
75478 Column *pCol = &pNew->aCol[i];
75479 pCol->zName = sqlite3DbStrDup(db, pCol->zName);
75480 pCol->zColl = 0;
75481 pCol->zType = 0;
75482 pCol->pDflt = 0;
75483 pCol->zDflt = 0;
75485 pNew->pSchema = db->aDb[iDb].pSchema;
75486 pNew->addColOffset = pTab->addColOffset;
75487 pNew->nRef = 1;
75489 /* Begin a transaction and increment the schema cookie. */
75490 sqlite3BeginWriteOperation(pParse, 0, iDb);
75491 v = sqlite3GetVdbe(pParse);
75492 if( !v ) goto exit_begin_add_column;
75493 sqlite3ChangeCookie(pParse, iDb);
75495 exit_begin_add_column:
75496 sqlite3SrcListDelete(db, pSrc);
75497 return;
75499 #endif /* SQLITE_ALTER_TABLE */
75501 /************** End of alter.c ***********************************************/
75502 /************** Begin file analyze.c *****************************************/
75504 ** 2005 July 8
75506 ** The author disclaims copyright to this source code. In place of
75507 ** a legal notice, here is a blessing:
75509 ** May you do good and not evil.
75510 ** May you find forgiveness for yourself and forgive others.
75511 ** May you share freely, never taking more than you give.
75513 *************************************************************************
75514 ** This file contains code associated with the ANALYZE command.
75516 #ifndef SQLITE_OMIT_ANALYZE
75519 ** This routine generates code that opens the sqlite_stat1 table for
75520 ** writing with cursor iStatCur. If the library was built with the
75521 ** SQLITE_ENABLE_STAT2 macro defined, then the sqlite_stat2 table is
75522 ** opened for writing using cursor (iStatCur+1)
75524 ** If the sqlite_stat1 tables does not previously exist, it is created.
75525 ** Similarly, if the sqlite_stat2 table does not exist and the library
75526 ** is compiled with SQLITE_ENABLE_STAT2 defined, it is created.
75528 ** Argument zWhere may be a pointer to a buffer containing a table name,
75529 ** or it may be a NULL pointer. If it is not NULL, then all entries in
75530 ** the sqlite_stat1 and (if applicable) sqlite_stat2 tables associated
75531 ** with the named table are deleted. If zWhere==0, then code is generated
75532 ** to delete all stat table entries.
75534 static void openStatTable(
75535 Parse *pParse, /* Parsing context */
75536 int iDb, /* The database we are looking in */
75537 int iStatCur, /* Open the sqlite_stat1 table on this cursor */
75538 const char *zWhere, /* Delete entries for this table or index */
75539 const char *zWhereType /* Either "tbl" or "idx" */
75541 static const struct {
75542 const char *zName;
75543 const char *zCols;
75544 } aTable[] = {
75545 { "sqlite_stat1", "tbl,idx,stat" },
75546 #ifdef SQLITE_ENABLE_STAT2
75547 { "sqlite_stat2", "tbl,idx,sampleno,sample" },
75548 #endif
75551 int aRoot[] = {0, 0};
75552 u8 aCreateTbl[] = {0, 0};
75554 int i;
75555 sqlite3 *db = pParse->db;
75556 Db *pDb;
75557 Vdbe *v = sqlite3GetVdbe(pParse);
75558 if( v==0 ) return;
75559 assert( sqlite3BtreeHoldsAllMutexes(db) );
75560 assert( sqlite3VdbeDb(v)==db );
75561 pDb = &db->aDb[iDb];
75563 for(i=0; i<ArraySize(aTable); i++){
75564 const char *zTab = aTable[i].zName;
75565 Table *pStat;
75566 if( (pStat = sqlite3FindTable(db, zTab, pDb->zName))==0 ){
75567 /* The sqlite_stat[12] table does not exist. Create it. Note that a
75568 ** side-effect of the CREATE TABLE statement is to leave the rootpage
75569 ** of the new table in register pParse->regRoot. This is important
75570 ** because the OpenWrite opcode below will be needing it. */
75571 sqlite3NestedParse(pParse,
75572 "CREATE TABLE %Q.%s(%s)", pDb->zName, zTab, aTable[i].zCols
75574 aRoot[i] = pParse->regRoot;
75575 aCreateTbl[i] = 1;
75576 }else{
75577 /* The table already exists. If zWhere is not NULL, delete all entries
75578 ** associated with the table zWhere. If zWhere is NULL, delete the
75579 ** entire contents of the table. */
75580 aRoot[i] = pStat->tnum;
75581 sqlite3TableLock(pParse, iDb, aRoot[i], 1, zTab);
75582 if( zWhere ){
75583 sqlite3NestedParse(pParse,
75584 "DELETE FROM %Q.%s WHERE %s=%Q", pDb->zName, zTab, zWhereType, zWhere
75586 }else{
75587 /* The sqlite_stat[12] table already exists. Delete all rows. */
75588 sqlite3VdbeAddOp2(v, OP_Clear, aRoot[i], iDb);
75593 /* Open the sqlite_stat[12] tables for writing. */
75594 for(i=0; i<ArraySize(aTable); i++){
75595 sqlite3VdbeAddOp3(v, OP_OpenWrite, iStatCur+i, aRoot[i], iDb);
75596 sqlite3VdbeChangeP4(v, -1, (char *)3, P4_INT32);
75597 sqlite3VdbeChangeP5(v, aCreateTbl[i]);
75602 ** Generate code to do an analysis of all indices associated with
75603 ** a single table.
75605 static void analyzeOneTable(
75606 Parse *pParse, /* Parser context */
75607 Table *pTab, /* Table whose indices are to be analyzed */
75608 Index *pOnlyIdx, /* If not NULL, only analyze this one index */
75609 int iStatCur, /* Index of VdbeCursor that writes the sqlite_stat1 table */
75610 int iMem /* Available memory locations begin here */
75612 sqlite3 *db = pParse->db; /* Database handle */
75613 Index *pIdx; /* An index to being analyzed */
75614 int iIdxCur; /* Cursor open on index being analyzed */
75615 Vdbe *v; /* The virtual machine being built up */
75616 int i; /* Loop counter */
75617 int topOfLoop; /* The top of the loop */
75618 int endOfLoop; /* The end of the loop */
75619 int jZeroRows = -1; /* Jump from here if number of rows is zero */
75620 int iDb; /* Index of database containing pTab */
75621 int regTabname = iMem++; /* Register containing table name */
75622 int regIdxname = iMem++; /* Register containing index name */
75623 int regSampleno = iMem++; /* Register containing next sample number */
75624 int regCol = iMem++; /* Content of a column analyzed table */
75625 int regRec = iMem++; /* Register holding completed record */
75626 int regTemp = iMem++; /* Temporary use register */
75627 int regRowid = iMem++; /* Rowid for the inserted record */
75629 #ifdef SQLITE_ENABLE_STAT2
75630 int addr = 0; /* Instruction address */
75631 int regTemp2 = iMem++; /* Temporary use register */
75632 int regSamplerecno = iMem++; /* Index of next sample to record */
75633 int regRecno = iMem++; /* Current sample index */
75634 int regLast = iMem++; /* Index of last sample to record */
75635 int regFirst = iMem++; /* Index of first sample to record */
75636 #endif
75638 v = sqlite3GetVdbe(pParse);
75639 if( v==0 || NEVER(pTab==0) ){
75640 return;
75642 if( pTab->tnum==0 ){
75643 /* Do not gather statistics on views or virtual tables */
75644 return;
75646 if( sqlite3_strnicmp(pTab->zName, "sqlite_", 7)==0 ){
75647 /* Do not gather statistics on system tables */
75648 return;
75650 assert( sqlite3BtreeHoldsAllMutexes(db) );
75651 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
75652 assert( iDb>=0 );
75653 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
75654 #ifndef SQLITE_OMIT_AUTHORIZATION
75655 if( sqlite3AuthCheck(pParse, SQLITE_ANALYZE, pTab->zName, 0,
75656 db->aDb[iDb].zName ) ){
75657 return;
75659 #endif
75661 /* Establish a read-lock on the table at the shared-cache level. */
75662 sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
75664 iIdxCur = pParse->nTab++;
75665 sqlite3VdbeAddOp4(v, OP_String8, 0, regTabname, 0, pTab->zName, 0);
75666 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
75667 int nCol;
75668 KeyInfo *pKey;
75670 if( pOnlyIdx && pOnlyIdx!=pIdx ) continue;
75671 nCol = pIdx->nColumn;
75672 pKey = sqlite3IndexKeyinfo(pParse, pIdx);
75673 if( iMem+1+(nCol*2)>pParse->nMem ){
75674 pParse->nMem = iMem+1+(nCol*2);
75677 /* Open a cursor to the index to be analyzed. */
75678 assert( iDb==sqlite3SchemaToIndex(db, pIdx->pSchema) );
75679 sqlite3VdbeAddOp4(v, OP_OpenRead, iIdxCur, pIdx->tnum, iDb,
75680 (char *)pKey, P4_KEYINFO_HANDOFF);
75681 VdbeComment((v, "%s", pIdx->zName));
75683 /* Populate the register containing the index name. */
75684 sqlite3VdbeAddOp4(v, OP_String8, 0, regIdxname, 0, pIdx->zName, 0);
75686 #ifdef SQLITE_ENABLE_STAT2
75688 /* If this iteration of the loop is generating code to analyze the
75689 ** first index in the pTab->pIndex list, then register regLast has
75690 ** not been populated. In this case populate it now. */
75691 if( pTab->pIndex==pIdx ){
75692 sqlite3VdbeAddOp2(v, OP_Integer, SQLITE_INDEX_SAMPLES, regSamplerecno);
75693 sqlite3VdbeAddOp2(v, OP_Integer, SQLITE_INDEX_SAMPLES*2-1, regTemp);
75694 sqlite3VdbeAddOp2(v, OP_Integer, SQLITE_INDEX_SAMPLES*2, regTemp2);
75696 sqlite3VdbeAddOp2(v, OP_Count, iIdxCur, regLast);
75697 sqlite3VdbeAddOp2(v, OP_Null, 0, regFirst);
75698 addr = sqlite3VdbeAddOp3(v, OP_Lt, regSamplerecno, 0, regLast);
75699 sqlite3VdbeAddOp3(v, OP_Divide, regTemp2, regLast, regFirst);
75700 sqlite3VdbeAddOp3(v, OP_Multiply, regLast, regTemp, regLast);
75701 sqlite3VdbeAddOp2(v, OP_AddImm, regLast, SQLITE_INDEX_SAMPLES*2-2);
75702 sqlite3VdbeAddOp3(v, OP_Divide, regTemp2, regLast, regLast);
75703 sqlite3VdbeJumpHere(v, addr);
75706 /* Zero the regSampleno and regRecno registers. */
75707 sqlite3VdbeAddOp2(v, OP_Integer, 0, regSampleno);
75708 sqlite3VdbeAddOp2(v, OP_Integer, 0, regRecno);
75709 sqlite3VdbeAddOp2(v, OP_Copy, regFirst, regSamplerecno);
75710 #endif
75712 /* The block of memory cells initialized here is used as follows.
75714 ** iMem:
75715 ** The total number of rows in the table.
75717 ** iMem+1 .. iMem+nCol:
75718 ** Number of distinct entries in index considering the
75719 ** left-most N columns only, where N is between 1 and nCol,
75720 ** inclusive.
75722 ** iMem+nCol+1 .. Mem+2*nCol:
75723 ** Previous value of indexed columns, from left to right.
75725 ** Cells iMem through iMem+nCol are initialized to 0. The others are
75726 ** initialized to contain an SQL NULL.
75728 for(i=0; i<=nCol; i++){
75729 sqlite3VdbeAddOp2(v, OP_Integer, 0, iMem+i);
75731 for(i=0; i<nCol; i++){
75732 sqlite3VdbeAddOp2(v, OP_Null, 0, iMem+nCol+i+1);
75735 /* Start the analysis loop. This loop runs through all the entries in
75736 ** the index b-tree. */
75737 endOfLoop = sqlite3VdbeMakeLabel(v);
75738 sqlite3VdbeAddOp2(v, OP_Rewind, iIdxCur, endOfLoop);
75739 topOfLoop = sqlite3VdbeCurrentAddr(v);
75740 sqlite3VdbeAddOp2(v, OP_AddImm, iMem, 1);
75742 for(i=0; i<nCol; i++){
75743 CollSeq *pColl;
75744 sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, i, regCol);
75745 if( i==0 ){
75746 #ifdef SQLITE_ENABLE_STAT2
75747 /* Check if the record that cursor iIdxCur points to contains a
75748 ** value that should be stored in the sqlite_stat2 table. If so,
75749 ** store it. */
75750 int ne = sqlite3VdbeAddOp3(v, OP_Ne, regRecno, 0, regSamplerecno);
75751 assert( regTabname+1==regIdxname
75752 && regTabname+2==regSampleno
75753 && regTabname+3==regCol
75755 sqlite3VdbeChangeP5(v, SQLITE_JUMPIFNULL);
75756 sqlite3VdbeAddOp4(v, OP_MakeRecord, regTabname, 4, regRec, "aaab", 0);
75757 sqlite3VdbeAddOp2(v, OP_NewRowid, iStatCur+1, regRowid);
75758 sqlite3VdbeAddOp3(v, OP_Insert, iStatCur+1, regRec, regRowid);
75760 /* Calculate new values for regSamplerecno and regSampleno.
75762 ** sampleno = sampleno + 1
75763 ** samplerecno = samplerecno+(remaining records)/(remaining samples)
75765 sqlite3VdbeAddOp2(v, OP_AddImm, regSampleno, 1);
75766 sqlite3VdbeAddOp3(v, OP_Subtract, regRecno, regLast, regTemp);
75767 sqlite3VdbeAddOp2(v, OP_AddImm, regTemp, -1);
75768 sqlite3VdbeAddOp2(v, OP_Integer, SQLITE_INDEX_SAMPLES, regTemp2);
75769 sqlite3VdbeAddOp3(v, OP_Subtract, regSampleno, regTemp2, regTemp2);
75770 sqlite3VdbeAddOp3(v, OP_Divide, regTemp2, regTemp, regTemp);
75771 sqlite3VdbeAddOp3(v, OP_Add, regSamplerecno, regTemp, regSamplerecno);
75773 sqlite3VdbeJumpHere(v, ne);
75774 sqlite3VdbeAddOp2(v, OP_AddImm, regRecno, 1);
75775 #endif
75777 /* Always record the very first row */
75778 sqlite3VdbeAddOp1(v, OP_IfNot, iMem+1);
75780 assert( pIdx->azColl!=0 );
75781 assert( pIdx->azColl[i]!=0 );
75782 pColl = sqlite3LocateCollSeq(pParse, pIdx->azColl[i]);
75783 sqlite3VdbeAddOp4(v, OP_Ne, regCol, 0, iMem+nCol+i+1,
75784 (char*)pColl, P4_COLLSEQ);
75785 sqlite3VdbeChangeP5(v, SQLITE_NULLEQ);
75787 if( db->mallocFailed ){
75788 /* If a malloc failure has occurred, then the result of the expression
75789 ** passed as the second argument to the call to sqlite3VdbeJumpHere()
75790 ** below may be negative. Which causes an assert() to fail (or an
75791 ** out-of-bounds write if SQLITE_DEBUG is not defined). */
75792 return;
75794 sqlite3VdbeAddOp2(v, OP_Goto, 0, endOfLoop);
75795 for(i=0; i<nCol; i++){
75796 int addr2 = sqlite3VdbeCurrentAddr(v) - (nCol*2);
75797 if( i==0 ){
75798 sqlite3VdbeJumpHere(v, addr2-1); /* Set jump dest for the OP_IfNot */
75800 sqlite3VdbeJumpHere(v, addr2); /* Set jump dest for the OP_Ne */
75801 sqlite3VdbeAddOp2(v, OP_AddImm, iMem+i+1, 1);
75802 sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, i, iMem+nCol+i+1);
75805 /* End of the analysis loop. */
75806 sqlite3VdbeResolveLabel(v, endOfLoop);
75807 sqlite3VdbeAddOp2(v, OP_Next, iIdxCur, topOfLoop);
75808 sqlite3VdbeAddOp1(v, OP_Close, iIdxCur);
75810 /* Store the results in sqlite_stat1.
75812 ** The result is a single row of the sqlite_stat1 table. The first
75813 ** two columns are the names of the table and index. The third column
75814 ** is a string composed of a list of integer statistics about the
75815 ** index. The first integer in the list is the total number of entries
75816 ** in the index. There is one additional integer in the list for each
75817 ** column of the table. This additional integer is a guess of how many
75818 ** rows of the table the index will select. If D is the count of distinct
75819 ** values and K is the total number of rows, then the integer is computed
75820 ** as:
75822 ** I = (K+D-1)/D
75824 ** If K==0 then no entry is made into the sqlite_stat1 table.
75825 ** If K>0 then it is always the case the D>0 so division by zero
75826 ** is never possible.
75828 sqlite3VdbeAddOp2(v, OP_SCopy, iMem, regSampleno);
75829 if( jZeroRows<0 ){
75830 jZeroRows = sqlite3VdbeAddOp1(v, OP_IfNot, iMem);
75832 for(i=0; i<nCol; i++){
75833 sqlite3VdbeAddOp4(v, OP_String8, 0, regTemp, 0, " ", 0);
75834 sqlite3VdbeAddOp3(v, OP_Concat, regTemp, regSampleno, regSampleno);
75835 sqlite3VdbeAddOp3(v, OP_Add, iMem, iMem+i+1, regTemp);
75836 sqlite3VdbeAddOp2(v, OP_AddImm, regTemp, -1);
75837 sqlite3VdbeAddOp3(v, OP_Divide, iMem+i+1, regTemp, regTemp);
75838 sqlite3VdbeAddOp1(v, OP_ToInt, regTemp);
75839 sqlite3VdbeAddOp3(v, OP_Concat, regTemp, regSampleno, regSampleno);
75841 sqlite3VdbeAddOp4(v, OP_MakeRecord, regTabname, 3, regRec, "aaa", 0);
75842 sqlite3VdbeAddOp2(v, OP_NewRowid, iStatCur, regRowid);
75843 sqlite3VdbeAddOp3(v, OP_Insert, iStatCur, regRec, regRowid);
75844 sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
75847 /* If the table has no indices, create a single sqlite_stat1 entry
75848 ** containing NULL as the index name and the row count as the content.
75850 if( pTab->pIndex==0 ){
75851 sqlite3VdbeAddOp3(v, OP_OpenRead, iIdxCur, pTab->tnum, iDb);
75852 VdbeComment((v, "%s", pTab->zName));
75853 sqlite3VdbeAddOp2(v, OP_Count, iIdxCur, regSampleno);
75854 sqlite3VdbeAddOp1(v, OP_Close, iIdxCur);
75855 jZeroRows = sqlite3VdbeAddOp1(v, OP_IfNot, regSampleno);
75856 }else{
75857 sqlite3VdbeJumpHere(v, jZeroRows);
75858 jZeroRows = sqlite3VdbeAddOp0(v, OP_Goto);
75860 sqlite3VdbeAddOp2(v, OP_Null, 0, regIdxname);
75861 sqlite3VdbeAddOp4(v, OP_MakeRecord, regTabname, 3, regRec, "aaa", 0);
75862 sqlite3VdbeAddOp2(v, OP_NewRowid, iStatCur, regRowid);
75863 sqlite3VdbeAddOp3(v, OP_Insert, iStatCur, regRec, regRowid);
75864 sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
75865 if( pParse->nMem<regRec ) pParse->nMem = regRec;
75866 sqlite3VdbeJumpHere(v, jZeroRows);
75870 ** Generate code that will cause the most recent index analysis to
75871 ** be loaded into internal hash tables where is can be used.
75873 static void loadAnalysis(Parse *pParse, int iDb){
75874 Vdbe *v = sqlite3GetVdbe(pParse);
75875 if( v ){
75876 sqlite3VdbeAddOp1(v, OP_LoadAnalysis, iDb);
75881 ** Generate code that will do an analysis of an entire database
75883 static void analyzeDatabase(Parse *pParse, int iDb){
75884 sqlite3 *db = pParse->db;
75885 Schema *pSchema = db->aDb[iDb].pSchema; /* Schema of database iDb */
75886 HashElem *k;
75887 int iStatCur;
75888 int iMem;
75890 sqlite3BeginWriteOperation(pParse, 0, iDb);
75891 iStatCur = pParse->nTab;
75892 pParse->nTab += 2;
75893 openStatTable(pParse, iDb, iStatCur, 0, 0);
75894 iMem = pParse->nMem+1;
75895 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
75896 for(k=sqliteHashFirst(&pSchema->tblHash); k; k=sqliteHashNext(k)){
75897 Table *pTab = (Table*)sqliteHashData(k);
75898 analyzeOneTable(pParse, pTab, 0, iStatCur, iMem);
75900 loadAnalysis(pParse, iDb);
75904 ** Generate code that will do an analysis of a single table in
75905 ** a database. If pOnlyIdx is not NULL then it is a single index
75906 ** in pTab that should be analyzed.
75908 static void analyzeTable(Parse *pParse, Table *pTab, Index *pOnlyIdx){
75909 int iDb;
75910 int iStatCur;
75912 assert( pTab!=0 );
75913 assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
75914 iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
75915 sqlite3BeginWriteOperation(pParse, 0, iDb);
75916 iStatCur = pParse->nTab;
75917 pParse->nTab += 2;
75918 if( pOnlyIdx ){
75919 openStatTable(pParse, iDb, iStatCur, pOnlyIdx->zName, "idx");
75920 }else{
75921 openStatTable(pParse, iDb, iStatCur, pTab->zName, "tbl");
75923 analyzeOneTable(pParse, pTab, pOnlyIdx, iStatCur, pParse->nMem+1);
75924 loadAnalysis(pParse, iDb);
75928 ** Generate code for the ANALYZE command. The parser calls this routine
75929 ** when it recognizes an ANALYZE command.
75931 ** ANALYZE -- 1
75932 ** ANALYZE <database> -- 2
75933 ** ANALYZE ?<database>.?<tablename> -- 3
75935 ** Form 1 causes all indices in all attached databases to be analyzed.
75936 ** Form 2 analyzes all indices the single database named.
75937 ** Form 3 analyzes all indices associated with the named table.
75939 SQLITE_PRIVATE void sqlite3Analyze(Parse *pParse, Token *pName1, Token *pName2){
75940 sqlite3 *db = pParse->db;
75941 int iDb;
75942 int i;
75943 char *z, *zDb;
75944 Table *pTab;
75945 Index *pIdx;
75946 Token *pTableName;
75948 /* Read the database schema. If an error occurs, leave an error message
75949 ** and code in pParse and return NULL. */
75950 assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
75951 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
75952 return;
75955 assert( pName2!=0 || pName1==0 );
75956 if( pName1==0 ){
75957 /* Form 1: Analyze everything */
75958 for(i=0; i<db->nDb; i++){
75959 if( i==1 ) continue; /* Do not analyze the TEMP database */
75960 analyzeDatabase(pParse, i);
75962 }else if( pName2->n==0 ){
75963 /* Form 2: Analyze the database or table named */
75964 iDb = sqlite3FindDb(db, pName1);
75965 if( iDb>=0 ){
75966 analyzeDatabase(pParse, iDb);
75967 }else{
75968 z = sqlite3NameFromToken(db, pName1);
75969 if( z ){
75970 if( (pIdx = sqlite3FindIndex(db, z, 0))!=0 ){
75971 analyzeTable(pParse, pIdx->pTable, pIdx);
75972 }else if( (pTab = sqlite3LocateTable(pParse, 0, z, 0))!=0 ){
75973 analyzeTable(pParse, pTab, 0);
75975 sqlite3DbFree(db, z);
75978 }else{
75979 /* Form 3: Analyze the fully qualified table name */
75980 iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pTableName);
75981 if( iDb>=0 ){
75982 zDb = db->aDb[iDb].zName;
75983 z = sqlite3NameFromToken(db, pTableName);
75984 if( z ){
75985 if( (pIdx = sqlite3FindIndex(db, z, zDb))!=0 ){
75986 analyzeTable(pParse, pIdx->pTable, pIdx);
75987 }else if( (pTab = sqlite3LocateTable(pParse, 0, z, zDb))!=0 ){
75988 analyzeTable(pParse, pTab, 0);
75990 sqlite3DbFree(db, z);
75997 ** Used to pass information from the analyzer reader through to the
75998 ** callback routine.
76000 typedef struct analysisInfo analysisInfo;
76001 struct analysisInfo {
76002 sqlite3 *db;
76003 const char *zDatabase;
76007 ** This callback is invoked once for each index when reading the
76008 ** sqlite_stat1 table.
76010 ** argv[0] = name of the table
76011 ** argv[1] = name of the index (might be NULL)
76012 ** argv[2] = results of analysis - on integer for each column
76014 ** Entries for which argv[1]==NULL simply record the number of rows in
76015 ** the table.
76017 static int analysisLoader(void *pData, int argc, char **argv, char **NotUsed){
76018 analysisInfo *pInfo = (analysisInfo*)pData;
76019 Index *pIndex;
76020 Table *pTable;
76021 int i, c, n;
76022 unsigned int v;
76023 const char *z;
76025 assert( argc==3 );
76026 UNUSED_PARAMETER2(NotUsed, argc);
76028 if( argv==0 || argv[0]==0 || argv[2]==0 ){
76029 return 0;
76031 pTable = sqlite3FindTable(pInfo->db, argv[0], pInfo->zDatabase);
76032 if( pTable==0 ){
76033 return 0;
76035 if( argv[1] ){
76036 pIndex = sqlite3FindIndex(pInfo->db, argv[1], pInfo->zDatabase);
76037 }else{
76038 pIndex = 0;
76040 n = pIndex ? pIndex->nColumn : 0;
76041 z = argv[2];
76042 for(i=0; *z && i<=n; i++){
76043 v = 0;
76044 while( (c=z[0])>='0' && c<='9' ){
76045 v = v*10 + c - '0';
76046 z++;
76048 if( i==0 ) pTable->nRowEst = v;
76049 if( pIndex==0 ) break;
76050 pIndex->aiRowEst[i] = v;
76051 if( *z==' ' ) z++;
76052 if( strcmp(z, "unordered")==0 ){
76053 pIndex->bUnordered = 1;
76054 break;
76057 return 0;
76061 ** If the Index.aSample variable is not NULL, delete the aSample[] array
76062 ** and its contents.
76064 SQLITE_PRIVATE void sqlite3DeleteIndexSamples(sqlite3 *db, Index *pIdx){
76065 #ifdef SQLITE_ENABLE_STAT2
76066 if( pIdx->aSample ){
76067 int j;
76068 for(j=0; j<SQLITE_INDEX_SAMPLES; j++){
76069 IndexSample *p = &pIdx->aSample[j];
76070 if( p->eType==SQLITE_TEXT || p->eType==SQLITE_BLOB ){
76071 sqlite3DbFree(db, p->u.z);
76074 sqlite3DbFree(db, pIdx->aSample);
76076 #else
76077 UNUSED_PARAMETER(db);
76078 UNUSED_PARAMETER(pIdx);
76079 #endif
76083 ** Load the content of the sqlite_stat1 and sqlite_stat2 tables. The
76084 ** contents of sqlite_stat1 are used to populate the Index.aiRowEst[]
76085 ** arrays. The contents of sqlite_stat2 are used to populate the
76086 ** Index.aSample[] arrays.
76088 ** If the sqlite_stat1 table is not present in the database, SQLITE_ERROR
76089 ** is returned. In this case, even if SQLITE_ENABLE_STAT2 was defined
76090 ** during compilation and the sqlite_stat2 table is present, no data is
76091 ** read from it.
76093 ** If SQLITE_ENABLE_STAT2 was defined during compilation and the
76094 ** sqlite_stat2 table is not present in the database, SQLITE_ERROR is
76095 ** returned. However, in this case, data is read from the sqlite_stat1
76096 ** table (if it is present) before returning.
76098 ** If an OOM error occurs, this function always sets db->mallocFailed.
76099 ** This means if the caller does not care about other errors, the return
76100 ** code may be ignored.
76102 SQLITE_PRIVATE int sqlite3AnalysisLoad(sqlite3 *db, int iDb){
76103 analysisInfo sInfo;
76104 HashElem *i;
76105 char *zSql;
76106 int rc;
76108 assert( iDb>=0 && iDb<db->nDb );
76109 assert( db->aDb[iDb].pBt!=0 );
76111 /* Clear any prior statistics */
76112 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
76113 for(i=sqliteHashFirst(&db->aDb[iDb].pSchema->idxHash);i;i=sqliteHashNext(i)){
76114 Index *pIdx = sqliteHashData(i);
76115 sqlite3DefaultRowEst(pIdx);
76116 sqlite3DeleteIndexSamples(db, pIdx);
76117 pIdx->aSample = 0;
76120 /* Check to make sure the sqlite_stat1 table exists */
76121 sInfo.db = db;
76122 sInfo.zDatabase = db->aDb[iDb].zName;
76123 if( sqlite3FindTable(db, "sqlite_stat1", sInfo.zDatabase)==0 ){
76124 return SQLITE_ERROR;
76127 /* Load new statistics out of the sqlite_stat1 table */
76128 zSql = sqlite3MPrintf(db,
76129 "SELECT tbl, idx, stat FROM %Q.sqlite_stat1", sInfo.zDatabase);
76130 if( zSql==0 ){
76131 rc = SQLITE_NOMEM;
76132 }else{
76133 rc = sqlite3_exec(db, zSql, analysisLoader, &sInfo, 0);
76134 sqlite3DbFree(db, zSql);
76138 /* Load the statistics from the sqlite_stat2 table. */
76139 #ifdef SQLITE_ENABLE_STAT2
76140 if( rc==SQLITE_OK && !sqlite3FindTable(db, "sqlite_stat2", sInfo.zDatabase) ){
76141 rc = SQLITE_ERROR;
76143 if( rc==SQLITE_OK ){
76144 sqlite3_stmt *pStmt = 0;
76146 zSql = sqlite3MPrintf(db,
76147 "SELECT idx,sampleno,sample FROM %Q.sqlite_stat2", sInfo.zDatabase);
76148 if( !zSql ){
76149 rc = SQLITE_NOMEM;
76150 }else{
76151 rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
76152 sqlite3DbFree(db, zSql);
76155 if( rc==SQLITE_OK ){
76156 while( sqlite3_step(pStmt)==SQLITE_ROW ){
76157 char *zIndex; /* Index name */
76158 Index *pIdx; /* Pointer to the index object */
76160 zIndex = (char *)sqlite3_column_text(pStmt, 0);
76161 pIdx = zIndex ? sqlite3FindIndex(db, zIndex, sInfo.zDatabase) : 0;
76162 if( pIdx ){
76163 int iSample = sqlite3_column_int(pStmt, 1);
76164 if( iSample<SQLITE_INDEX_SAMPLES && iSample>=0 ){
76165 int eType = sqlite3_column_type(pStmt, 2);
76167 if( pIdx->aSample==0 ){
76168 static const int sz = sizeof(IndexSample)*SQLITE_INDEX_SAMPLES;
76169 pIdx->aSample = (IndexSample *)sqlite3DbMallocRaw(0, sz);
76170 if( pIdx->aSample==0 ){
76171 db->mallocFailed = 1;
76172 break;
76174 memset(pIdx->aSample, 0, sz);
76177 assert( pIdx->aSample );
76179 IndexSample *pSample = &pIdx->aSample[iSample];
76180 pSample->eType = (u8)eType;
76181 if( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT ){
76182 pSample->u.r = sqlite3_column_double(pStmt, 2);
76183 }else if( eType==SQLITE_TEXT || eType==SQLITE_BLOB ){
76184 const char *z = (const char *)(
76185 (eType==SQLITE_BLOB) ?
76186 sqlite3_column_blob(pStmt, 2):
76187 sqlite3_column_text(pStmt, 2)
76189 int n = sqlite3_column_bytes(pStmt, 2);
76190 if( n>24 ){
76191 n = 24;
76193 pSample->nByte = (u8)n;
76194 if( n < 1){
76195 pSample->u.z = 0;
76196 }else{
76197 pSample->u.z = sqlite3DbStrNDup(0, z, n);
76198 if( pSample->u.z==0 ){
76199 db->mallocFailed = 1;
76200 break;
76208 rc = sqlite3_finalize(pStmt);
76211 #endif
76213 if( rc==SQLITE_NOMEM ){
76214 db->mallocFailed = 1;
76216 return rc;
76220 #endif /* SQLITE_OMIT_ANALYZE */
76222 /************** End of analyze.c *********************************************/
76223 /************** Begin file attach.c ******************************************/
76225 ** 2003 April 6
76227 ** The author disclaims copyright to this source code. In place of
76228 ** a legal notice, here is a blessing:
76230 ** May you do good and not evil.
76231 ** May you find forgiveness for yourself and forgive others.
76232 ** May you share freely, never taking more than you give.
76234 *************************************************************************
76235 ** This file contains code used to implement the ATTACH and DETACH commands.
76238 #ifndef SQLITE_OMIT_ATTACH
76240 ** Resolve an expression that was part of an ATTACH or DETACH statement. This
76241 ** is slightly different from resolving a normal SQL expression, because simple
76242 ** identifiers are treated as strings, not possible column names or aliases.
76244 ** i.e. if the parser sees:
76246 ** ATTACH DATABASE abc AS def
76248 ** it treats the two expressions as literal strings 'abc' and 'def' instead of
76249 ** looking for columns of the same name.
76251 ** This only applies to the root node of pExpr, so the statement:
76253 ** ATTACH DATABASE abc||def AS 'db2'
76255 ** will fail because neither abc or def can be resolved.
76257 static int resolveAttachExpr(NameContext *pName, Expr *pExpr)
76259 int rc = SQLITE_OK;
76260 if( pExpr ){
76261 if( pExpr->op!=TK_ID ){
76262 rc = sqlite3ResolveExprNames(pName, pExpr);
76263 if( rc==SQLITE_OK && !sqlite3ExprIsConstant(pExpr) ){
76264 sqlite3ErrorMsg(pName->pParse, "invalid name: \"%s\"", pExpr->u.zToken);
76265 return SQLITE_ERROR;
76267 }else{
76268 pExpr->op = TK_STRING;
76271 return rc;
76275 ** An SQL user-function registered to do the work of an ATTACH statement. The
76276 ** three arguments to the function come directly from an attach statement:
76278 ** ATTACH DATABASE x AS y KEY z
76280 ** SELECT sqlite_attach(x, y, z)
76282 ** If the optional "KEY z" syntax is omitted, an SQL NULL is passed as the
76283 ** third argument.
76285 static void attachFunc(
76286 sqlite3_context *context,
76287 int NotUsed,
76288 sqlite3_value **argv
76290 int i;
76291 int rc = 0;
76292 sqlite3 *db = sqlite3_context_db_handle(context);
76293 const char *zName;
76294 const char *zFile;
76295 Db *aNew;
76296 char *zErrDyn = 0;
76298 UNUSED_PARAMETER(NotUsed);
76300 zFile = (const char *)sqlite3_value_text(argv[0]);
76301 zName = (const char *)sqlite3_value_text(argv[1]);
76302 if( zFile==0 ) zFile = "";
76303 if( zName==0 ) zName = "";
76305 /* Check for the following errors:
76307 ** * Too many attached databases,
76308 ** * Transaction currently open
76309 ** * Specified database name already being used.
76311 if( db->nDb>=db->aLimit[SQLITE_LIMIT_ATTACHED]+2 ){
76312 zErrDyn = sqlite3MPrintf(db, "too many attached databases - max %d",
76313 db->aLimit[SQLITE_LIMIT_ATTACHED]
76315 goto attach_error;
76317 if( !db->autoCommit ){
76318 zErrDyn = sqlite3MPrintf(db, "cannot ATTACH database within transaction");
76319 goto attach_error;
76321 for(i=0; i<db->nDb; i++){
76322 char *z = db->aDb[i].zName;
76323 assert( z && zName );
76324 if( sqlite3StrICmp(z, zName)==0 ){
76325 zErrDyn = sqlite3MPrintf(db, "database %s is already in use", zName);
76326 goto attach_error;
76330 /* Allocate the new entry in the db->aDb[] array and initialise the schema
76331 ** hash tables.
76333 if( db->aDb==db->aDbStatic ){
76334 aNew = sqlite3DbMallocRaw(db, sizeof(db->aDb[0])*3 );
76335 if( aNew==0 ) return;
76336 memcpy(aNew, db->aDb, sizeof(db->aDb[0])*2);
76337 }else{
76338 aNew = sqlite3DbRealloc(db, db->aDb, sizeof(db->aDb[0])*(db->nDb+1) );
76339 if( aNew==0 ) return;
76341 db->aDb = aNew;
76342 aNew = &db->aDb[db->nDb];
76343 memset(aNew, 0, sizeof(*aNew));
76345 /* Open the database file. If the btree is successfully opened, use
76346 ** it to obtain the database schema. At this point the schema may
76347 ** or may not be initialised.
76349 rc = sqlite3BtreeOpen(zFile, db, &aNew->pBt, 0,
76350 db->openFlags | SQLITE_OPEN_MAIN_DB);
76351 db->nDb++;
76352 if( rc==SQLITE_CONSTRAINT ){
76353 rc = SQLITE_ERROR;
76354 zErrDyn = sqlite3MPrintf(db, "database is already attached");
76355 }else if( rc==SQLITE_OK ){
76356 Pager *pPager;
76357 aNew->pSchema = sqlite3SchemaGet(db, aNew->pBt);
76358 if( !aNew->pSchema ){
76359 rc = SQLITE_NOMEM;
76360 }else if( aNew->pSchema->file_format && aNew->pSchema->enc!=ENC(db) ){
76361 zErrDyn = sqlite3MPrintf(db,
76362 "attached databases must use the same text encoding as main database");
76363 rc = SQLITE_ERROR;
76365 pPager = sqlite3BtreePager(aNew->pBt);
76366 sqlite3PagerLockingMode(pPager, db->dfltLockMode);
76367 sqlite3BtreeSecureDelete(aNew->pBt,
76368 sqlite3BtreeSecureDelete(db->aDb[0].pBt,-1) );
76370 aNew->safety_level = 3;
76371 aNew->zName = sqlite3DbStrDup(db, zName);
76372 if( rc==SQLITE_OK && aNew->zName==0 ){
76373 rc = SQLITE_NOMEM;
76377 #ifdef SQLITE_HAS_CODEC
76378 if( rc==SQLITE_OK ){
76379 extern int sqlite3CodecAttach(sqlite3*, int, const void*, int);
76380 extern void sqlite3CodecGetKey(sqlite3*, int, void**, int*);
76381 int nKey;
76382 char *zKey;
76383 int t = sqlite3_value_type(argv[2]);
76384 switch( t ){
76385 case SQLITE_INTEGER:
76386 case SQLITE_FLOAT:
76387 zErrDyn = sqlite3DbStrDup(db, "Invalid key value");
76388 rc = SQLITE_ERROR;
76389 break;
76391 case SQLITE_TEXT:
76392 case SQLITE_BLOB:
76393 nKey = sqlite3_value_bytes(argv[2]);
76394 zKey = (char *)sqlite3_value_blob(argv[2]);
76395 rc = sqlite3CodecAttach(db, db->nDb-1, zKey, nKey);
76396 break;
76398 case SQLITE_NULL:
76399 /* No key specified. Use the key from the main database */
76400 sqlite3CodecGetKey(db, 0, (void**)&zKey, &nKey);
76401 if( nKey>0 || sqlite3BtreeGetReserve(db->aDb[0].pBt)>0 ){
76402 rc = sqlite3CodecAttach(db, db->nDb-1, zKey, nKey);
76404 break;
76407 #endif
76409 /* If the file was opened successfully, read the schema for the new database.
76410 ** If this fails, or if opening the file failed, then close the file and
76411 ** remove the entry from the db->aDb[] array. i.e. put everything back the way
76412 ** we found it.
76414 if( rc==SQLITE_OK ){
76415 sqlite3BtreeEnterAll(db);
76416 rc = sqlite3Init(db, &zErrDyn);
76417 sqlite3BtreeLeaveAll(db);
76419 if( rc ){
76420 int iDb = db->nDb - 1;
76421 assert( iDb>=2 );
76422 if( db->aDb[iDb].pBt ){
76423 sqlite3BtreeClose(db->aDb[iDb].pBt);
76424 db->aDb[iDb].pBt = 0;
76425 db->aDb[iDb].pSchema = 0;
76427 sqlite3ResetInternalSchema(db, -1);
76428 db->nDb = iDb;
76429 if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){
76430 db->mallocFailed = 1;
76431 sqlite3DbFree(db, zErrDyn);
76432 zErrDyn = sqlite3MPrintf(db, "out of memory");
76433 }else if( zErrDyn==0 ){
76434 zErrDyn = sqlite3MPrintf(db, "unable to open database: %s", zFile);
76436 goto attach_error;
76439 return;
76441 attach_error:
76442 /* Return an error if we get here */
76443 if( zErrDyn ){
76444 sqlite3_result_error(context, zErrDyn, -1);
76445 sqlite3DbFree(db, zErrDyn);
76447 if( rc ) sqlite3_result_error_code(context, rc);
76451 ** An SQL user-function registered to do the work of an DETACH statement. The
76452 ** three arguments to the function come directly from a detach statement:
76454 ** DETACH DATABASE x
76456 ** SELECT sqlite_detach(x)
76458 static void detachFunc(
76459 sqlite3_context *context,
76460 int NotUsed,
76461 sqlite3_value **argv
76463 const char *zName = (const char *)sqlite3_value_text(argv[0]);
76464 sqlite3 *db = sqlite3_context_db_handle(context);
76465 int i;
76466 Db *pDb = 0;
76467 char zErr[128];
76469 UNUSED_PARAMETER(NotUsed);
76471 if( zName==0 ) zName = "";
76472 for(i=0; i<db->nDb; i++){
76473 pDb = &db->aDb[i];
76474 if( pDb->pBt==0 ) continue;
76475 if( sqlite3StrICmp(pDb->zName, zName)==0 ) break;
76478 if( i>=db->nDb ){
76479 sqlite3_snprintf(sizeof(zErr),zErr, "no such database: %s", zName);
76480 goto detach_error;
76482 if( i<2 ){
76483 sqlite3_snprintf(sizeof(zErr),zErr, "cannot detach database %s", zName);
76484 goto detach_error;
76486 if( !db->autoCommit ){
76487 sqlite3_snprintf(sizeof(zErr), zErr,
76488 "cannot DETACH database within transaction");
76489 goto detach_error;
76491 if( sqlite3BtreeIsInReadTrans(pDb->pBt) || sqlite3BtreeIsInBackup(pDb->pBt) ){
76492 sqlite3_snprintf(sizeof(zErr),zErr, "database %s is locked", zName);
76493 goto detach_error;
76496 sqlite3BtreeClose(pDb->pBt);
76497 pDb->pBt = 0;
76498 pDb->pSchema = 0;
76499 sqlite3ResetInternalSchema(db, -1);
76500 return;
76502 detach_error:
76503 sqlite3_result_error(context, zErr, -1);
76507 ** This procedure generates VDBE code for a single invocation of either the
76508 ** sqlite_detach() or sqlite_attach() SQL user functions.
76510 static void codeAttach(
76511 Parse *pParse, /* The parser context */
76512 int type, /* Either SQLITE_ATTACH or SQLITE_DETACH */
76513 FuncDef const *pFunc,/* FuncDef wrapper for detachFunc() or attachFunc() */
76514 Expr *pAuthArg, /* Expression to pass to authorization callback */
76515 Expr *pFilename, /* Name of database file */
76516 Expr *pDbname, /* Name of the database to use internally */
76517 Expr *pKey /* Database key for encryption extension */
76519 int rc;
76520 NameContext sName;
76521 Vdbe *v;
76522 sqlite3* db = pParse->db;
76523 int regArgs;
76525 memset(&sName, 0, sizeof(NameContext));
76526 sName.pParse = pParse;
76528 if(
76529 SQLITE_OK!=(rc = resolveAttachExpr(&sName, pFilename)) ||
76530 SQLITE_OK!=(rc = resolveAttachExpr(&sName, pDbname)) ||
76531 SQLITE_OK!=(rc = resolveAttachExpr(&sName, pKey))
76533 pParse->nErr++;
76534 goto attach_end;
76537 #ifndef SQLITE_OMIT_AUTHORIZATION
76538 if( pAuthArg ){
76539 char *zAuthArg;
76540 if( pAuthArg->op==TK_STRING ){
76541 zAuthArg = pAuthArg->u.zToken;
76542 }else{
76543 zAuthArg = 0;
76545 rc = sqlite3AuthCheck(pParse, type, zAuthArg, 0, 0);
76546 if(rc!=SQLITE_OK ){
76547 goto attach_end;
76550 #endif /* SQLITE_OMIT_AUTHORIZATION */
76553 v = sqlite3GetVdbe(pParse);
76554 regArgs = sqlite3GetTempRange(pParse, 4);
76555 sqlite3ExprCode(pParse, pFilename, regArgs);
76556 sqlite3ExprCode(pParse, pDbname, regArgs+1);
76557 sqlite3ExprCode(pParse, pKey, regArgs+2);
76559 assert( v || db->mallocFailed );
76560 if( v ){
76561 sqlite3VdbeAddOp3(v, OP_Function, 0, regArgs+3-pFunc->nArg, regArgs+3);
76562 assert( pFunc->nArg==-1 || (pFunc->nArg&0xff)==pFunc->nArg );
76563 sqlite3VdbeChangeP5(v, (u8)(pFunc->nArg));
76564 sqlite3VdbeChangeP4(v, -1, (char *)pFunc, P4_FUNCDEF);
76566 /* Code an OP_Expire. For an ATTACH statement, set P1 to true (expire this
76567 ** statement only). For DETACH, set it to false (expire all existing
76568 ** statements).
76570 sqlite3VdbeAddOp1(v, OP_Expire, (type==SQLITE_ATTACH));
76573 attach_end:
76574 sqlite3ExprDelete(db, pFilename);
76575 sqlite3ExprDelete(db, pDbname);
76576 sqlite3ExprDelete(db, pKey);
76580 ** Called by the parser to compile a DETACH statement.
76582 ** DETACH pDbname
76584 SQLITE_PRIVATE void sqlite3Detach(Parse *pParse, Expr *pDbname){
76585 static const FuncDef detach_func = {
76586 1, /* nArg */
76587 SQLITE_UTF8, /* iPrefEnc */
76588 0, /* flags */
76589 0, /* pUserData */
76590 0, /* pNext */
76591 detachFunc, /* xFunc */
76592 0, /* xStep */
76593 0, /* xFinalize */
76594 "sqlite_detach", /* zName */
76595 0, /* pHash */
76596 0 /* pDestructor */
76598 codeAttach(pParse, SQLITE_DETACH, &detach_func, pDbname, 0, 0, pDbname);
76602 ** Called by the parser to compile an ATTACH statement.
76604 ** ATTACH p AS pDbname KEY pKey
76606 SQLITE_PRIVATE void sqlite3Attach(Parse *pParse, Expr *p, Expr *pDbname, Expr *pKey){
76607 static const FuncDef attach_func = {
76608 3, /* nArg */
76609 SQLITE_UTF8, /* iPrefEnc */
76610 0, /* flags */
76611 0, /* pUserData */
76612 0, /* pNext */
76613 attachFunc, /* xFunc */
76614 0, /* xStep */
76615 0, /* xFinalize */
76616 "sqlite_attach", /* zName */
76617 0, /* pHash */
76618 0 /* pDestructor */
76620 codeAttach(pParse, SQLITE_ATTACH, &attach_func, p, p, pDbname, pKey);
76622 #endif /* SQLITE_OMIT_ATTACH */
76625 ** Initialize a DbFixer structure. This routine must be called prior
76626 ** to passing the structure to one of the sqliteFixAAAA() routines below.
76628 ** The return value indicates whether or not fixation is required. TRUE
76629 ** means we do need to fix the database references, FALSE means we do not.
76631 SQLITE_PRIVATE int sqlite3FixInit(
76632 DbFixer *pFix, /* The fixer to be initialized */
76633 Parse *pParse, /* Error messages will be written here */
76634 int iDb, /* This is the database that must be used */
76635 const char *zType, /* "view", "trigger", or "index" */
76636 const Token *pName /* Name of the view, trigger, or index */
76638 sqlite3 *db;
76640 if( NEVER(iDb<0) || iDb==1 ) return 0;
76641 db = pParse->db;
76642 assert( db->nDb>iDb );
76643 pFix->pParse = pParse;
76644 pFix->zDb = db->aDb[iDb].zName;
76645 pFix->zType = zType;
76646 pFix->pName = pName;
76647 return 1;
76651 ** The following set of routines walk through the parse tree and assign
76652 ** a specific database to all table references where the database name
76653 ** was left unspecified in the original SQL statement. The pFix structure
76654 ** must have been initialized by a prior call to sqlite3FixInit().
76656 ** These routines are used to make sure that an index, trigger, or
76657 ** view in one database does not refer to objects in a different database.
76658 ** (Exception: indices, triggers, and views in the TEMP database are
76659 ** allowed to refer to anything.) If a reference is explicitly made
76660 ** to an object in a different database, an error message is added to
76661 ** pParse->zErrMsg and these routines return non-zero. If everything
76662 ** checks out, these routines return 0.
76664 SQLITE_PRIVATE int sqlite3FixSrcList(
76665 DbFixer *pFix, /* Context of the fixation */
76666 SrcList *pList /* The Source list to check and modify */
76668 int i;
76669 const char *zDb;
76670 struct SrcList_item *pItem;
76672 if( NEVER(pList==0) ) return 0;
76673 zDb = pFix->zDb;
76674 for(i=0, pItem=pList->a; i<pList->nSrc; i++, pItem++){
76675 if( pItem->zDatabase==0 ){
76676 pItem->zDatabase = sqlite3DbStrDup(pFix->pParse->db, zDb);
76677 }else if( sqlite3StrICmp(pItem->zDatabase,zDb)!=0 ){
76678 sqlite3ErrorMsg(pFix->pParse,
76679 "%s %T cannot reference objects in database %s",
76680 pFix->zType, pFix->pName, pItem->zDatabase);
76681 return 1;
76683 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER)
76684 if( sqlite3FixSelect(pFix, pItem->pSelect) ) return 1;
76685 if( sqlite3FixExpr(pFix, pItem->pOn) ) return 1;
76686 #endif
76688 return 0;
76690 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER)
76691 SQLITE_PRIVATE int sqlite3FixSelect(
76692 DbFixer *pFix, /* Context of the fixation */
76693 Select *pSelect /* The SELECT statement to be fixed to one database */
76695 while( pSelect ){
76696 if( sqlite3FixExprList(pFix, pSelect->pEList) ){
76697 return 1;
76699 if( sqlite3FixSrcList(pFix, pSelect->pSrc) ){
76700 return 1;
76702 if( sqlite3FixExpr(pFix, pSelect->pWhere) ){
76703 return 1;
76705 if( sqlite3FixExpr(pFix, pSelect->pHaving) ){
76706 return 1;
76708 pSelect = pSelect->pPrior;
76710 return 0;
76712 SQLITE_PRIVATE int sqlite3FixExpr(
76713 DbFixer *pFix, /* Context of the fixation */
76714 Expr *pExpr /* The expression to be fixed to one database */
76716 while( pExpr ){
76717 if( ExprHasAnyProperty(pExpr, EP_TokenOnly) ) break;
76718 if( ExprHasProperty(pExpr, EP_xIsSelect) ){
76719 if( sqlite3FixSelect(pFix, pExpr->x.pSelect) ) return 1;
76720 }else{
76721 if( sqlite3FixExprList(pFix, pExpr->x.pList) ) return 1;
76723 if( sqlite3FixExpr(pFix, pExpr->pRight) ){
76724 return 1;
76726 pExpr = pExpr->pLeft;
76728 return 0;
76730 SQLITE_PRIVATE int sqlite3FixExprList(
76731 DbFixer *pFix, /* Context of the fixation */
76732 ExprList *pList /* The expression to be fixed to one database */
76734 int i;
76735 struct ExprList_item *pItem;
76736 if( pList==0 ) return 0;
76737 for(i=0, pItem=pList->a; i<pList->nExpr; i++, pItem++){
76738 if( sqlite3FixExpr(pFix, pItem->pExpr) ){
76739 return 1;
76742 return 0;
76744 #endif
76746 #ifndef SQLITE_OMIT_TRIGGER
76747 SQLITE_PRIVATE int sqlite3FixTriggerStep(
76748 DbFixer *pFix, /* Context of the fixation */
76749 TriggerStep *pStep /* The trigger step be fixed to one database */
76751 while( pStep ){
76752 if( sqlite3FixSelect(pFix, pStep->pSelect) ){
76753 return 1;
76755 if( sqlite3FixExpr(pFix, pStep->pWhere) ){
76756 return 1;
76758 if( sqlite3FixExprList(pFix, pStep->pExprList) ){
76759 return 1;
76761 pStep = pStep->pNext;
76763 return 0;
76765 #endif
76767 /************** End of attach.c **********************************************/
76768 /************** Begin file auth.c ********************************************/
76770 ** 2003 January 11
76772 ** The author disclaims copyright to this source code. In place of
76773 ** a legal notice, here is a blessing:
76775 ** May you do good and not evil.
76776 ** May you find forgiveness for yourself and forgive others.
76777 ** May you share freely, never taking more than you give.
76779 *************************************************************************
76780 ** This file contains code used to implement the sqlite3_set_authorizer()
76781 ** API. This facility is an optional feature of the library. Embedded
76782 ** systems that do not need this facility may omit it by recompiling
76783 ** the library with -DSQLITE_OMIT_AUTHORIZATION=1
76787 ** All of the code in this file may be omitted by defining a single
76788 ** macro.
76790 #ifndef SQLITE_OMIT_AUTHORIZATION
76793 ** Set or clear the access authorization function.
76795 ** The access authorization function is be called during the compilation
76796 ** phase to verify that the user has read and/or write access permission on
76797 ** various fields of the database. The first argument to the auth function
76798 ** is a copy of the 3rd argument to this routine. The second argument
76799 ** to the auth function is one of these constants:
76801 ** SQLITE_CREATE_INDEX
76802 ** SQLITE_CREATE_TABLE
76803 ** SQLITE_CREATE_TEMP_INDEX
76804 ** SQLITE_CREATE_TEMP_TABLE
76805 ** SQLITE_CREATE_TEMP_TRIGGER
76806 ** SQLITE_CREATE_TEMP_VIEW
76807 ** SQLITE_CREATE_TRIGGER
76808 ** SQLITE_CREATE_VIEW
76809 ** SQLITE_DELETE
76810 ** SQLITE_DROP_INDEX
76811 ** SQLITE_DROP_TABLE
76812 ** SQLITE_DROP_TEMP_INDEX
76813 ** SQLITE_DROP_TEMP_TABLE
76814 ** SQLITE_DROP_TEMP_TRIGGER
76815 ** SQLITE_DROP_TEMP_VIEW
76816 ** SQLITE_DROP_TRIGGER
76817 ** SQLITE_DROP_VIEW
76818 ** SQLITE_INSERT
76819 ** SQLITE_PRAGMA
76820 ** SQLITE_READ
76821 ** SQLITE_SELECT
76822 ** SQLITE_TRANSACTION
76823 ** SQLITE_UPDATE
76825 ** The third and fourth arguments to the auth function are the name of
76826 ** the table and the column that are being accessed. The auth function
76827 ** should return either SQLITE_OK, SQLITE_DENY, or SQLITE_IGNORE. If
76828 ** SQLITE_OK is returned, it means that access is allowed. SQLITE_DENY
76829 ** means that the SQL statement will never-run - the sqlite3_exec() call
76830 ** will return with an error. SQLITE_IGNORE means that the SQL statement
76831 ** should run but attempts to read the specified column will return NULL
76832 ** and attempts to write the column will be ignored.
76834 ** Setting the auth function to NULL disables this hook. The default
76835 ** setting of the auth function is NULL.
76837 SQLITE_API int sqlite3_set_authorizer(
76838 sqlite3 *db,
76839 int (*xAuth)(void*,int,const char*,const char*,const char*,const char*),
76840 void *pArg
76842 sqlite3_mutex_enter(db->mutex);
76843 db->xAuth = xAuth;
76844 db->pAuthArg = pArg;
76845 sqlite3ExpirePreparedStatements(db);
76846 sqlite3_mutex_leave(db->mutex);
76847 return SQLITE_OK;
76851 ** Write an error message into pParse->zErrMsg that explains that the
76852 ** user-supplied authorization function returned an illegal value.
76854 static void sqliteAuthBadReturnCode(Parse *pParse){
76855 sqlite3ErrorMsg(pParse, "authorizer malfunction");
76856 pParse->rc = SQLITE_ERROR;
76860 ** Invoke the authorization callback for permission to read column zCol from
76861 ** table zTab in database zDb. This function assumes that an authorization
76862 ** callback has been registered (i.e. that sqlite3.xAuth is not NULL).
76864 ** If SQLITE_IGNORE is returned and pExpr is not NULL, then pExpr is changed
76865 ** to an SQL NULL expression. Otherwise, if pExpr is NULL, then SQLITE_IGNORE
76866 ** is treated as SQLITE_DENY. In this case an error is left in pParse.
76868 SQLITE_PRIVATE int sqlite3AuthReadCol(
76869 Parse *pParse, /* The parser context */
76870 const char *zTab, /* Table name */
76871 const char *zCol, /* Column name */
76872 int iDb /* Index of containing database. */
76874 sqlite3 *db = pParse->db; /* Database handle */
76875 char *zDb = db->aDb[iDb].zName; /* Name of attached database */
76876 int rc; /* Auth callback return code */
76878 rc = db->xAuth(db->pAuthArg, SQLITE_READ, zTab,zCol,zDb,pParse->zAuthContext);
76879 if( rc==SQLITE_DENY ){
76880 if( db->nDb>2 || iDb!=0 ){
76881 sqlite3ErrorMsg(pParse, "access to %s.%s.%s is prohibited",zDb,zTab,zCol);
76882 }else{
76883 sqlite3ErrorMsg(pParse, "access to %s.%s is prohibited", zTab, zCol);
76885 pParse->rc = SQLITE_AUTH;
76886 }else if( rc!=SQLITE_IGNORE && rc!=SQLITE_OK ){
76887 sqliteAuthBadReturnCode(pParse);
76889 return rc;
76893 ** The pExpr should be a TK_COLUMN expression. The table referred to
76894 ** is in pTabList or else it is the NEW or OLD table of a trigger.
76895 ** Check to see if it is OK to read this particular column.
76897 ** If the auth function returns SQLITE_IGNORE, change the TK_COLUMN
76898 ** instruction into a TK_NULL. If the auth function returns SQLITE_DENY,
76899 ** then generate an error.
76901 SQLITE_PRIVATE void sqlite3AuthRead(
76902 Parse *pParse, /* The parser context */
76903 Expr *pExpr, /* The expression to check authorization on */
76904 Schema *pSchema, /* The schema of the expression */
76905 SrcList *pTabList /* All table that pExpr might refer to */
76907 sqlite3 *db = pParse->db;
76908 Table *pTab = 0; /* The table being read */
76909 const char *zCol; /* Name of the column of the table */
76910 int iSrc; /* Index in pTabList->a[] of table being read */
76911 int iDb; /* The index of the database the expression refers to */
76912 int iCol; /* Index of column in table */
76914 if( db->xAuth==0 ) return;
76915 iDb = sqlite3SchemaToIndex(pParse->db, pSchema);
76916 if( iDb<0 ){
76917 /* An attempt to read a column out of a subquery or other
76918 ** temporary table. */
76919 return;
76922 assert( pExpr->op==TK_COLUMN || pExpr->op==TK_TRIGGER );
76923 if( pExpr->op==TK_TRIGGER ){
76924 pTab = pParse->pTriggerTab;
76925 }else{
76926 assert( pTabList );
76927 for(iSrc=0; ALWAYS(iSrc<pTabList->nSrc); iSrc++){
76928 if( pExpr->iTable==pTabList->a[iSrc].iCursor ){
76929 pTab = pTabList->a[iSrc].pTab;
76930 break;
76934 iCol = pExpr->iColumn;
76935 if( NEVER(pTab==0) ) return;
76937 if( iCol>=0 ){
76938 assert( iCol<pTab->nCol );
76939 zCol = pTab->aCol[iCol].zName;
76940 }else if( pTab->iPKey>=0 ){
76941 assert( pTab->iPKey<pTab->nCol );
76942 zCol = pTab->aCol[pTab->iPKey].zName;
76943 }else{
76944 zCol = "ROWID";
76946 assert( iDb>=0 && iDb<db->nDb );
76947 if( SQLITE_IGNORE==sqlite3AuthReadCol(pParse, pTab->zName, zCol, iDb) ){
76948 pExpr->op = TK_NULL;
76953 ** Do an authorization check using the code and arguments given. Return
76954 ** either SQLITE_OK (zero) or SQLITE_IGNORE or SQLITE_DENY. If SQLITE_DENY
76955 ** is returned, then the error count and error message in pParse are
76956 ** modified appropriately.
76958 SQLITE_PRIVATE int sqlite3AuthCheck(
76959 Parse *pParse,
76960 int code,
76961 const char *zArg1,
76962 const char *zArg2,
76963 const char *zArg3
76965 sqlite3 *db = pParse->db;
76966 int rc;
76968 /* Don't do any authorization checks if the database is initialising
76969 ** or if the parser is being invoked from within sqlite3_declare_vtab.
76971 if( db->init.busy || IN_DECLARE_VTAB ){
76972 return SQLITE_OK;
76975 if( db->xAuth==0 ){
76976 return SQLITE_OK;
76978 rc = db->xAuth(db->pAuthArg, code, zArg1, zArg2, zArg3, pParse->zAuthContext);
76979 if( rc==SQLITE_DENY ){
76980 sqlite3ErrorMsg(pParse, "not authorized");
76981 pParse->rc = SQLITE_AUTH;
76982 }else if( rc!=SQLITE_OK && rc!=SQLITE_IGNORE ){
76983 rc = SQLITE_DENY;
76984 sqliteAuthBadReturnCode(pParse);
76986 return rc;
76990 ** Push an authorization context. After this routine is called, the
76991 ** zArg3 argument to authorization callbacks will be zContext until
76992 ** popped. Or if pParse==0, this routine is a no-op.
76994 SQLITE_PRIVATE void sqlite3AuthContextPush(
76995 Parse *pParse,
76996 AuthContext *pContext,
76997 const char *zContext
76999 assert( pParse );
77000 pContext->pParse = pParse;
77001 pContext->zAuthContext = pParse->zAuthContext;
77002 pParse->zAuthContext = zContext;
77006 ** Pop an authorization context that was previously pushed
77007 ** by sqlite3AuthContextPush
77009 SQLITE_PRIVATE void sqlite3AuthContextPop(AuthContext *pContext){
77010 if( pContext->pParse ){
77011 pContext->pParse->zAuthContext = pContext->zAuthContext;
77012 pContext->pParse = 0;
77016 #endif /* SQLITE_OMIT_AUTHORIZATION */
77018 /************** End of auth.c ************************************************/
77019 /************** Begin file build.c *******************************************/
77021 ** 2001 September 15
77023 ** The author disclaims copyright to this source code. In place of
77024 ** a legal notice, here is a blessing:
77026 ** May you do good and not evil.
77027 ** May you find forgiveness for yourself and forgive others.
77028 ** May you share freely, never taking more than you give.
77030 *************************************************************************
77031 ** This file contains C code routines that are called by the SQLite parser
77032 ** when syntax rules are reduced. The routines in this file handle the
77033 ** following kinds of SQL syntax:
77035 ** CREATE TABLE
77036 ** DROP TABLE
77037 ** CREATE INDEX
77038 ** DROP INDEX
77039 ** creating ID lists
77040 ** BEGIN TRANSACTION
77041 ** COMMIT
77042 ** ROLLBACK
77047 ** This routine is called when a new SQL statement is beginning to
77048 ** be parsed. Initialize the pParse structure as needed.
77050 SQLITE_PRIVATE void sqlite3BeginParse(Parse *pParse, int explainFlag){
77051 pParse->explain = (u8)explainFlag;
77052 pParse->nVar = 0;
77055 #ifndef SQLITE_OMIT_SHARED_CACHE
77057 ** The TableLock structure is only used by the sqlite3TableLock() and
77058 ** codeTableLocks() functions.
77060 struct TableLock {
77061 int iDb; /* The database containing the table to be locked */
77062 int iTab; /* The root page of the table to be locked */
77063 u8 isWriteLock; /* True for write lock. False for a read lock */
77064 const char *zName; /* Name of the table */
77068 ** Record the fact that we want to lock a table at run-time.
77070 ** The table to be locked has root page iTab and is found in database iDb.
77071 ** A read or a write lock can be taken depending on isWritelock.
77073 ** This routine just records the fact that the lock is desired. The
77074 ** code to make the lock occur is generated by a later call to
77075 ** codeTableLocks() which occurs during sqlite3FinishCoding().
77077 SQLITE_PRIVATE void sqlite3TableLock(
77078 Parse *pParse, /* Parsing context */
77079 int iDb, /* Index of the database containing the table to lock */
77080 int iTab, /* Root page number of the table to be locked */
77081 u8 isWriteLock, /* True for a write lock */
77082 const char *zName /* Name of the table to be locked */
77084 Parse *pToplevel = sqlite3ParseToplevel(pParse);
77085 int i;
77086 int nBytes;
77087 TableLock *p;
77088 assert( iDb>=0 );
77090 for(i=0; i<pToplevel->nTableLock; i++){
77091 p = &pToplevel->aTableLock[i];
77092 if( p->iDb==iDb && p->iTab==iTab ){
77093 p->isWriteLock = (p->isWriteLock || isWriteLock);
77094 return;
77098 nBytes = sizeof(TableLock) * (pToplevel->nTableLock+1);
77099 pToplevel->aTableLock =
77100 sqlite3DbReallocOrFree(pToplevel->db, pToplevel->aTableLock, nBytes);
77101 if( pToplevel->aTableLock ){
77102 p = &pToplevel->aTableLock[pToplevel->nTableLock++];
77103 p->iDb = iDb;
77104 p->iTab = iTab;
77105 p->isWriteLock = isWriteLock;
77106 p->zName = zName;
77107 }else{
77108 pToplevel->nTableLock = 0;
77109 pToplevel->db->mallocFailed = 1;
77114 ** Code an OP_TableLock instruction for each table locked by the
77115 ** statement (configured by calls to sqlite3TableLock()).
77117 static void codeTableLocks(Parse *pParse){
77118 int i;
77119 Vdbe *pVdbe;
77121 pVdbe = sqlite3GetVdbe(pParse);
77122 assert( pVdbe!=0 ); /* sqlite3GetVdbe cannot fail: VDBE already allocated */
77124 for(i=0; i<pParse->nTableLock; i++){
77125 TableLock *p = &pParse->aTableLock[i];
77126 int p1 = p->iDb;
77127 sqlite3VdbeAddOp4(pVdbe, OP_TableLock, p1, p->iTab, p->isWriteLock,
77128 p->zName, P4_STATIC);
77131 #else
77132 #define codeTableLocks(x)
77133 #endif
77136 ** This routine is called after a single SQL statement has been
77137 ** parsed and a VDBE program to execute that statement has been
77138 ** prepared. This routine puts the finishing touches on the
77139 ** VDBE program and resets the pParse structure for the next
77140 ** parse.
77142 ** Note that if an error occurred, it might be the case that
77143 ** no VDBE code was generated.
77145 SQLITE_PRIVATE void sqlite3FinishCoding(Parse *pParse){
77146 sqlite3 *db;
77147 Vdbe *v;
77149 db = pParse->db;
77150 if( db->mallocFailed ) return;
77151 if( pParse->nested ) return;
77152 if( pParse->nErr ) return;
77154 /* Begin by generating some termination code at the end of the
77155 ** vdbe program
77157 v = sqlite3GetVdbe(pParse);
77158 assert( !pParse->isMultiWrite
77159 || sqlite3VdbeAssertMayAbort(v, pParse->mayAbort));
77160 if( v ){
77161 sqlite3VdbeAddOp0(v, OP_Halt);
77163 /* The cookie mask contains one bit for each database file open.
77164 ** (Bit 0 is for main, bit 1 is for temp, and so forth.) Bits are
77165 ** set for each database that is used. Generate code to start a
77166 ** transaction on each used database and to verify the schema cookie
77167 ** on each used database.
77169 if( pParse->cookieGoto>0 ){
77170 yDbMask mask;
77171 int iDb;
77172 sqlite3VdbeJumpHere(v, pParse->cookieGoto-1);
77173 for(iDb=0, mask=1; iDb<db->nDb; mask<<=1, iDb++){
77174 if( (mask & pParse->cookieMask)==0 ) continue;
77175 sqlite3VdbeUsesBtree(v, iDb);
77176 sqlite3VdbeAddOp2(v,OP_Transaction, iDb, (mask & pParse->writeMask)!=0);
77177 if( db->init.busy==0 ){
77178 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
77179 sqlite3VdbeAddOp3(v, OP_VerifyCookie,
77180 iDb, pParse->cookieValue[iDb],
77181 db->aDb[iDb].pSchema->iGeneration);
77184 #ifndef SQLITE_OMIT_VIRTUALTABLE
77186 int i;
77187 for(i=0; i<pParse->nVtabLock; i++){
77188 char *vtab = (char *)sqlite3GetVTable(db, pParse->apVtabLock[i]);
77189 sqlite3VdbeAddOp4(v, OP_VBegin, 0, 0, 0, vtab, P4_VTAB);
77191 pParse->nVtabLock = 0;
77193 #endif
77195 /* Once all the cookies have been verified and transactions opened,
77196 ** obtain the required table-locks. This is a no-op unless the
77197 ** shared-cache feature is enabled.
77199 codeTableLocks(pParse);
77201 /* Initialize any AUTOINCREMENT data structures required.
77203 sqlite3AutoincrementBegin(pParse);
77205 /* Finally, jump back to the beginning of the executable code. */
77206 sqlite3VdbeAddOp2(v, OP_Goto, 0, pParse->cookieGoto);
77211 /* Get the VDBE program ready for execution
77213 if( v && ALWAYS(pParse->nErr==0) && !db->mallocFailed ){
77214 #ifdef SQLITE_DEBUG
77215 FILE *trace = (db->flags & SQLITE_VdbeTrace)!=0 ? stdout : 0;
77216 sqlite3VdbeTrace(v, trace);
77217 #endif
77218 assert( pParse->iCacheLevel==0 ); /* Disables and re-enables match */
77219 /* A minimum of one cursor is required if autoincrement is used
77220 * See ticket [a696379c1f08866] */
77221 if( pParse->pAinc!=0 && pParse->nTab==0 ) pParse->nTab = 1;
77222 sqlite3VdbeMakeReady(v, pParse->nVar, pParse->nMem,
77223 pParse->nTab, pParse->nMaxArg, pParse->explain,
77224 pParse->isMultiWrite && pParse->mayAbort);
77225 pParse->rc = SQLITE_DONE;
77226 pParse->colNamesSet = 0;
77227 }else{
77228 pParse->rc = SQLITE_ERROR;
77230 pParse->nTab = 0;
77231 pParse->nMem = 0;
77232 pParse->nSet = 0;
77233 pParse->nVar = 0;
77234 pParse->cookieMask = 0;
77235 pParse->cookieGoto = 0;
77239 ** Run the parser and code generator recursively in order to generate
77240 ** code for the SQL statement given onto the end of the pParse context
77241 ** currently under construction. When the parser is run recursively
77242 ** this way, the final OP_Halt is not appended and other initialization
77243 ** and finalization steps are omitted because those are handling by the
77244 ** outermost parser.
77246 ** Not everything is nestable. This facility is designed to permit
77247 ** INSERT, UPDATE, and DELETE operations against SQLITE_MASTER. Use
77248 ** care if you decide to try to use this routine for some other purposes.
77250 SQLITE_PRIVATE void sqlite3NestedParse(Parse *pParse, const char *zFormat, ...){
77251 va_list ap;
77252 char *zSql;
77253 char *zErrMsg = 0;
77254 sqlite3 *db = pParse->db;
77255 # define SAVE_SZ (sizeof(Parse) - offsetof(Parse,nVar))
77256 char saveBuf[SAVE_SZ];
77258 if( pParse->nErr ) return;
77259 assert( pParse->nested<10 ); /* Nesting should only be of limited depth */
77260 va_start(ap, zFormat);
77261 zSql = sqlite3VMPrintf(db, zFormat, ap);
77262 va_end(ap);
77263 if( zSql==0 ){
77264 return; /* A malloc must have failed */
77266 pParse->nested++;
77267 memcpy(saveBuf, &pParse->nVar, SAVE_SZ);
77268 memset(&pParse->nVar, 0, SAVE_SZ);
77269 sqlite3RunParser(pParse, zSql, &zErrMsg);
77270 sqlite3DbFree(db, zErrMsg);
77271 sqlite3DbFree(db, zSql);
77272 memcpy(&pParse->nVar, saveBuf, SAVE_SZ);
77273 pParse->nested--;
77277 ** Locate the in-memory structure that describes a particular database
77278 ** table given the name of that table and (optionally) the name of the
77279 ** database containing the table. Return NULL if not found.
77281 ** If zDatabase is 0, all databases are searched for the table and the
77282 ** first matching table is returned. (No checking for duplicate table
77283 ** names is done.) The search order is TEMP first, then MAIN, then any
77284 ** auxiliary databases added using the ATTACH command.
77286 ** See also sqlite3LocateTable().
77288 SQLITE_PRIVATE Table *sqlite3FindTable(sqlite3 *db, const char *zName, const char *zDatabase){
77289 Table *p = 0;
77290 int i;
77291 int nName;
77292 assert( zName!=0 );
77293 nName = sqlite3Strlen30(zName);
77294 /* All mutexes are required for schema access. Make sure we hold them. */
77295 assert( zDatabase!=0 || sqlite3BtreeHoldsAllMutexes(db) );
77296 for(i=OMIT_TEMPDB; i<db->nDb; i++){
77297 int j = (i<2) ? i^1 : i; /* Search TEMP before MAIN */
77298 if( zDatabase!=0 && sqlite3StrICmp(zDatabase, db->aDb[j].zName) ) continue;
77299 assert( sqlite3SchemaMutexHeld(db, j, 0) );
77300 p = sqlite3HashFind(&db->aDb[j].pSchema->tblHash, zName, nName);
77301 if( p ) break;
77303 return p;
77307 ** Locate the in-memory structure that describes a particular database
77308 ** table given the name of that table and (optionally) the name of the
77309 ** database containing the table. Return NULL if not found. Also leave an
77310 ** error message in pParse->zErrMsg.
77312 ** The difference between this routine and sqlite3FindTable() is that this
77313 ** routine leaves an error message in pParse->zErrMsg where
77314 ** sqlite3FindTable() does not.
77316 SQLITE_PRIVATE Table *sqlite3LocateTable(
77317 Parse *pParse, /* context in which to report errors */
77318 int isView, /* True if looking for a VIEW rather than a TABLE */
77319 const char *zName, /* Name of the table we are looking for */
77320 const char *zDbase /* Name of the database. Might be NULL */
77322 Table *p;
77324 /* Read the database schema. If an error occurs, leave an error message
77325 ** and code in pParse and return NULL. */
77326 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
77327 return 0;
77330 p = sqlite3FindTable(pParse->db, zName, zDbase);
77331 if( p==0 ){
77332 const char *zMsg = isView ? "no such view" : "no such table";
77333 if( zDbase ){
77334 sqlite3ErrorMsg(pParse, "%s: %s.%s", zMsg, zDbase, zName);
77335 }else{
77336 sqlite3ErrorMsg(pParse, "%s: %s", zMsg, zName);
77338 pParse->checkSchema = 1;
77340 return p;
77344 ** Locate the in-memory structure that describes
77345 ** a particular index given the name of that index
77346 ** and the name of the database that contains the index.
77347 ** Return NULL if not found.
77349 ** If zDatabase is 0, all databases are searched for the
77350 ** table and the first matching index is returned. (No checking
77351 ** for duplicate index names is done.) The search order is
77352 ** TEMP first, then MAIN, then any auxiliary databases added
77353 ** using the ATTACH command.
77355 SQLITE_PRIVATE Index *sqlite3FindIndex(sqlite3 *db, const char *zName, const char *zDb){
77356 Index *p = 0;
77357 int i;
77358 int nName = sqlite3Strlen30(zName);
77359 /* All mutexes are required for schema access. Make sure we hold them. */
77360 assert( zDb!=0 || sqlite3BtreeHoldsAllMutexes(db) );
77361 for(i=OMIT_TEMPDB; i<db->nDb; i++){
77362 int j = (i<2) ? i^1 : i; /* Search TEMP before MAIN */
77363 Schema *pSchema = db->aDb[j].pSchema;
77364 assert( pSchema );
77365 if( zDb && sqlite3StrICmp(zDb, db->aDb[j].zName) ) continue;
77366 assert( sqlite3SchemaMutexHeld(db, j, 0) );
77367 p = sqlite3HashFind(&pSchema->idxHash, zName, nName);
77368 if( p ) break;
77370 return p;
77374 ** Reclaim the memory used by an index
77376 static void freeIndex(sqlite3 *db, Index *p){
77377 #ifndef SQLITE_OMIT_ANALYZE
77378 sqlite3DeleteIndexSamples(db, p);
77379 #endif
77380 sqlite3DbFree(db, p->zColAff);
77381 sqlite3DbFree(db, p);
77385 ** For the index called zIdxName which is found in the database iDb,
77386 ** unlike that index from its Table then remove the index from
77387 ** the index hash table and free all memory structures associated
77388 ** with the index.
77390 SQLITE_PRIVATE void sqlite3UnlinkAndDeleteIndex(sqlite3 *db, int iDb, const char *zIdxName){
77391 Index *pIndex;
77392 int len;
77393 Hash *pHash;
77395 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
77396 pHash = &db->aDb[iDb].pSchema->idxHash;
77397 len = sqlite3Strlen30(zIdxName);
77398 pIndex = sqlite3HashInsert(pHash, zIdxName, len, 0);
77399 if( ALWAYS(pIndex) ){
77400 if( pIndex->pTable->pIndex==pIndex ){
77401 pIndex->pTable->pIndex = pIndex->pNext;
77402 }else{
77403 Index *p;
77404 /* Justification of ALWAYS(); The index must be on the list of
77405 ** indices. */
77406 p = pIndex->pTable->pIndex;
77407 while( ALWAYS(p) && p->pNext!=pIndex ){ p = p->pNext; }
77408 if( ALWAYS(p && p->pNext==pIndex) ){
77409 p->pNext = pIndex->pNext;
77412 freeIndex(db, pIndex);
77414 db->flags |= SQLITE_InternChanges;
77418 ** Erase all schema information from the in-memory hash tables of
77419 ** a single database. This routine is called to reclaim memory
77420 ** before the database closes. It is also called during a rollback
77421 ** if there were schema changes during the transaction or if a
77422 ** schema-cookie mismatch occurs.
77424 ** If iDb<0 then reset the internal schema tables for all database
77425 ** files. If iDb>=0 then reset the internal schema for only the
77426 ** single file indicated.
77428 SQLITE_PRIVATE void sqlite3ResetInternalSchema(sqlite3 *db, int iDb){
77429 int i, j;
77430 assert( iDb<db->nDb );
77432 if( iDb>=0 ){
77433 /* Case 1: Reset the single schema identified by iDb */
77434 Db *pDb = &db->aDb[iDb];
77435 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
77436 assert( pDb->pSchema!=0 );
77437 sqlite3SchemaClear(pDb->pSchema);
77439 /* If any database other than TEMP is reset, then also reset TEMP
77440 ** since TEMP might be holding triggers that reference tables in the
77441 ** other database.
77443 if( iDb!=1 ){
77444 pDb = &db->aDb[1];
77445 assert( pDb->pSchema!=0 );
77446 sqlite3SchemaClear(pDb->pSchema);
77448 return;
77450 /* Case 2 (from here to the end): Reset all schemas for all attached
77451 ** databases. */
77452 assert( iDb<0 );
77453 sqlite3BtreeEnterAll(db);
77454 for(i=0; i<db->nDb; i++){
77455 Db *pDb = &db->aDb[i];
77456 if( pDb->pSchema ){
77457 sqlite3SchemaClear(pDb->pSchema);
77460 db->flags &= ~SQLITE_InternChanges;
77461 sqlite3VtabUnlockList(db);
77462 sqlite3BtreeLeaveAll(db);
77464 /* If one or more of the auxiliary database files has been closed,
77465 ** then remove them from the auxiliary database list. We take the
77466 ** opportunity to do this here since we have just deleted all of the
77467 ** schema hash tables and therefore do not have to make any changes
77468 ** to any of those tables.
77470 for(i=j=2; i<db->nDb; i++){
77471 struct Db *pDb = &db->aDb[i];
77472 if( pDb->pBt==0 ){
77473 sqlite3DbFree(db, pDb->zName);
77474 pDb->zName = 0;
77475 continue;
77477 if( j<i ){
77478 db->aDb[j] = db->aDb[i];
77480 j++;
77482 memset(&db->aDb[j], 0, (db->nDb-j)*sizeof(db->aDb[j]));
77483 db->nDb = j;
77484 if( db->nDb<=2 && db->aDb!=db->aDbStatic ){
77485 memcpy(db->aDbStatic, db->aDb, 2*sizeof(db->aDb[0]));
77486 sqlite3DbFree(db, db->aDb);
77487 db->aDb = db->aDbStatic;
77492 ** This routine is called when a commit occurs.
77494 SQLITE_PRIVATE void sqlite3CommitInternalChanges(sqlite3 *db){
77495 db->flags &= ~SQLITE_InternChanges;
77499 ** Delete memory allocated for the column names of a table or view (the
77500 ** Table.aCol[] array).
77502 static void sqliteDeleteColumnNames(sqlite3 *db, Table *pTable){
77503 int i;
77504 Column *pCol;
77505 assert( pTable!=0 );
77506 if( (pCol = pTable->aCol)!=0 ){
77507 for(i=0; i<pTable->nCol; i++, pCol++){
77508 sqlite3DbFree(db, pCol->zName);
77509 sqlite3ExprDelete(db, pCol->pDflt);
77510 sqlite3DbFree(db, pCol->zDflt);
77511 sqlite3DbFree(db, pCol->zType);
77512 sqlite3DbFree(db, pCol->zColl);
77514 sqlite3DbFree(db, pTable->aCol);
77519 ** Remove the memory data structures associated with the given
77520 ** Table. No changes are made to disk by this routine.
77522 ** This routine just deletes the data structure. It does not unlink
77523 ** the table data structure from the hash table. But it does destroy
77524 ** memory structures of the indices and foreign keys associated with
77525 ** the table.
77527 SQLITE_PRIVATE void sqlite3DeleteTable(sqlite3 *db, Table *pTable){
77528 Index *pIndex, *pNext;
77530 assert( !pTable || pTable->nRef>0 );
77532 /* Do not delete the table until the reference count reaches zero. */
77533 if( !pTable ) return;
77534 if( ((!db || db->pnBytesFreed==0) && (--pTable->nRef)>0) ) return;
77536 /* Delete all indices associated with this table. */
77537 for(pIndex = pTable->pIndex; pIndex; pIndex=pNext){
77538 pNext = pIndex->pNext;
77539 assert( pIndex->pSchema==pTable->pSchema );
77540 if( !db || db->pnBytesFreed==0 ){
77541 char *zName = pIndex->zName;
77542 TESTONLY ( Index *pOld = ) sqlite3HashInsert(
77543 &pIndex->pSchema->idxHash, zName, sqlite3Strlen30(zName), 0
77545 assert( db==0 || sqlite3SchemaMutexHeld(db, 0, pIndex->pSchema) );
77546 assert( pOld==pIndex || pOld==0 );
77548 freeIndex(db, pIndex);
77551 /* Delete any foreign keys attached to this table. */
77552 sqlite3FkDelete(db, pTable);
77554 /* Delete the Table structure itself.
77556 sqliteDeleteColumnNames(db, pTable);
77557 sqlite3DbFree(db, pTable->zName);
77558 sqlite3DbFree(db, pTable->zColAff);
77559 sqlite3SelectDelete(db, pTable->pSelect);
77560 #ifndef SQLITE_OMIT_CHECK
77561 sqlite3ExprDelete(db, pTable->pCheck);
77562 #endif
77563 #ifndef SQLITE_OMIT_VIRTUALTABLE
77564 sqlite3VtabClear(db, pTable);
77565 #endif
77566 sqlite3DbFree(db, pTable);
77570 ** Unlink the given table from the hash tables and the delete the
77571 ** table structure with all its indices and foreign keys.
77573 SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTable(sqlite3 *db, int iDb, const char *zTabName){
77574 Table *p;
77575 Db *pDb;
77577 assert( db!=0 );
77578 assert( iDb>=0 && iDb<db->nDb );
77579 assert( zTabName );
77580 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
77581 testcase( zTabName[0]==0 ); /* Zero-length table names are allowed */
77582 pDb = &db->aDb[iDb];
77583 p = sqlite3HashInsert(&pDb->pSchema->tblHash, zTabName,
77584 sqlite3Strlen30(zTabName),0);
77585 sqlite3DeleteTable(db, p);
77586 db->flags |= SQLITE_InternChanges;
77590 ** Given a token, return a string that consists of the text of that
77591 ** token. Space to hold the returned string
77592 ** is obtained from sqliteMalloc() and must be freed by the calling
77593 ** function.
77595 ** Any quotation marks (ex: "name", 'name', [name], or `name`) that
77596 ** surround the body of the token are removed.
77598 ** Tokens are often just pointers into the original SQL text and so
77599 ** are not \000 terminated and are not persistent. The returned string
77600 ** is \000 terminated and is persistent.
77602 SQLITE_PRIVATE char *sqlite3NameFromToken(sqlite3 *db, Token *pName){
77603 char *zName;
77604 if( pName ){
77605 zName = sqlite3DbStrNDup(db, (char*)pName->z, pName->n);
77606 sqlite3Dequote(zName);
77607 }else{
77608 zName = 0;
77610 return zName;
77614 ** Open the sqlite_master table stored in database number iDb for
77615 ** writing. The table is opened using cursor 0.
77617 SQLITE_PRIVATE void sqlite3OpenMasterTable(Parse *p, int iDb){
77618 Vdbe *v = sqlite3GetVdbe(p);
77619 sqlite3TableLock(p, iDb, MASTER_ROOT, 1, SCHEMA_TABLE(iDb));
77620 sqlite3VdbeAddOp3(v, OP_OpenWrite, 0, MASTER_ROOT, iDb);
77621 sqlite3VdbeChangeP4(v, -1, (char *)5, P4_INT32); /* 5 column table */
77622 if( p->nTab==0 ){
77623 p->nTab = 1;
77628 ** Parameter zName points to a nul-terminated buffer containing the name
77629 ** of a database ("main", "temp" or the name of an attached db). This
77630 ** function returns the index of the named database in db->aDb[], or
77631 ** -1 if the named db cannot be found.
77633 SQLITE_PRIVATE int sqlite3FindDbName(sqlite3 *db, const char *zName){
77634 int i = -1; /* Database number */
77635 if( zName ){
77636 Db *pDb;
77637 int n = sqlite3Strlen30(zName);
77638 for(i=(db->nDb-1), pDb=&db->aDb[i]; i>=0; i--, pDb--){
77639 if( (!OMIT_TEMPDB || i!=1 ) && n==sqlite3Strlen30(pDb->zName) &&
77640 0==sqlite3StrICmp(pDb->zName, zName) ){
77641 break;
77645 return i;
77649 ** The token *pName contains the name of a database (either "main" or
77650 ** "temp" or the name of an attached db). This routine returns the
77651 ** index of the named database in db->aDb[], or -1 if the named db
77652 ** does not exist.
77654 SQLITE_PRIVATE int sqlite3FindDb(sqlite3 *db, Token *pName){
77655 int i; /* Database number */
77656 char *zName; /* Name we are searching for */
77657 zName = sqlite3NameFromToken(db, pName);
77658 i = sqlite3FindDbName(db, zName);
77659 sqlite3DbFree(db, zName);
77660 return i;
77663 /* The table or view or trigger name is passed to this routine via tokens
77664 ** pName1 and pName2. If the table name was fully qualified, for example:
77666 ** CREATE TABLE xxx.yyy (...);
77668 ** Then pName1 is set to "xxx" and pName2 "yyy". On the other hand if
77669 ** the table name is not fully qualified, i.e.:
77671 ** CREATE TABLE yyy(...);
77673 ** Then pName1 is set to "yyy" and pName2 is "".
77675 ** This routine sets the *ppUnqual pointer to point at the token (pName1 or
77676 ** pName2) that stores the unqualified table name. The index of the
77677 ** database "xxx" is returned.
77679 SQLITE_PRIVATE int sqlite3TwoPartName(
77680 Parse *pParse, /* Parsing and code generating context */
77681 Token *pName1, /* The "xxx" in the name "xxx.yyy" or "xxx" */
77682 Token *pName2, /* The "yyy" in the name "xxx.yyy" */
77683 Token **pUnqual /* Write the unqualified object name here */
77685 int iDb; /* Database holding the object */
77686 sqlite3 *db = pParse->db;
77688 if( ALWAYS(pName2!=0) && pName2->n>0 ){
77689 if( db->init.busy ) {
77690 sqlite3ErrorMsg(pParse, "corrupt database");
77691 pParse->nErr++;
77692 return -1;
77694 *pUnqual = pName2;
77695 iDb = sqlite3FindDb(db, pName1);
77696 if( iDb<0 ){
77697 sqlite3ErrorMsg(pParse, "unknown database %T", pName1);
77698 pParse->nErr++;
77699 return -1;
77701 }else{
77702 assert( db->init.iDb==0 || db->init.busy );
77703 iDb = db->init.iDb;
77704 *pUnqual = pName1;
77706 return iDb;
77710 ** This routine is used to check if the UTF-8 string zName is a legal
77711 ** unqualified name for a new schema object (table, index, view or
77712 ** trigger). All names are legal except those that begin with the string
77713 ** "sqlite_" (in upper, lower or mixed case). This portion of the namespace
77714 ** is reserved for internal use.
77716 SQLITE_PRIVATE int sqlite3CheckObjectName(Parse *pParse, const char *zName){
77717 if( !pParse->db->init.busy && pParse->nested==0
77718 && (pParse->db->flags & SQLITE_WriteSchema)==0
77719 && 0==sqlite3StrNICmp(zName, "sqlite_", 7) ){
77720 sqlite3ErrorMsg(pParse, "object name reserved for internal use: %s", zName);
77721 return SQLITE_ERROR;
77723 return SQLITE_OK;
77727 ** Begin constructing a new table representation in memory. This is
77728 ** the first of several action routines that get called in response
77729 ** to a CREATE TABLE statement. In particular, this routine is called
77730 ** after seeing tokens "CREATE" and "TABLE" and the table name. The isTemp
77731 ** flag is true if the table should be stored in the auxiliary database
77732 ** file instead of in the main database file. This is normally the case
77733 ** when the "TEMP" or "TEMPORARY" keyword occurs in between
77734 ** CREATE and TABLE.
77736 ** The new table record is initialized and put in pParse->pNewTable.
77737 ** As more of the CREATE TABLE statement is parsed, additional action
77738 ** routines will be called to add more information to this record.
77739 ** At the end of the CREATE TABLE statement, the sqlite3EndTable() routine
77740 ** is called to complete the construction of the new table record.
77742 SQLITE_PRIVATE void sqlite3StartTable(
77743 Parse *pParse, /* Parser context */
77744 Token *pName1, /* First part of the name of the table or view */
77745 Token *pName2, /* Second part of the name of the table or view */
77746 int isTemp, /* True if this is a TEMP table */
77747 int isView, /* True if this is a VIEW */
77748 int isVirtual, /* True if this is a VIRTUAL table */
77749 int noErr /* Do nothing if table already exists */
77751 Table *pTable;
77752 char *zName = 0; /* The name of the new table */
77753 sqlite3 *db = pParse->db;
77754 Vdbe *v;
77755 int iDb; /* Database number to create the table in */
77756 Token *pName; /* Unqualified name of the table to create */
77758 /* The table or view name to create is passed to this routine via tokens
77759 ** pName1 and pName2. If the table name was fully qualified, for example:
77761 ** CREATE TABLE xxx.yyy (...);
77763 ** Then pName1 is set to "xxx" and pName2 "yyy". On the other hand if
77764 ** the table name is not fully qualified, i.e.:
77766 ** CREATE TABLE yyy(...);
77768 ** Then pName1 is set to "yyy" and pName2 is "".
77770 ** The call below sets the pName pointer to point at the token (pName1 or
77771 ** pName2) that stores the unqualified table name. The variable iDb is
77772 ** set to the index of the database that the table or view is to be
77773 ** created in.
77775 iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
77776 if( iDb<0 ) return;
77777 if( !OMIT_TEMPDB && isTemp && pName2->n>0 && iDb!=1 ){
77778 /* If creating a temp table, the name may not be qualified. Unless
77779 ** the database name is "temp" anyway. */
77780 sqlite3ErrorMsg(pParse, "temporary table name must be unqualified");
77781 return;
77783 if( !OMIT_TEMPDB && isTemp ) iDb = 1;
77785 pParse->sNameToken = *pName;
77786 zName = sqlite3NameFromToken(db, pName);
77787 if( zName==0 ) return;
77788 if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
77789 goto begin_table_error;
77791 if( db->init.iDb==1 ) isTemp = 1;
77792 #ifndef SQLITE_OMIT_AUTHORIZATION
77793 assert( (isTemp & 1)==isTemp );
77795 int code;
77796 char *zDb = db->aDb[iDb].zName;
77797 if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(isTemp), 0, zDb) ){
77798 goto begin_table_error;
77800 if( isView ){
77801 if( !OMIT_TEMPDB && isTemp ){
77802 code = SQLITE_CREATE_TEMP_VIEW;
77803 }else{
77804 code = SQLITE_CREATE_VIEW;
77806 }else{
77807 if( !OMIT_TEMPDB && isTemp ){
77808 code = SQLITE_CREATE_TEMP_TABLE;
77809 }else{
77810 code = SQLITE_CREATE_TABLE;
77813 if( !isVirtual && sqlite3AuthCheck(pParse, code, zName, 0, zDb) ){
77814 goto begin_table_error;
77817 #endif
77819 /* Make sure the new table name does not collide with an existing
77820 ** index or table name in the same database. Issue an error message if
77821 ** it does. The exception is if the statement being parsed was passed
77822 ** to an sqlite3_declare_vtab() call. In that case only the column names
77823 ** and types will be used, so there is no need to test for namespace
77824 ** collisions.
77826 if( !IN_DECLARE_VTAB ){
77827 char *zDb = db->aDb[iDb].zName;
77828 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
77829 goto begin_table_error;
77831 pTable = sqlite3FindTable(db, zName, zDb);
77832 if( pTable ){
77833 if( !noErr ){
77834 sqlite3ErrorMsg(pParse, "table %T already exists", pName);
77835 }else{
77836 assert( !db->init.busy );
77837 sqlite3CodeVerifySchema(pParse, iDb);
77839 goto begin_table_error;
77841 if( sqlite3FindIndex(db, zName, zDb)!=0 ){
77842 sqlite3ErrorMsg(pParse, "there is already an index named %s", zName);
77843 goto begin_table_error;
77847 pTable = sqlite3DbMallocZero(db, sizeof(Table));
77848 if( pTable==0 ){
77849 db->mallocFailed = 1;
77850 pParse->rc = SQLITE_NOMEM;
77851 pParse->nErr++;
77852 goto begin_table_error;
77854 pTable->zName = zName;
77855 pTable->iPKey = -1;
77856 pTable->pSchema = db->aDb[iDb].pSchema;
77857 pTable->nRef = 1;
77858 pTable->nRowEst = 1000000;
77859 assert( pParse->pNewTable==0 );
77860 pParse->pNewTable = pTable;
77862 /* If this is the magic sqlite_sequence table used by autoincrement,
77863 ** then record a pointer to this table in the main database structure
77864 ** so that INSERT can find the table easily.
77866 #ifndef SQLITE_OMIT_AUTOINCREMENT
77867 if( !pParse->nested && strcmp(zName, "sqlite_sequence")==0 ){
77868 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
77869 pTable->pSchema->pSeqTab = pTable;
77871 #endif
77873 /* Begin generating the code that will insert the table record into
77874 ** the SQLITE_MASTER table. Note in particular that we must go ahead
77875 ** and allocate the record number for the table entry now. Before any
77876 ** PRIMARY KEY or UNIQUE keywords are parsed. Those keywords will cause
77877 ** indices to be created and the table record must come before the
77878 ** indices. Hence, the record number for the table must be allocated
77879 ** now.
77881 if( !db->init.busy && (v = sqlite3GetVdbe(pParse))!=0 ){
77882 int j1;
77883 int fileFormat;
77884 int reg1, reg2, reg3;
77885 sqlite3BeginWriteOperation(pParse, 0, iDb);
77887 #ifndef SQLITE_OMIT_VIRTUALTABLE
77888 if( isVirtual ){
77889 sqlite3VdbeAddOp0(v, OP_VBegin);
77891 #endif
77893 /* If the file format and encoding in the database have not been set,
77894 ** set them now.
77896 reg1 = pParse->regRowid = ++pParse->nMem;
77897 reg2 = pParse->regRoot = ++pParse->nMem;
77898 reg3 = ++pParse->nMem;
77899 sqlite3VdbeAddOp3(v, OP_ReadCookie, iDb, reg3, BTREE_FILE_FORMAT);
77900 sqlite3VdbeUsesBtree(v, iDb);
77901 j1 = sqlite3VdbeAddOp1(v, OP_If, reg3);
77902 fileFormat = (db->flags & SQLITE_LegacyFileFmt)!=0 ?
77903 1 : SQLITE_MAX_FILE_FORMAT;
77904 sqlite3VdbeAddOp2(v, OP_Integer, fileFormat, reg3);
77905 sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_FILE_FORMAT, reg3);
77906 sqlite3VdbeAddOp2(v, OP_Integer, ENC(db), reg3);
77907 sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_TEXT_ENCODING, reg3);
77908 sqlite3VdbeJumpHere(v, j1);
77910 /* This just creates a place-holder record in the sqlite_master table.
77911 ** The record created does not contain anything yet. It will be replaced
77912 ** by the real entry in code generated at sqlite3EndTable().
77914 ** The rowid for the new entry is left in register pParse->regRowid.
77915 ** The root page number of the new table is left in reg pParse->regRoot.
77916 ** The rowid and root page number values are needed by the code that
77917 ** sqlite3EndTable will generate.
77919 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
77920 if( isView || isVirtual ){
77921 sqlite3VdbeAddOp2(v, OP_Integer, 0, reg2);
77922 }else
77923 #endif
77925 sqlite3VdbeAddOp2(v, OP_CreateTable, iDb, reg2);
77927 sqlite3OpenMasterTable(pParse, iDb);
77928 sqlite3VdbeAddOp2(v, OP_NewRowid, 0, reg1);
77929 sqlite3VdbeAddOp2(v, OP_Null, 0, reg3);
77930 sqlite3VdbeAddOp3(v, OP_Insert, 0, reg3, reg1);
77931 sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
77932 sqlite3VdbeAddOp0(v, OP_Close);
77935 /* Normal (non-error) return. */
77936 return;
77938 /* If an error occurs, we jump here */
77939 begin_table_error:
77940 sqlite3DbFree(db, zName);
77941 return;
77945 ** This macro is used to compare two strings in a case-insensitive manner.
77946 ** It is slightly faster than calling sqlite3StrICmp() directly, but
77947 ** produces larger code.
77949 ** WARNING: This macro is not compatible with the strcmp() family. It
77950 ** returns true if the two strings are equal, otherwise false.
77952 #define STRICMP(x, y) (\
77953 sqlite3UpperToLower[*(unsigned char *)(x)]== \
77954 sqlite3UpperToLower[*(unsigned char *)(y)] \
77955 && sqlite3StrICmp((x)+1,(y)+1)==0 )
77958 ** Add a new column to the table currently being constructed.
77960 ** The parser calls this routine once for each column declaration
77961 ** in a CREATE TABLE statement. sqlite3StartTable() gets called
77962 ** first to get things going. Then this routine is called for each
77963 ** column.
77965 SQLITE_PRIVATE void sqlite3AddColumn(Parse *pParse, Token *pName){
77966 Table *p;
77967 int i;
77968 char *z;
77969 Column *pCol;
77970 sqlite3 *db = pParse->db;
77971 if( (p = pParse->pNewTable)==0 ) return;
77972 #if SQLITE_MAX_COLUMN
77973 if( p->nCol+1>db->aLimit[SQLITE_LIMIT_COLUMN] ){
77974 sqlite3ErrorMsg(pParse, "too many columns on %s", p->zName);
77975 return;
77977 #endif
77978 z = sqlite3NameFromToken(db, pName);
77979 if( z==0 ) return;
77980 for(i=0; i<p->nCol; i++){
77981 if( STRICMP(z, p->aCol[i].zName) ){
77982 sqlite3ErrorMsg(pParse, "duplicate column name: %s", z);
77983 sqlite3DbFree(db, z);
77984 return;
77987 if( (p->nCol & 0x7)==0 ){
77988 Column *aNew;
77989 aNew = sqlite3DbRealloc(db,p->aCol,(p->nCol+8)*sizeof(p->aCol[0]));
77990 if( aNew==0 ){
77991 sqlite3DbFree(db, z);
77992 return;
77994 p->aCol = aNew;
77996 pCol = &p->aCol[p->nCol];
77997 memset(pCol, 0, sizeof(p->aCol[0]));
77998 pCol->zName = z;
78000 /* If there is no type specified, columns have the default affinity
78001 ** 'NONE'. If there is a type specified, then sqlite3AddColumnType() will
78002 ** be called next to set pCol->affinity correctly.
78004 pCol->affinity = SQLITE_AFF_NONE;
78005 p->nCol++;
78009 ** This routine is called by the parser while in the middle of
78010 ** parsing a CREATE TABLE statement. A "NOT NULL" constraint has
78011 ** been seen on a column. This routine sets the notNull flag on
78012 ** the column currently under construction.
78014 SQLITE_PRIVATE void sqlite3AddNotNull(Parse *pParse, int onError){
78015 Table *p;
78016 p = pParse->pNewTable;
78017 if( p==0 || NEVER(p->nCol<1) ) return;
78018 p->aCol[p->nCol-1].notNull = (u8)onError;
78022 ** Scan the column type name zType (length nType) and return the
78023 ** associated affinity type.
78025 ** This routine does a case-independent search of zType for the
78026 ** substrings in the following table. If one of the substrings is
78027 ** found, the corresponding affinity is returned. If zType contains
78028 ** more than one of the substrings, entries toward the top of
78029 ** the table take priority. For example, if zType is 'BLOBINT',
78030 ** SQLITE_AFF_INTEGER is returned.
78032 ** Substring | Affinity
78033 ** --------------------------------
78034 ** 'INT' | SQLITE_AFF_INTEGER
78035 ** 'CHAR' | SQLITE_AFF_TEXT
78036 ** 'CLOB' | SQLITE_AFF_TEXT
78037 ** 'TEXT' | SQLITE_AFF_TEXT
78038 ** 'BLOB' | SQLITE_AFF_NONE
78039 ** 'REAL' | SQLITE_AFF_REAL
78040 ** 'FLOA' | SQLITE_AFF_REAL
78041 ** 'DOUB' | SQLITE_AFF_REAL
78043 ** If none of the substrings in the above table are found,
78044 ** SQLITE_AFF_NUMERIC is returned.
78046 SQLITE_PRIVATE char sqlite3AffinityType(const char *zIn){
78047 u32 h = 0;
78048 char aff = SQLITE_AFF_NUMERIC;
78050 if( zIn ) while( zIn[0] ){
78051 h = (h<<8) + sqlite3UpperToLower[(*zIn)&0xff];
78052 zIn++;
78053 if( h==(('c'<<24)+('h'<<16)+('a'<<8)+'r') ){ /* CHAR */
78054 aff = SQLITE_AFF_TEXT;
78055 }else if( h==(('c'<<24)+('l'<<16)+('o'<<8)+'b') ){ /* CLOB */
78056 aff = SQLITE_AFF_TEXT;
78057 }else if( h==(('t'<<24)+('e'<<16)+('x'<<8)+'t') ){ /* TEXT */
78058 aff = SQLITE_AFF_TEXT;
78059 }else if( h==(('b'<<24)+('l'<<16)+('o'<<8)+'b') /* BLOB */
78060 && (aff==SQLITE_AFF_NUMERIC || aff==SQLITE_AFF_REAL) ){
78061 aff = SQLITE_AFF_NONE;
78062 #ifndef SQLITE_OMIT_FLOATING_POINT
78063 }else if( h==(('r'<<24)+('e'<<16)+('a'<<8)+'l') /* REAL */
78064 && aff==SQLITE_AFF_NUMERIC ){
78065 aff = SQLITE_AFF_REAL;
78066 }else if( h==(('f'<<24)+('l'<<16)+('o'<<8)+'a') /* FLOA */
78067 && aff==SQLITE_AFF_NUMERIC ){
78068 aff = SQLITE_AFF_REAL;
78069 }else if( h==(('d'<<24)+('o'<<16)+('u'<<8)+'b') /* DOUB */
78070 && aff==SQLITE_AFF_NUMERIC ){
78071 aff = SQLITE_AFF_REAL;
78072 #endif
78073 }else if( (h&0x00FFFFFF)==(('i'<<16)+('n'<<8)+'t') ){ /* INT */
78074 aff = SQLITE_AFF_INTEGER;
78075 break;
78079 return aff;
78083 ** This routine is called by the parser while in the middle of
78084 ** parsing a CREATE TABLE statement. The pFirst token is the first
78085 ** token in the sequence of tokens that describe the type of the
78086 ** column currently under construction. pLast is the last token
78087 ** in the sequence. Use this information to construct a string
78088 ** that contains the typename of the column and store that string
78089 ** in zType.
78091 SQLITE_PRIVATE void sqlite3AddColumnType(Parse *pParse, Token *pType){
78092 Table *p;
78093 Column *pCol;
78095 p = pParse->pNewTable;
78096 if( p==0 || NEVER(p->nCol<1) ) return;
78097 pCol = &p->aCol[p->nCol-1];
78098 assert( pCol->zType==0 );
78099 pCol->zType = sqlite3NameFromToken(pParse->db, pType);
78100 pCol->affinity = sqlite3AffinityType(pCol->zType);
78104 ** The expression is the default value for the most recently added column
78105 ** of the table currently under construction.
78107 ** Default value expressions must be constant. Raise an exception if this
78108 ** is not the case.
78110 ** This routine is called by the parser while in the middle of
78111 ** parsing a CREATE TABLE statement.
78113 SQLITE_PRIVATE void sqlite3AddDefaultValue(Parse *pParse, ExprSpan *pSpan){
78114 Table *p;
78115 Column *pCol;
78116 sqlite3 *db = pParse->db;
78117 p = pParse->pNewTable;
78118 if( p!=0 ){
78119 pCol = &(p->aCol[p->nCol-1]);
78120 if( !sqlite3ExprIsConstantOrFunction(pSpan->pExpr) ){
78121 sqlite3ErrorMsg(pParse, "default value of column [%s] is not constant",
78122 pCol->zName);
78123 }else{
78124 /* A copy of pExpr is used instead of the original, as pExpr contains
78125 ** tokens that point to volatile memory. The 'span' of the expression
78126 ** is required by pragma table_info.
78128 sqlite3ExprDelete(db, pCol->pDflt);
78129 pCol->pDflt = sqlite3ExprDup(db, pSpan->pExpr, EXPRDUP_REDUCE);
78130 sqlite3DbFree(db, pCol->zDflt);
78131 pCol->zDflt = sqlite3DbStrNDup(db, (char*)pSpan->zStart,
78132 (int)(pSpan->zEnd - pSpan->zStart));
78135 sqlite3ExprDelete(db, pSpan->pExpr);
78139 ** Designate the PRIMARY KEY for the table. pList is a list of names
78140 ** of columns that form the primary key. If pList is NULL, then the
78141 ** most recently added column of the table is the primary key.
78143 ** A table can have at most one primary key. If the table already has
78144 ** a primary key (and this is the second primary key) then create an
78145 ** error.
78147 ** If the PRIMARY KEY is on a single column whose datatype is INTEGER,
78148 ** then we will try to use that column as the rowid. Set the Table.iPKey
78149 ** field of the table under construction to be the index of the
78150 ** INTEGER PRIMARY KEY column. Table.iPKey is set to -1 if there is
78151 ** no INTEGER PRIMARY KEY.
78153 ** If the key is not an INTEGER PRIMARY KEY, then create a unique
78154 ** index for the key. No index is created for INTEGER PRIMARY KEYs.
78156 SQLITE_PRIVATE void sqlite3AddPrimaryKey(
78157 Parse *pParse, /* Parsing context */
78158 ExprList *pList, /* List of field names to be indexed */
78159 int onError, /* What to do with a uniqueness conflict */
78160 int autoInc, /* True if the AUTOINCREMENT keyword is present */
78161 int sortOrder /* SQLITE_SO_ASC or SQLITE_SO_DESC */
78163 Table *pTab = pParse->pNewTable;
78164 char *zType = 0;
78165 int iCol = -1, i;
78166 if( pTab==0 || IN_DECLARE_VTAB ) goto primary_key_exit;
78167 if( pTab->tabFlags & TF_HasPrimaryKey ){
78168 sqlite3ErrorMsg(pParse,
78169 "table \"%s\" has more than one primary key", pTab->zName);
78170 goto primary_key_exit;
78172 pTab->tabFlags |= TF_HasPrimaryKey;
78173 if( pList==0 ){
78174 iCol = pTab->nCol - 1;
78175 pTab->aCol[iCol].isPrimKey = 1;
78176 }else{
78177 for(i=0; i<pList->nExpr; i++){
78178 for(iCol=0; iCol<pTab->nCol; iCol++){
78179 if( sqlite3StrICmp(pList->a[i].zName, pTab->aCol[iCol].zName)==0 ){
78180 break;
78183 if( iCol<pTab->nCol ){
78184 pTab->aCol[iCol].isPrimKey = 1;
78187 if( pList->nExpr>1 ) iCol = -1;
78189 if( iCol>=0 && iCol<pTab->nCol ){
78190 zType = pTab->aCol[iCol].zType;
78192 if( zType && sqlite3StrICmp(zType, "INTEGER")==0
78193 && sortOrder==SQLITE_SO_ASC ){
78194 pTab->iPKey = iCol;
78195 pTab->keyConf = (u8)onError;
78196 assert( autoInc==0 || autoInc==1 );
78197 pTab->tabFlags |= autoInc*TF_Autoincrement;
78198 }else if( autoInc ){
78199 #ifndef SQLITE_OMIT_AUTOINCREMENT
78200 sqlite3ErrorMsg(pParse, "AUTOINCREMENT is only allowed on an "
78201 "INTEGER PRIMARY KEY");
78202 #endif
78203 }else{
78204 Index *p;
78205 p = sqlite3CreateIndex(pParse, 0, 0, 0, pList, onError, 0, 0, sortOrder, 0);
78206 if( p ){
78207 p->autoIndex = 2;
78209 pList = 0;
78212 primary_key_exit:
78213 sqlite3ExprListDelete(pParse->db, pList);
78214 return;
78218 ** Add a new CHECK constraint to the table currently under construction.
78220 SQLITE_PRIVATE void sqlite3AddCheckConstraint(
78221 Parse *pParse, /* Parsing context */
78222 Expr *pCheckExpr /* The check expression */
78224 sqlite3 *db = pParse->db;
78225 #ifndef SQLITE_OMIT_CHECK
78226 Table *pTab = pParse->pNewTable;
78227 if( pTab && !IN_DECLARE_VTAB ){
78228 pTab->pCheck = sqlite3ExprAnd(db, pTab->pCheck, pCheckExpr);
78229 }else
78230 #endif
78232 sqlite3ExprDelete(db, pCheckExpr);
78237 ** Set the collation function of the most recently parsed table column
78238 ** to the CollSeq given.
78240 SQLITE_PRIVATE void sqlite3AddCollateType(Parse *pParse, Token *pToken){
78241 Table *p;
78242 int i;
78243 char *zColl; /* Dequoted name of collation sequence */
78244 sqlite3 *db;
78246 if( (p = pParse->pNewTable)==0 ) return;
78247 i = p->nCol-1;
78248 db = pParse->db;
78249 zColl = sqlite3NameFromToken(db, pToken);
78250 if( !zColl ) return;
78252 if( sqlite3LocateCollSeq(pParse, zColl) ){
78253 Index *pIdx;
78254 p->aCol[i].zColl = zColl;
78256 /* If the column is declared as "<name> PRIMARY KEY COLLATE <type>",
78257 ** then an index may have been created on this column before the
78258 ** collation type was added. Correct this if it is the case.
78260 for(pIdx=p->pIndex; pIdx; pIdx=pIdx->pNext){
78261 assert( pIdx->nColumn==1 );
78262 if( pIdx->aiColumn[0]==i ){
78263 pIdx->azColl[0] = p->aCol[i].zColl;
78266 }else{
78267 sqlite3DbFree(db, zColl);
78272 ** This function returns the collation sequence for database native text
78273 ** encoding identified by the string zName, length nName.
78275 ** If the requested collation sequence is not available, or not available
78276 ** in the database native encoding, the collation factory is invoked to
78277 ** request it. If the collation factory does not supply such a sequence,
78278 ** and the sequence is available in another text encoding, then that is
78279 ** returned instead.
78281 ** If no versions of the requested collations sequence are available, or
78282 ** another error occurs, NULL is returned and an error message written into
78283 ** pParse.
78285 ** This routine is a wrapper around sqlite3FindCollSeq(). This routine
78286 ** invokes the collation factory if the named collation cannot be found
78287 ** and generates an error message.
78289 ** See also: sqlite3FindCollSeq(), sqlite3GetCollSeq()
78291 SQLITE_PRIVATE CollSeq *sqlite3LocateCollSeq(Parse *pParse, const char *zName){
78292 sqlite3 *db = pParse->db;
78293 u8 enc = ENC(db);
78294 u8 initbusy = db->init.busy;
78295 CollSeq *pColl;
78297 pColl = sqlite3FindCollSeq(db, enc, zName, initbusy);
78298 if( !initbusy && (!pColl || !pColl->xCmp) ){
78299 pColl = sqlite3GetCollSeq(db, enc, pColl, zName);
78300 if( !pColl ){
78301 sqlite3ErrorMsg(pParse, "no such collation sequence: %s", zName);
78305 return pColl;
78310 ** Generate code that will increment the schema cookie.
78312 ** The schema cookie is used to determine when the schema for the
78313 ** database changes. After each schema change, the cookie value
78314 ** changes. When a process first reads the schema it records the
78315 ** cookie. Thereafter, whenever it goes to access the database,
78316 ** it checks the cookie to make sure the schema has not changed
78317 ** since it was last read.
78319 ** This plan is not completely bullet-proof. It is possible for
78320 ** the schema to change multiple times and for the cookie to be
78321 ** set back to prior value. But schema changes are infrequent
78322 ** and the probability of hitting the same cookie value is only
78323 ** 1 chance in 2^32. So we're safe enough.
78325 SQLITE_PRIVATE void sqlite3ChangeCookie(Parse *pParse, int iDb){
78326 int r1 = sqlite3GetTempReg(pParse);
78327 sqlite3 *db = pParse->db;
78328 Vdbe *v = pParse->pVdbe;
78329 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
78330 sqlite3VdbeAddOp2(v, OP_Integer, db->aDb[iDb].pSchema->schema_cookie+1, r1);
78331 sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_SCHEMA_VERSION, r1);
78332 sqlite3ReleaseTempReg(pParse, r1);
78336 ** Measure the number of characters needed to output the given
78337 ** identifier. The number returned includes any quotes used
78338 ** but does not include the null terminator.
78340 ** The estimate is conservative. It might be larger that what is
78341 ** really needed.
78343 static int identLength(const char *z){
78344 int n;
78345 for(n=0; *z; n++, z++){
78346 if( *z=='"' ){ n++; }
78348 return n + 2;
78352 ** The first parameter is a pointer to an output buffer. The second
78353 ** parameter is a pointer to an integer that contains the offset at
78354 ** which to write into the output buffer. This function copies the
78355 ** nul-terminated string pointed to by the third parameter, zSignedIdent,
78356 ** to the specified offset in the buffer and updates *pIdx to refer
78357 ** to the first byte after the last byte written before returning.
78359 ** If the string zSignedIdent consists entirely of alpha-numeric
78360 ** characters, does not begin with a digit and is not an SQL keyword,
78361 ** then it is copied to the output buffer exactly as it is. Otherwise,
78362 ** it is quoted using double-quotes.
78364 static void identPut(char *z, int *pIdx, char *zSignedIdent){
78365 unsigned char *zIdent = (unsigned char*)zSignedIdent;
78366 int i, j, needQuote;
78367 i = *pIdx;
78369 for(j=0; zIdent[j]; j++){
78370 if( !sqlite3Isalnum(zIdent[j]) && zIdent[j]!='_' ) break;
78372 needQuote = sqlite3Isdigit(zIdent[0]) || sqlite3KeywordCode(zIdent, j)!=TK_ID;
78373 if( !needQuote ){
78374 needQuote = zIdent[j];
78377 if( needQuote ) z[i++] = '"';
78378 for(j=0; zIdent[j]; j++){
78379 z[i++] = zIdent[j];
78380 if( zIdent[j]=='"' ) z[i++] = '"';
78382 if( needQuote ) z[i++] = '"';
78383 z[i] = 0;
78384 *pIdx = i;
78388 ** Generate a CREATE TABLE statement appropriate for the given
78389 ** table. Memory to hold the text of the statement is obtained
78390 ** from sqliteMalloc() and must be freed by the calling function.
78392 static char *createTableStmt(sqlite3 *db, Table *p){
78393 int i, k, n;
78394 char *zStmt;
78395 char *zSep, *zSep2, *zEnd;
78396 Column *pCol;
78397 n = 0;
78398 for(pCol = p->aCol, i=0; i<p->nCol; i++, pCol++){
78399 n += identLength(pCol->zName) + 5;
78401 n += identLength(p->zName);
78402 if( n<50 ){
78403 zSep = "";
78404 zSep2 = ",";
78405 zEnd = ")";
78406 }else{
78407 zSep = "\n ";
78408 zSep2 = ",\n ";
78409 zEnd = "\n)";
78411 n += 35 + 6*p->nCol;
78412 zStmt = sqlite3DbMallocRaw(0, n);
78413 if( zStmt==0 ){
78414 db->mallocFailed = 1;
78415 return 0;
78417 sqlite3_snprintf(n, zStmt, "CREATE TABLE ");
78418 k = sqlite3Strlen30(zStmt);
78419 identPut(zStmt, &k, p->zName);
78420 zStmt[k++] = '(';
78421 for(pCol=p->aCol, i=0; i<p->nCol; i++, pCol++){
78422 static const char * const azType[] = {
78423 /* SQLITE_AFF_TEXT */ " TEXT",
78424 /* SQLITE_AFF_NONE */ "",
78425 /* SQLITE_AFF_NUMERIC */ " NUM",
78426 /* SQLITE_AFF_INTEGER */ " INT",
78427 /* SQLITE_AFF_REAL */ " REAL"
78429 int len;
78430 const char *zType;
78432 sqlite3_snprintf(n-k, &zStmt[k], zSep);
78433 k += sqlite3Strlen30(&zStmt[k]);
78434 zSep = zSep2;
78435 identPut(zStmt, &k, pCol->zName);
78436 assert( pCol->affinity-SQLITE_AFF_TEXT >= 0 );
78437 assert( pCol->affinity-SQLITE_AFF_TEXT < ArraySize(azType) );
78438 testcase( pCol->affinity==SQLITE_AFF_TEXT );
78439 testcase( pCol->affinity==SQLITE_AFF_NONE );
78440 testcase( pCol->affinity==SQLITE_AFF_NUMERIC );
78441 testcase( pCol->affinity==SQLITE_AFF_INTEGER );
78442 testcase( pCol->affinity==SQLITE_AFF_REAL );
78444 zType = azType[pCol->affinity - SQLITE_AFF_TEXT];
78445 len = sqlite3Strlen30(zType);
78446 assert( pCol->affinity==SQLITE_AFF_NONE
78447 || pCol->affinity==sqlite3AffinityType(zType) );
78448 memcpy(&zStmt[k], zType, len);
78449 k += len;
78450 assert( k<=n );
78452 sqlite3_snprintf(n-k, &zStmt[k], "%s", zEnd);
78453 return zStmt;
78457 ** This routine is called to report the final ")" that terminates
78458 ** a CREATE TABLE statement.
78460 ** The table structure that other action routines have been building
78461 ** is added to the internal hash tables, assuming no errors have
78462 ** occurred.
78464 ** An entry for the table is made in the master table on disk, unless
78465 ** this is a temporary table or db->init.busy==1. When db->init.busy==1
78466 ** it means we are reading the sqlite_master table because we just
78467 ** connected to the database or because the sqlite_master table has
78468 ** recently changed, so the entry for this table already exists in
78469 ** the sqlite_master table. We do not want to create it again.
78471 ** If the pSelect argument is not NULL, it means that this routine
78472 ** was called to create a table generated from a
78473 ** "CREATE TABLE ... AS SELECT ..." statement. The column names of
78474 ** the new table will match the result set of the SELECT.
78476 SQLITE_PRIVATE void sqlite3EndTable(
78477 Parse *pParse, /* Parse context */
78478 Token *pCons, /* The ',' token after the last column defn. */
78479 Token *pEnd, /* The final ')' token in the CREATE TABLE */
78480 Select *pSelect /* Select from a "CREATE ... AS SELECT" */
78482 Table *p;
78483 sqlite3 *db = pParse->db;
78484 int iDb;
78486 if( (pEnd==0 && pSelect==0) || db->mallocFailed ){
78487 return;
78489 p = pParse->pNewTable;
78490 if( p==0 ) return;
78492 assert( !db->init.busy || !pSelect );
78494 iDb = sqlite3SchemaToIndex(db, p->pSchema);
78496 #ifndef SQLITE_OMIT_CHECK
78497 /* Resolve names in all CHECK constraint expressions.
78499 if( p->pCheck ){
78500 SrcList sSrc; /* Fake SrcList for pParse->pNewTable */
78501 NameContext sNC; /* Name context for pParse->pNewTable */
78503 memset(&sNC, 0, sizeof(sNC));
78504 memset(&sSrc, 0, sizeof(sSrc));
78505 sSrc.nSrc = 1;
78506 sSrc.a[0].zName = p->zName;
78507 sSrc.a[0].pTab = p;
78508 sSrc.a[0].iCursor = -1;
78509 sNC.pParse = pParse;
78510 sNC.pSrcList = &sSrc;
78511 sNC.isCheck = 1;
78512 if( sqlite3ResolveExprNames(&sNC, p->pCheck) ){
78513 return;
78516 #endif /* !defined(SQLITE_OMIT_CHECK) */
78518 /* If the db->init.busy is 1 it means we are reading the SQL off the
78519 ** "sqlite_master" or "sqlite_temp_master" table on the disk.
78520 ** So do not write to the disk again. Extract the root page number
78521 ** for the table from the db->init.newTnum field. (The page number
78522 ** should have been put there by the sqliteOpenCb routine.)
78524 if( db->init.busy ){
78525 p->tnum = db->init.newTnum;
78528 /* If not initializing, then create a record for the new table
78529 ** in the SQLITE_MASTER table of the database.
78531 ** If this is a TEMPORARY table, write the entry into the auxiliary
78532 ** file instead of into the main database file.
78534 if( !db->init.busy ){
78535 int n;
78536 Vdbe *v;
78537 char *zType; /* "view" or "table" */
78538 char *zType2; /* "VIEW" or "TABLE" */
78539 char *zStmt; /* Text of the CREATE TABLE or CREATE VIEW statement */
78541 v = sqlite3GetVdbe(pParse);
78542 if( NEVER(v==0) ) return;
78544 sqlite3VdbeAddOp1(v, OP_Close, 0);
78547 ** Initialize zType for the new view or table.
78549 if( p->pSelect==0 ){
78550 /* A regular table */
78551 zType = "table";
78552 zType2 = "TABLE";
78553 #ifndef SQLITE_OMIT_VIEW
78554 }else{
78555 /* A view */
78556 zType = "view";
78557 zType2 = "VIEW";
78558 #endif
78561 /* If this is a CREATE TABLE xx AS SELECT ..., execute the SELECT
78562 ** statement to populate the new table. The root-page number for the
78563 ** new table is in register pParse->regRoot.
78565 ** Once the SELECT has been coded by sqlite3Select(), it is in a
78566 ** suitable state to query for the column names and types to be used
78567 ** by the new table.
78569 ** A shared-cache write-lock is not required to write to the new table,
78570 ** as a schema-lock must have already been obtained to create it. Since
78571 ** a schema-lock excludes all other database users, the write-lock would
78572 ** be redundant.
78574 if( pSelect ){
78575 SelectDest dest;
78576 Table *pSelTab;
78578 assert(pParse->nTab==1);
78579 sqlite3VdbeAddOp3(v, OP_OpenWrite, 1, pParse->regRoot, iDb);
78580 sqlite3VdbeChangeP5(v, 1);
78581 pParse->nTab = 2;
78582 sqlite3SelectDestInit(&dest, SRT_Table, 1);
78583 sqlite3Select(pParse, pSelect, &dest);
78584 sqlite3VdbeAddOp1(v, OP_Close, 1);
78585 if( pParse->nErr==0 ){
78586 pSelTab = sqlite3ResultSetOfSelect(pParse, pSelect);
78587 if( pSelTab==0 ) return;
78588 assert( p->aCol==0 );
78589 p->nCol = pSelTab->nCol;
78590 p->aCol = pSelTab->aCol;
78591 pSelTab->nCol = 0;
78592 pSelTab->aCol = 0;
78593 sqlite3DeleteTable(db, pSelTab);
78597 /* Compute the complete text of the CREATE statement */
78598 if( pSelect ){
78599 zStmt = createTableStmt(db, p);
78600 }else{
78601 n = (int)(pEnd->z - pParse->sNameToken.z) + 1;
78602 zStmt = sqlite3MPrintf(db,
78603 "CREATE %s %.*s", zType2, n, pParse->sNameToken.z
78607 /* A slot for the record has already been allocated in the
78608 ** SQLITE_MASTER table. We just need to update that slot with all
78609 ** the information we've collected.
78611 sqlite3NestedParse(pParse,
78612 "UPDATE %Q.%s "
78613 "SET type='%s', name=%Q, tbl_name=%Q, rootpage=#%d, sql=%Q "
78614 "WHERE rowid=#%d",
78615 db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
78616 zType,
78617 p->zName,
78618 p->zName,
78619 pParse->regRoot,
78620 zStmt,
78621 pParse->regRowid
78623 sqlite3DbFree(db, zStmt);
78624 sqlite3ChangeCookie(pParse, iDb);
78626 #ifndef SQLITE_OMIT_AUTOINCREMENT
78627 /* Check to see if we need to create an sqlite_sequence table for
78628 ** keeping track of autoincrement keys.
78630 if( p->tabFlags & TF_Autoincrement ){
78631 Db *pDb = &db->aDb[iDb];
78632 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
78633 if( pDb->pSchema->pSeqTab==0 ){
78634 sqlite3NestedParse(pParse,
78635 "CREATE TABLE %Q.sqlite_sequence(name,seq)",
78636 pDb->zName
78640 #endif
78642 /* Reparse everything to update our internal data structures */
78643 sqlite3VdbeAddOp4(v, OP_ParseSchema, iDb, 0, 0,
78644 sqlite3MPrintf(db, "tbl_name='%q'",p->zName), P4_DYNAMIC);
78648 /* Add the table to the in-memory representation of the database.
78650 if( db->init.busy ){
78651 Table *pOld;
78652 Schema *pSchema = p->pSchema;
78653 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
78654 pOld = sqlite3HashInsert(&pSchema->tblHash, p->zName,
78655 sqlite3Strlen30(p->zName),p);
78656 if( pOld ){
78657 assert( p==pOld ); /* Malloc must have failed inside HashInsert() */
78658 db->mallocFailed = 1;
78659 return;
78661 pParse->pNewTable = 0;
78662 db->nTable++;
78663 db->flags |= SQLITE_InternChanges;
78665 #ifndef SQLITE_OMIT_ALTERTABLE
78666 if( !p->pSelect ){
78667 const char *zName = (const char *)pParse->sNameToken.z;
78668 int nName;
78669 assert( !pSelect && pCons && pEnd );
78670 if( pCons->z==0 ){
78671 pCons = pEnd;
78673 nName = (int)((const char *)pCons->z - zName);
78674 p->addColOffset = 13 + sqlite3Utf8CharLen(zName, nName);
78676 #endif
78680 #ifndef SQLITE_OMIT_VIEW
78682 ** The parser calls this routine in order to create a new VIEW
78684 SQLITE_PRIVATE void sqlite3CreateView(
78685 Parse *pParse, /* The parsing context */
78686 Token *pBegin, /* The CREATE token that begins the statement */
78687 Token *pName1, /* The token that holds the name of the view */
78688 Token *pName2, /* The token that holds the name of the view */
78689 Select *pSelect, /* A SELECT statement that will become the new view */
78690 int isTemp, /* TRUE for a TEMPORARY view */
78691 int noErr /* Suppress error messages if VIEW already exists */
78693 Table *p;
78694 int n;
78695 const char *z;
78696 Token sEnd;
78697 DbFixer sFix;
78698 Token *pName;
78699 int iDb;
78700 sqlite3 *db = pParse->db;
78702 if( pParse->nVar>0 ){
78703 sqlite3ErrorMsg(pParse, "parameters are not allowed in views");
78704 sqlite3SelectDelete(db, pSelect);
78705 return;
78707 sqlite3StartTable(pParse, pName1, pName2, isTemp, 1, 0, noErr);
78708 p = pParse->pNewTable;
78709 if( p==0 || pParse->nErr ){
78710 sqlite3SelectDelete(db, pSelect);
78711 return;
78713 sqlite3TwoPartName(pParse, pName1, pName2, &pName);
78714 iDb = sqlite3SchemaToIndex(db, p->pSchema);
78715 if( sqlite3FixInit(&sFix, pParse, iDb, "view", pName)
78716 && sqlite3FixSelect(&sFix, pSelect)
78718 sqlite3SelectDelete(db, pSelect);
78719 return;
78722 /* Make a copy of the entire SELECT statement that defines the view.
78723 ** This will force all the Expr.token.z values to be dynamically
78724 ** allocated rather than point to the input string - which means that
78725 ** they will persist after the current sqlite3_exec() call returns.
78727 p->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
78728 sqlite3SelectDelete(db, pSelect);
78729 if( db->mallocFailed ){
78730 return;
78732 if( !db->init.busy ){
78733 sqlite3ViewGetColumnNames(pParse, p);
78736 /* Locate the end of the CREATE VIEW statement. Make sEnd point to
78737 ** the end.
78739 sEnd = pParse->sLastToken;
78740 if( ALWAYS(sEnd.z[0]!=0) && sEnd.z[0]!=';' ){
78741 sEnd.z += sEnd.n;
78743 sEnd.n = 0;
78744 n = (int)(sEnd.z - pBegin->z);
78745 z = pBegin->z;
78746 while( ALWAYS(n>0) && sqlite3Isspace(z[n-1]) ){ n--; }
78747 sEnd.z = &z[n-1];
78748 sEnd.n = 1;
78750 /* Use sqlite3EndTable() to add the view to the SQLITE_MASTER table */
78751 sqlite3EndTable(pParse, 0, &sEnd, 0);
78752 return;
78754 #endif /* SQLITE_OMIT_VIEW */
78756 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
78758 ** The Table structure pTable is really a VIEW. Fill in the names of
78759 ** the columns of the view in the pTable structure. Return the number
78760 ** of errors. If an error is seen leave an error message in pParse->zErrMsg.
78762 SQLITE_PRIVATE int sqlite3ViewGetColumnNames(Parse *pParse, Table *pTable){
78763 Table *pSelTab; /* A fake table from which we get the result set */
78764 Select *pSel; /* Copy of the SELECT that implements the view */
78765 int nErr = 0; /* Number of errors encountered */
78766 int n; /* Temporarily holds the number of cursors assigned */
78767 sqlite3 *db = pParse->db; /* Database connection for malloc errors */
78768 int (*xAuth)(void*,int,const char*,const char*,const char*,const char*);
78770 assert( pTable );
78772 #ifndef SQLITE_OMIT_VIRTUALTABLE
78773 if( sqlite3VtabCallConnect(pParse, pTable) ){
78774 return SQLITE_ERROR;
78776 if( IsVirtual(pTable) ) return 0;
78777 #endif
78779 #ifndef SQLITE_OMIT_VIEW
78780 /* A positive nCol means the columns names for this view are
78781 ** already known.
78783 if( pTable->nCol>0 ) return 0;
78785 /* A negative nCol is a special marker meaning that we are currently
78786 ** trying to compute the column names. If we enter this routine with
78787 ** a negative nCol, it means two or more views form a loop, like this:
78789 ** CREATE VIEW one AS SELECT * FROM two;
78790 ** CREATE VIEW two AS SELECT * FROM one;
78792 ** Actually, the error above is now caught prior to reaching this point.
78793 ** But the following test is still important as it does come up
78794 ** in the following:
78796 ** CREATE TABLE main.ex1(a);
78797 ** CREATE TEMP VIEW ex1 AS SELECT a FROM ex1;
78798 ** SELECT * FROM temp.ex1;
78800 if( pTable->nCol<0 ){
78801 sqlite3ErrorMsg(pParse, "view %s is circularly defined", pTable->zName);
78802 return 1;
78804 assert( pTable->nCol>=0 );
78806 /* If we get this far, it means we need to compute the table names.
78807 ** Note that the call to sqlite3ResultSetOfSelect() will expand any
78808 ** "*" elements in the results set of the view and will assign cursors
78809 ** to the elements of the FROM clause. But we do not want these changes
78810 ** to be permanent. So the computation is done on a copy of the SELECT
78811 ** statement that defines the view.
78813 assert( pTable->pSelect );
78814 pSel = sqlite3SelectDup(db, pTable->pSelect, 0);
78815 if( pSel ){
78816 u8 enableLookaside = db->lookaside.bEnabled;
78817 n = pParse->nTab;
78818 sqlite3SrcListAssignCursors(pParse, pSel->pSrc);
78819 pTable->nCol = -1;
78820 db->lookaside.bEnabled = 0;
78821 #ifndef SQLITE_OMIT_AUTHORIZATION
78822 xAuth = db->xAuth;
78823 db->xAuth = 0;
78824 pSelTab = sqlite3ResultSetOfSelect(pParse, pSel);
78825 db->xAuth = xAuth;
78826 #else
78827 pSelTab = sqlite3ResultSetOfSelect(pParse, pSel);
78828 #endif
78829 db->lookaside.bEnabled = enableLookaside;
78830 pParse->nTab = n;
78831 if( pSelTab ){
78832 assert( pTable->aCol==0 );
78833 pTable->nCol = pSelTab->nCol;
78834 pTable->aCol = pSelTab->aCol;
78835 pSelTab->nCol = 0;
78836 pSelTab->aCol = 0;
78837 sqlite3DeleteTable(db, pSelTab);
78838 assert( sqlite3SchemaMutexHeld(db, 0, pTable->pSchema) );
78839 pTable->pSchema->flags |= DB_UnresetViews;
78840 }else{
78841 pTable->nCol = 0;
78842 nErr++;
78844 sqlite3SelectDelete(db, pSel);
78845 } else {
78846 nErr++;
78848 #endif /* SQLITE_OMIT_VIEW */
78849 return nErr;
78851 #endif /* !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE) */
78853 #ifndef SQLITE_OMIT_VIEW
78855 ** Clear the column names from every VIEW in database idx.
78857 static void sqliteViewResetAll(sqlite3 *db, int idx){
78858 HashElem *i;
78859 assert( sqlite3SchemaMutexHeld(db, idx, 0) );
78860 if( !DbHasProperty(db, idx, DB_UnresetViews) ) return;
78861 for(i=sqliteHashFirst(&db->aDb[idx].pSchema->tblHash); i;i=sqliteHashNext(i)){
78862 Table *pTab = sqliteHashData(i);
78863 if( pTab->pSelect ){
78864 sqliteDeleteColumnNames(db, pTab);
78865 pTab->aCol = 0;
78866 pTab->nCol = 0;
78869 DbClearProperty(db, idx, DB_UnresetViews);
78871 #else
78872 # define sqliteViewResetAll(A,B)
78873 #endif /* SQLITE_OMIT_VIEW */
78876 ** This function is called by the VDBE to adjust the internal schema
78877 ** used by SQLite when the btree layer moves a table root page. The
78878 ** root-page of a table or index in database iDb has changed from iFrom
78879 ** to iTo.
78881 ** Ticket #1728: The symbol table might still contain information
78882 ** on tables and/or indices that are the process of being deleted.
78883 ** If you are unlucky, one of those deleted indices or tables might
78884 ** have the same rootpage number as the real table or index that is
78885 ** being moved. So we cannot stop searching after the first match
78886 ** because the first match might be for one of the deleted indices
78887 ** or tables and not the table/index that is actually being moved.
78888 ** We must continue looping until all tables and indices with
78889 ** rootpage==iFrom have been converted to have a rootpage of iTo
78890 ** in order to be certain that we got the right one.
78892 #ifndef SQLITE_OMIT_AUTOVACUUM
78893 SQLITE_PRIVATE void sqlite3RootPageMoved(sqlite3 *db, int iDb, int iFrom, int iTo){
78894 HashElem *pElem;
78895 Hash *pHash;
78896 Db *pDb;
78898 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
78899 pDb = &db->aDb[iDb];
78900 pHash = &pDb->pSchema->tblHash;
78901 for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){
78902 Table *pTab = sqliteHashData(pElem);
78903 if( pTab->tnum==iFrom ){
78904 pTab->tnum = iTo;
78907 pHash = &pDb->pSchema->idxHash;
78908 for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){
78909 Index *pIdx = sqliteHashData(pElem);
78910 if( pIdx->tnum==iFrom ){
78911 pIdx->tnum = iTo;
78915 #endif
78918 ** Write code to erase the table with root-page iTable from database iDb.
78919 ** Also write code to modify the sqlite_master table and internal schema
78920 ** if a root-page of another table is moved by the btree-layer whilst
78921 ** erasing iTable (this can happen with an auto-vacuum database).
78923 static void destroyRootPage(Parse *pParse, int iTable, int iDb){
78924 Vdbe *v = sqlite3GetVdbe(pParse);
78925 int r1 = sqlite3GetTempReg(pParse);
78926 sqlite3VdbeAddOp3(v, OP_Destroy, iTable, r1, iDb);
78927 sqlite3MayAbort(pParse);
78928 #ifndef SQLITE_OMIT_AUTOVACUUM
78929 /* OP_Destroy stores an in integer r1. If this integer
78930 ** is non-zero, then it is the root page number of a table moved to
78931 ** location iTable. The following code modifies the sqlite_master table to
78932 ** reflect this.
78934 ** The "#NNN" in the SQL is a special constant that means whatever value
78935 ** is in register NNN. See grammar rules associated with the TK_REGISTER
78936 ** token for additional information.
78938 sqlite3NestedParse(pParse,
78939 "UPDATE %Q.%s SET rootpage=%d WHERE #%d AND rootpage=#%d",
78940 pParse->db->aDb[iDb].zName, SCHEMA_TABLE(iDb), iTable, r1, r1);
78941 #endif
78942 sqlite3ReleaseTempReg(pParse, r1);
78946 ** Write VDBE code to erase table pTab and all associated indices on disk.
78947 ** Code to update the sqlite_master tables and internal schema definitions
78948 ** in case a root-page belonging to another table is moved by the btree layer
78949 ** is also added (this can happen with an auto-vacuum database).
78951 static void destroyTable(Parse *pParse, Table *pTab){
78952 #ifdef SQLITE_OMIT_AUTOVACUUM
78953 Index *pIdx;
78954 int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
78955 destroyRootPage(pParse, pTab->tnum, iDb);
78956 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
78957 destroyRootPage(pParse, pIdx->tnum, iDb);
78959 #else
78960 /* If the database may be auto-vacuum capable (if SQLITE_OMIT_AUTOVACUUM
78961 ** is not defined), then it is important to call OP_Destroy on the
78962 ** table and index root-pages in order, starting with the numerically
78963 ** largest root-page number. This guarantees that none of the root-pages
78964 ** to be destroyed is relocated by an earlier OP_Destroy. i.e. if the
78965 ** following were coded:
78967 ** OP_Destroy 4 0
78968 ** ...
78969 ** OP_Destroy 5 0
78971 ** and root page 5 happened to be the largest root-page number in the
78972 ** database, then root page 5 would be moved to page 4 by the
78973 ** "OP_Destroy 4 0" opcode. The subsequent "OP_Destroy 5 0" would hit
78974 ** a free-list page.
78976 int iTab = pTab->tnum;
78977 int iDestroyed = 0;
78979 while( 1 ){
78980 Index *pIdx;
78981 int iLargest = 0;
78983 if( iDestroyed==0 || iTab<iDestroyed ){
78984 iLargest = iTab;
78986 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
78987 int iIdx = pIdx->tnum;
78988 assert( pIdx->pSchema==pTab->pSchema );
78989 if( (iDestroyed==0 || (iIdx<iDestroyed)) && iIdx>iLargest ){
78990 iLargest = iIdx;
78993 if( iLargest==0 ){
78994 return;
78995 }else{
78996 int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
78997 destroyRootPage(pParse, iLargest, iDb);
78998 iDestroyed = iLargest;
79001 #endif
79005 ** This routine is called to do the work of a DROP TABLE statement.
79006 ** pName is the name of the table to be dropped.
79008 SQLITE_PRIVATE void sqlite3DropTable(Parse *pParse, SrcList *pName, int isView, int noErr){
79009 Table *pTab;
79010 Vdbe *v;
79011 sqlite3 *db = pParse->db;
79012 int iDb;
79014 if( db->mallocFailed ){
79015 goto exit_drop_table;
79017 assert( pParse->nErr==0 );
79018 assert( pName->nSrc==1 );
79019 if( noErr ) db->suppressErr++;
79020 pTab = sqlite3LocateTable(pParse, isView,
79021 pName->a[0].zName, pName->a[0].zDatabase);
79022 if( noErr ) db->suppressErr--;
79024 if( pTab==0 ){
79025 if( noErr ) sqlite3CodeVerifyNamedSchema(pParse, pName->a[0].zDatabase);
79026 goto exit_drop_table;
79028 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
79029 assert( iDb>=0 && iDb<db->nDb );
79031 /* If pTab is a virtual table, call ViewGetColumnNames() to ensure
79032 ** it is initialized.
79034 if( IsVirtual(pTab) && sqlite3ViewGetColumnNames(pParse, pTab) ){
79035 goto exit_drop_table;
79037 #ifndef SQLITE_OMIT_AUTHORIZATION
79039 int code;
79040 const char *zTab = SCHEMA_TABLE(iDb);
79041 const char *zDb = db->aDb[iDb].zName;
79042 const char *zArg2 = 0;
79043 if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb)){
79044 goto exit_drop_table;
79046 if( isView ){
79047 if( !OMIT_TEMPDB && iDb==1 ){
79048 code = SQLITE_DROP_TEMP_VIEW;
79049 }else{
79050 code = SQLITE_DROP_VIEW;
79052 #ifndef SQLITE_OMIT_VIRTUALTABLE
79053 }else if( IsVirtual(pTab) ){
79054 code = SQLITE_DROP_VTABLE;
79055 zArg2 = sqlite3GetVTable(db, pTab)->pMod->zName;
79056 #endif
79057 }else{
79058 if( !OMIT_TEMPDB && iDb==1 ){
79059 code = SQLITE_DROP_TEMP_TABLE;
79060 }else{
79061 code = SQLITE_DROP_TABLE;
79064 if( sqlite3AuthCheck(pParse, code, pTab->zName, zArg2, zDb) ){
79065 goto exit_drop_table;
79067 if( sqlite3AuthCheck(pParse, SQLITE_DELETE, pTab->zName, 0, zDb) ){
79068 goto exit_drop_table;
79071 #endif
79072 if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0 ){
79073 sqlite3ErrorMsg(pParse, "table %s may not be dropped", pTab->zName);
79074 goto exit_drop_table;
79077 #ifndef SQLITE_OMIT_VIEW
79078 /* Ensure DROP TABLE is not used on a view, and DROP VIEW is not used
79079 ** on a table.
79081 if( isView && pTab->pSelect==0 ){
79082 sqlite3ErrorMsg(pParse, "use DROP TABLE to delete table %s", pTab->zName);
79083 goto exit_drop_table;
79085 if( !isView && pTab->pSelect ){
79086 sqlite3ErrorMsg(pParse, "use DROP VIEW to delete view %s", pTab->zName);
79087 goto exit_drop_table;
79089 #endif
79091 /* Generate code to remove the table from the master table
79092 ** on disk.
79094 v = sqlite3GetVdbe(pParse);
79095 if( v ){
79096 Trigger *pTrigger;
79097 Db *pDb = &db->aDb[iDb];
79098 sqlite3BeginWriteOperation(pParse, 1, iDb);
79100 #ifndef SQLITE_OMIT_VIRTUALTABLE
79101 if( IsVirtual(pTab) ){
79102 sqlite3VdbeAddOp0(v, OP_VBegin);
79104 #endif
79105 sqlite3FkDropTable(pParse, pName, pTab);
79107 /* Drop all triggers associated with the table being dropped. Code
79108 ** is generated to remove entries from sqlite_master and/or
79109 ** sqlite_temp_master if required.
79111 pTrigger = sqlite3TriggerList(pParse, pTab);
79112 while( pTrigger ){
79113 assert( pTrigger->pSchema==pTab->pSchema ||
79114 pTrigger->pSchema==db->aDb[1].pSchema );
79115 sqlite3DropTriggerPtr(pParse, pTrigger);
79116 pTrigger = pTrigger->pNext;
79119 #ifndef SQLITE_OMIT_AUTOINCREMENT
79120 /* Remove any entries of the sqlite_sequence table associated with
79121 ** the table being dropped. This is done before the table is dropped
79122 ** at the btree level, in case the sqlite_sequence table needs to
79123 ** move as a result of the drop (can happen in auto-vacuum mode).
79125 if( pTab->tabFlags & TF_Autoincrement ){
79126 sqlite3NestedParse(pParse,
79127 "DELETE FROM %s.sqlite_sequence WHERE name=%Q",
79128 pDb->zName, pTab->zName
79131 #endif
79133 /* Drop all SQLITE_MASTER table and index entries that refer to the
79134 ** table. The program name loops through the master table and deletes
79135 ** every row that refers to a table of the same name as the one being
79136 ** dropped. Triggers are handled seperately because a trigger can be
79137 ** created in the temp database that refers to a table in another
79138 ** database.
79140 sqlite3NestedParse(pParse,
79141 "DELETE FROM %Q.%s WHERE tbl_name=%Q and type!='trigger'",
79142 pDb->zName, SCHEMA_TABLE(iDb), pTab->zName);
79144 /* Drop any statistics from the sqlite_stat1 table, if it exists */
79145 if( sqlite3FindTable(db, "sqlite_stat1", db->aDb[iDb].zName) ){
79146 sqlite3NestedParse(pParse,
79147 "DELETE FROM %Q.sqlite_stat1 WHERE tbl=%Q", pDb->zName, pTab->zName
79151 if( !isView && !IsVirtual(pTab) ){
79152 destroyTable(pParse, pTab);
79155 /* Remove the table entry from SQLite's internal schema and modify
79156 ** the schema cookie.
79158 if( IsVirtual(pTab) ){
79159 sqlite3VdbeAddOp4(v, OP_VDestroy, iDb, 0, 0, pTab->zName, 0);
79161 sqlite3VdbeAddOp4(v, OP_DropTable, iDb, 0, 0, pTab->zName, 0);
79162 sqlite3ChangeCookie(pParse, iDb);
79164 sqliteViewResetAll(db, iDb);
79166 exit_drop_table:
79167 sqlite3SrcListDelete(db, pName);
79171 ** This routine is called to create a new foreign key on the table
79172 ** currently under construction. pFromCol determines which columns
79173 ** in the current table point to the foreign key. If pFromCol==0 then
79174 ** connect the key to the last column inserted. pTo is the name of
79175 ** the table referred to. pToCol is a list of tables in the other
79176 ** pTo table that the foreign key points to. flags contains all
79177 ** information about the conflict resolution algorithms specified
79178 ** in the ON DELETE, ON UPDATE and ON INSERT clauses.
79180 ** An FKey structure is created and added to the table currently
79181 ** under construction in the pParse->pNewTable field.
79183 ** The foreign key is set for IMMEDIATE processing. A subsequent call
79184 ** to sqlite3DeferForeignKey() might change this to DEFERRED.
79186 SQLITE_PRIVATE void sqlite3CreateForeignKey(
79187 Parse *pParse, /* Parsing context */
79188 ExprList *pFromCol, /* Columns in this table that point to other table */
79189 Token *pTo, /* Name of the other table */
79190 ExprList *pToCol, /* Columns in the other table */
79191 int flags /* Conflict resolution algorithms. */
79193 sqlite3 *db = pParse->db;
79194 #ifndef SQLITE_OMIT_FOREIGN_KEY
79195 FKey *pFKey = 0;
79196 FKey *pNextTo;
79197 Table *p = pParse->pNewTable;
79198 int nByte;
79199 int i;
79200 int nCol;
79201 char *z;
79203 assert( pTo!=0 );
79204 if( p==0 || IN_DECLARE_VTAB ) goto fk_end;
79205 if( pFromCol==0 ){
79206 int iCol = p->nCol-1;
79207 if( NEVER(iCol<0) ) goto fk_end;
79208 if( pToCol && pToCol->nExpr!=1 ){
79209 sqlite3ErrorMsg(pParse, "foreign key on %s"
79210 " should reference only one column of table %T",
79211 p->aCol[iCol].zName, pTo);
79212 goto fk_end;
79214 nCol = 1;
79215 }else if( pToCol && pToCol->nExpr!=pFromCol->nExpr ){
79216 sqlite3ErrorMsg(pParse,
79217 "number of columns in foreign key does not match the number of "
79218 "columns in the referenced table");
79219 goto fk_end;
79220 }else{
79221 nCol = pFromCol->nExpr;
79223 nByte = sizeof(*pFKey) + (nCol-1)*sizeof(pFKey->aCol[0]) + pTo->n + 1;
79224 if( pToCol ){
79225 for(i=0; i<pToCol->nExpr; i++){
79226 nByte += sqlite3Strlen30(pToCol->a[i].zName) + 1;
79229 pFKey = sqlite3DbMallocZero(db, nByte );
79230 if( pFKey==0 ){
79231 goto fk_end;
79233 pFKey->pFrom = p;
79234 pFKey->pNextFrom = p->pFKey;
79235 z = (char*)&pFKey->aCol[nCol];
79236 pFKey->zTo = z;
79237 memcpy(z, pTo->z, pTo->n);
79238 z[pTo->n] = 0;
79239 sqlite3Dequote(z);
79240 z += pTo->n+1;
79241 pFKey->nCol = nCol;
79242 if( pFromCol==0 ){
79243 pFKey->aCol[0].iFrom = p->nCol-1;
79244 }else{
79245 for(i=0; i<nCol; i++){
79246 int j;
79247 for(j=0; j<p->nCol; j++){
79248 if( sqlite3StrICmp(p->aCol[j].zName, pFromCol->a[i].zName)==0 ){
79249 pFKey->aCol[i].iFrom = j;
79250 break;
79253 if( j>=p->nCol ){
79254 sqlite3ErrorMsg(pParse,
79255 "unknown column \"%s\" in foreign key definition",
79256 pFromCol->a[i].zName);
79257 goto fk_end;
79261 if( pToCol ){
79262 for(i=0; i<nCol; i++){
79263 int n = sqlite3Strlen30(pToCol->a[i].zName);
79264 pFKey->aCol[i].zCol = z;
79265 memcpy(z, pToCol->a[i].zName, n);
79266 z[n] = 0;
79267 z += n+1;
79270 pFKey->isDeferred = 0;
79271 pFKey->aAction[0] = (u8)(flags & 0xff); /* ON DELETE action */
79272 pFKey->aAction[1] = (u8)((flags >> 8 ) & 0xff); /* ON UPDATE action */
79274 assert( sqlite3SchemaMutexHeld(db, 0, p->pSchema) );
79275 pNextTo = (FKey *)sqlite3HashInsert(&p->pSchema->fkeyHash,
79276 pFKey->zTo, sqlite3Strlen30(pFKey->zTo), (void *)pFKey
79278 if( pNextTo==pFKey ){
79279 db->mallocFailed = 1;
79280 goto fk_end;
79282 if( pNextTo ){
79283 assert( pNextTo->pPrevTo==0 );
79284 pFKey->pNextTo = pNextTo;
79285 pNextTo->pPrevTo = pFKey;
79288 /* Link the foreign key to the table as the last step.
79290 p->pFKey = pFKey;
79291 pFKey = 0;
79293 fk_end:
79294 sqlite3DbFree(db, pFKey);
79295 #endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
79296 sqlite3ExprListDelete(db, pFromCol);
79297 sqlite3ExprListDelete(db, pToCol);
79301 ** This routine is called when an INITIALLY IMMEDIATE or INITIALLY DEFERRED
79302 ** clause is seen as part of a foreign key definition. The isDeferred
79303 ** parameter is 1 for INITIALLY DEFERRED and 0 for INITIALLY IMMEDIATE.
79304 ** The behavior of the most recently created foreign key is adjusted
79305 ** accordingly.
79307 SQLITE_PRIVATE void sqlite3DeferForeignKey(Parse *pParse, int isDeferred){
79308 #ifndef SQLITE_OMIT_FOREIGN_KEY
79309 Table *pTab;
79310 FKey *pFKey;
79311 if( (pTab = pParse->pNewTable)==0 || (pFKey = pTab->pFKey)==0 ) return;
79312 assert( isDeferred==0 || isDeferred==1 ); /* EV: R-30323-21917 */
79313 pFKey->isDeferred = (u8)isDeferred;
79314 #endif
79318 ** Generate code that will erase and refill index *pIdx. This is
79319 ** used to initialize a newly created index or to recompute the
79320 ** content of an index in response to a REINDEX command.
79322 ** if memRootPage is not negative, it means that the index is newly
79323 ** created. The register specified by memRootPage contains the
79324 ** root page number of the index. If memRootPage is negative, then
79325 ** the index already exists and must be cleared before being refilled and
79326 ** the root page number of the index is taken from pIndex->tnum.
79328 static void sqlite3RefillIndex(Parse *pParse, Index *pIndex, int memRootPage){
79329 Table *pTab = pIndex->pTable; /* The table that is indexed */
79330 int iTab = pParse->nTab++; /* Btree cursor used for pTab */
79331 int iIdx = pParse->nTab++; /* Btree cursor used for pIndex */
79332 int addr1; /* Address of top of loop */
79333 int tnum; /* Root page of index */
79334 Vdbe *v; /* Generate code into this virtual machine */
79335 KeyInfo *pKey; /* KeyInfo for index */
79336 int regIdxKey; /* Registers containing the index key */
79337 int regRecord; /* Register holding assemblied index record */
79338 sqlite3 *db = pParse->db; /* The database connection */
79339 int iDb = sqlite3SchemaToIndex(db, pIndex->pSchema);
79341 #ifndef SQLITE_OMIT_AUTHORIZATION
79342 if( sqlite3AuthCheck(pParse, SQLITE_REINDEX, pIndex->zName, 0,
79343 db->aDb[iDb].zName ) ){
79344 return;
79346 #endif
79348 /* Require a write-lock on the table to perform this operation */
79349 sqlite3TableLock(pParse, iDb, pTab->tnum, 1, pTab->zName);
79351 v = sqlite3GetVdbe(pParse);
79352 if( v==0 ) return;
79353 if( memRootPage>=0 ){
79354 tnum = memRootPage;
79355 }else{
79356 tnum = pIndex->tnum;
79357 sqlite3VdbeAddOp2(v, OP_Clear, tnum, iDb);
79359 pKey = sqlite3IndexKeyinfo(pParse, pIndex);
79360 sqlite3VdbeAddOp4(v, OP_OpenWrite, iIdx, tnum, iDb,
79361 (char *)pKey, P4_KEYINFO_HANDOFF);
79362 if( memRootPage>=0 ){
79363 sqlite3VdbeChangeP5(v, 1);
79365 sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead);
79366 addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iTab, 0);
79367 regRecord = sqlite3GetTempReg(pParse);
79368 regIdxKey = sqlite3GenerateIndexKey(pParse, pIndex, iTab, regRecord, 1);
79369 if( pIndex->onError!=OE_None ){
79370 const int regRowid = regIdxKey + pIndex->nColumn;
79371 const int j2 = sqlite3VdbeCurrentAddr(v) + 2;
79372 void * const pRegKey = SQLITE_INT_TO_PTR(regIdxKey);
79374 /* The registers accessed by the OP_IsUnique opcode were allocated
79375 ** using sqlite3GetTempRange() inside of the sqlite3GenerateIndexKey()
79376 ** call above. Just before that function was freed they were released
79377 ** (made available to the compiler for reuse) using
79378 ** sqlite3ReleaseTempRange(). So in some ways having the OP_IsUnique
79379 ** opcode use the values stored within seems dangerous. However, since
79380 ** we can be sure that no other temp registers have been allocated
79381 ** since sqlite3ReleaseTempRange() was called, it is safe to do so.
79383 sqlite3VdbeAddOp4(v, OP_IsUnique, iIdx, j2, regRowid, pRegKey, P4_INT32);
79384 sqlite3HaltConstraint(
79385 pParse, OE_Abort, "indexed columns are not unique", P4_STATIC);
79387 sqlite3VdbeAddOp2(v, OP_IdxInsert, iIdx, regRecord);
79388 sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
79389 sqlite3ReleaseTempReg(pParse, regRecord);
79390 sqlite3VdbeAddOp2(v, OP_Next, iTab, addr1+1);
79391 sqlite3VdbeJumpHere(v, addr1);
79392 sqlite3VdbeAddOp1(v, OP_Close, iTab);
79393 sqlite3VdbeAddOp1(v, OP_Close, iIdx);
79397 ** Create a new index for an SQL table. pName1.pName2 is the name of the index
79398 ** and pTblList is the name of the table that is to be indexed. Both will
79399 ** be NULL for a primary key or an index that is created to satisfy a
79400 ** UNIQUE constraint. If pTable and pIndex are NULL, use pParse->pNewTable
79401 ** as the table to be indexed. pParse->pNewTable is a table that is
79402 ** currently being constructed by a CREATE TABLE statement.
79404 ** pList is a list of columns to be indexed. pList will be NULL if this
79405 ** is a primary key or unique-constraint on the most recent column added
79406 ** to the table currently under construction.
79408 ** If the index is created successfully, return a pointer to the new Index
79409 ** structure. This is used by sqlite3AddPrimaryKey() to mark the index
79410 ** as the tables primary key (Index.autoIndex==2).
79412 SQLITE_PRIVATE Index *sqlite3CreateIndex(
79413 Parse *pParse, /* All information about this parse */
79414 Token *pName1, /* First part of index name. May be NULL */
79415 Token *pName2, /* Second part of index name. May be NULL */
79416 SrcList *pTblName, /* Table to index. Use pParse->pNewTable if 0 */
79417 ExprList *pList, /* A list of columns to be indexed */
79418 int onError, /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */
79419 Token *pStart, /* The CREATE token that begins this statement */
79420 Token *pEnd, /* The ")" that closes the CREATE INDEX statement */
79421 int sortOrder, /* Sort order of primary key when pList==NULL */
79422 int ifNotExist /* Omit error if index already exists */
79424 Index *pRet = 0; /* Pointer to return */
79425 Table *pTab = 0; /* Table to be indexed */
79426 Index *pIndex = 0; /* The index to be created */
79427 char *zName = 0; /* Name of the index */
79428 int nName; /* Number of characters in zName */
79429 int i, j;
79430 Token nullId; /* Fake token for an empty ID list */
79431 DbFixer sFix; /* For assigning database names to pTable */
79432 int sortOrderMask; /* 1 to honor DESC in index. 0 to ignore. */
79433 sqlite3 *db = pParse->db;
79434 Db *pDb; /* The specific table containing the indexed database */
79435 int iDb; /* Index of the database that is being written */
79436 Token *pName = 0; /* Unqualified name of the index to create */
79437 struct ExprList_item *pListItem; /* For looping over pList */
79438 int nCol;
79439 int nExtra = 0;
79440 char *zExtra;
79442 assert( pStart==0 || pEnd!=0 ); /* pEnd must be non-NULL if pStart is */
79443 assert( pParse->nErr==0 ); /* Never called with prior errors */
79444 if( db->mallocFailed || IN_DECLARE_VTAB ){
79445 goto exit_create_index;
79447 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
79448 goto exit_create_index;
79452 ** Find the table that is to be indexed. Return early if not found.
79454 if( pTblName!=0 ){
79456 /* Use the two-part index name to determine the database
79457 ** to search for the table. 'Fix' the table name to this db
79458 ** before looking up the table.
79460 assert( pName1 && pName2 );
79461 iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
79462 if( iDb<0 ) goto exit_create_index;
79464 #ifndef SQLITE_OMIT_TEMPDB
79465 /* If the index name was unqualified, check if the the table
79466 ** is a temp table. If so, set the database to 1. Do not do this
79467 ** if initialising a database schema.
79469 if( !db->init.busy ){
79470 pTab = sqlite3SrcListLookup(pParse, pTblName);
79471 if( pName2->n==0 && pTab && pTab->pSchema==db->aDb[1].pSchema ){
79472 iDb = 1;
79475 #endif
79477 if( sqlite3FixInit(&sFix, pParse, iDb, "index", pName) &&
79478 sqlite3FixSrcList(&sFix, pTblName)
79480 /* Because the parser constructs pTblName from a single identifier,
79481 ** sqlite3FixSrcList can never fail. */
79482 assert(0);
79484 pTab = sqlite3LocateTable(pParse, 0, pTblName->a[0].zName,
79485 pTblName->a[0].zDatabase);
79486 if( !pTab || db->mallocFailed ) goto exit_create_index;
79487 assert( db->aDb[iDb].pSchema==pTab->pSchema );
79488 }else{
79489 assert( pName==0 );
79490 pTab = pParse->pNewTable;
79491 if( !pTab ) goto exit_create_index;
79492 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
79494 pDb = &db->aDb[iDb];
79496 assert( pTab!=0 );
79497 assert( pParse->nErr==0 );
79498 if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0
79499 && sqlite3StrNICmp(&pTab->zName[7],"altertab_",9)!=0 ){
79500 sqlite3ErrorMsg(pParse, "table %s may not be indexed", pTab->zName);
79501 goto exit_create_index;
79503 #ifndef SQLITE_OMIT_VIEW
79504 if( pTab->pSelect ){
79505 sqlite3ErrorMsg(pParse, "views may not be indexed");
79506 goto exit_create_index;
79508 #endif
79509 #ifndef SQLITE_OMIT_VIRTUALTABLE
79510 if( IsVirtual(pTab) ){
79511 sqlite3ErrorMsg(pParse, "virtual tables may not be indexed");
79512 goto exit_create_index;
79514 #endif
79517 ** Find the name of the index. Make sure there is not already another
79518 ** index or table with the same name.
79520 ** Exception: If we are reading the names of permanent indices from the
79521 ** sqlite_master table (because some other process changed the schema) and
79522 ** one of the index names collides with the name of a temporary table or
79523 ** index, then we will continue to process this index.
79525 ** If pName==0 it means that we are
79526 ** dealing with a primary key or UNIQUE constraint. We have to invent our
79527 ** own name.
79529 if( pName ){
79530 zName = sqlite3NameFromToken(db, pName);
79531 if( zName==0 ) goto exit_create_index;
79532 if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
79533 goto exit_create_index;
79535 if( !db->init.busy ){
79536 if( sqlite3FindTable(db, zName, 0)!=0 ){
79537 sqlite3ErrorMsg(pParse, "there is already a table named %s", zName);
79538 goto exit_create_index;
79541 if( sqlite3FindIndex(db, zName, pDb->zName)!=0 ){
79542 if( !ifNotExist ){
79543 sqlite3ErrorMsg(pParse, "index %s already exists", zName);
79544 }else{
79545 assert( !db->init.busy );
79546 sqlite3CodeVerifySchema(pParse, iDb);
79548 goto exit_create_index;
79550 }else{
79551 int n;
79552 Index *pLoop;
79553 for(pLoop=pTab->pIndex, n=1; pLoop; pLoop=pLoop->pNext, n++){}
79554 zName = sqlite3MPrintf(db, "sqlite_autoindex_%s_%d", pTab->zName, n);
79555 if( zName==0 ){
79556 goto exit_create_index;
79560 /* Check for authorization to create an index.
79562 #ifndef SQLITE_OMIT_AUTHORIZATION
79564 const char *zDb = pDb->zName;
79565 if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(iDb), 0, zDb) ){
79566 goto exit_create_index;
79568 i = SQLITE_CREATE_INDEX;
79569 if( !OMIT_TEMPDB && iDb==1 ) i = SQLITE_CREATE_TEMP_INDEX;
79570 if( sqlite3AuthCheck(pParse, i, zName, pTab->zName, zDb) ){
79571 goto exit_create_index;
79574 #endif
79576 /* If pList==0, it means this routine was called to make a primary
79577 ** key out of the last column added to the table under construction.
79578 ** So create a fake list to simulate this.
79580 if( pList==0 ){
79581 nullId.z = pTab->aCol[pTab->nCol-1].zName;
79582 nullId.n = sqlite3Strlen30((char*)nullId.z);
79583 pList = sqlite3ExprListAppend(pParse, 0, 0);
79584 if( pList==0 ) goto exit_create_index;
79585 sqlite3ExprListSetName(pParse, pList, &nullId, 0);
79586 pList->a[0].sortOrder = (u8)sortOrder;
79589 /* Figure out how many bytes of space are required to store explicitly
79590 ** specified collation sequence names.
79592 for(i=0; i<pList->nExpr; i++){
79593 Expr *pExpr = pList->a[i].pExpr;
79594 if( pExpr ){
79595 CollSeq *pColl = pExpr->pColl;
79596 /* Either pColl!=0 or there was an OOM failure. But if an OOM
79597 ** failure we have quit before reaching this point. */
79598 if( ALWAYS(pColl) ){
79599 nExtra += (1 + sqlite3Strlen30(pColl->zName));
79605 ** Allocate the index structure.
79607 nName = sqlite3Strlen30(zName);
79608 nCol = pList->nExpr;
79609 pIndex = sqlite3DbMallocZero(db,
79610 sizeof(Index) + /* Index structure */
79611 sizeof(int)*nCol + /* Index.aiColumn */
79612 sizeof(int)*(nCol+1) + /* Index.aiRowEst */
79613 sizeof(char *)*nCol + /* Index.azColl */
79614 sizeof(u8)*nCol + /* Index.aSortOrder */
79615 nName + 1 + /* Index.zName */
79616 nExtra /* Collation sequence names */
79618 if( db->mallocFailed ){
79619 goto exit_create_index;
79621 pIndex->azColl = (char**)(&pIndex[1]);
79622 pIndex->aiColumn = (int *)(&pIndex->azColl[nCol]);
79623 pIndex->aiRowEst = (unsigned *)(&pIndex->aiColumn[nCol]);
79624 pIndex->aSortOrder = (u8 *)(&pIndex->aiRowEst[nCol+1]);
79625 pIndex->zName = (char *)(&pIndex->aSortOrder[nCol]);
79626 zExtra = (char *)(&pIndex->zName[nName+1]);
79627 memcpy(pIndex->zName, zName, nName+1);
79628 pIndex->pTable = pTab;
79629 pIndex->nColumn = pList->nExpr;
79630 pIndex->onError = (u8)onError;
79631 pIndex->autoIndex = (u8)(pName==0);
79632 pIndex->pSchema = db->aDb[iDb].pSchema;
79633 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
79635 /* Check to see if we should honor DESC requests on index columns
79637 if( pDb->pSchema->file_format>=4 ){
79638 sortOrderMask = -1; /* Honor DESC */
79639 }else{
79640 sortOrderMask = 0; /* Ignore DESC */
79643 /* Scan the names of the columns of the table to be indexed and
79644 ** load the column indices into the Index structure. Report an error
79645 ** if any column is not found.
79647 ** TODO: Add a test to make sure that the same column is not named
79648 ** more than once within the same index. Only the first instance of
79649 ** the column will ever be used by the optimizer. Note that using the
79650 ** same column more than once cannot be an error because that would
79651 ** break backwards compatibility - it needs to be a warning.
79653 for(i=0, pListItem=pList->a; i<pList->nExpr; i++, pListItem++){
79654 const char *zColName = pListItem->zName;
79655 Column *pTabCol;
79656 int requestedSortOrder;
79657 char *zColl; /* Collation sequence name */
79659 for(j=0, pTabCol=pTab->aCol; j<pTab->nCol; j++, pTabCol++){
79660 if( sqlite3StrICmp(zColName, pTabCol->zName)==0 ) break;
79662 if( j>=pTab->nCol ){
79663 sqlite3ErrorMsg(pParse, "table %s has no column named %s",
79664 pTab->zName, zColName);
79665 pParse->checkSchema = 1;
79666 goto exit_create_index;
79668 pIndex->aiColumn[i] = j;
79669 /* Justification of the ALWAYS(pListItem->pExpr->pColl): Because of
79670 ** the way the "idxlist" non-terminal is constructed by the parser,
79671 ** if pListItem->pExpr is not null then either pListItem->pExpr->pColl
79672 ** must exist or else there must have been an OOM error. But if there
79673 ** was an OOM error, we would never reach this point. */
79674 if( pListItem->pExpr && ALWAYS(pListItem->pExpr->pColl) ){
79675 int nColl;
79676 zColl = pListItem->pExpr->pColl->zName;
79677 nColl = sqlite3Strlen30(zColl) + 1;
79678 assert( nExtra>=nColl );
79679 memcpy(zExtra, zColl, nColl);
79680 zColl = zExtra;
79681 zExtra += nColl;
79682 nExtra -= nColl;
79683 }else{
79684 zColl = pTab->aCol[j].zColl;
79685 if( !zColl ){
79686 zColl = db->pDfltColl->zName;
79689 if( !db->init.busy && !sqlite3LocateCollSeq(pParse, zColl) ){
79690 goto exit_create_index;
79692 pIndex->azColl[i] = zColl;
79693 requestedSortOrder = pListItem->sortOrder & sortOrderMask;
79694 pIndex->aSortOrder[i] = (u8)requestedSortOrder;
79696 sqlite3DefaultRowEst(pIndex);
79698 if( pTab==pParse->pNewTable ){
79699 /* This routine has been called to create an automatic index as a
79700 ** result of a PRIMARY KEY or UNIQUE clause on a column definition, or
79701 ** a PRIMARY KEY or UNIQUE clause following the column definitions.
79702 ** i.e. one of:
79704 ** CREATE TABLE t(x PRIMARY KEY, y);
79705 ** CREATE TABLE t(x, y, UNIQUE(x, y));
79707 ** Either way, check to see if the table already has such an index. If
79708 ** so, don't bother creating this one. This only applies to
79709 ** automatically created indices. Users can do as they wish with
79710 ** explicit indices.
79712 ** Two UNIQUE or PRIMARY KEY constraints are considered equivalent
79713 ** (and thus suppressing the second one) even if they have different
79714 ** sort orders.
79716 ** If there are different collating sequences or if the columns of
79717 ** the constraint occur in different orders, then the constraints are
79718 ** considered distinct and both result in separate indices.
79720 Index *pIdx;
79721 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
79722 int k;
79723 assert( pIdx->onError!=OE_None );
79724 assert( pIdx->autoIndex );
79725 assert( pIndex->onError!=OE_None );
79727 if( pIdx->nColumn!=pIndex->nColumn ) continue;
79728 for(k=0; k<pIdx->nColumn; k++){
79729 const char *z1;
79730 const char *z2;
79731 if( pIdx->aiColumn[k]!=pIndex->aiColumn[k] ) break;
79732 z1 = pIdx->azColl[k];
79733 z2 = pIndex->azColl[k];
79734 if( z1!=z2 && sqlite3StrICmp(z1, z2) ) break;
79736 if( k==pIdx->nColumn ){
79737 if( pIdx->onError!=pIndex->onError ){
79738 /* This constraint creates the same index as a previous
79739 ** constraint specified somewhere in the CREATE TABLE statement.
79740 ** However the ON CONFLICT clauses are different. If both this
79741 ** constraint and the previous equivalent constraint have explicit
79742 ** ON CONFLICT clauses this is an error. Otherwise, use the
79743 ** explicitly specified behaviour for the index.
79745 if( !(pIdx->onError==OE_Default || pIndex->onError==OE_Default) ){
79746 sqlite3ErrorMsg(pParse,
79747 "conflicting ON CONFLICT clauses specified", 0);
79749 if( pIdx->onError==OE_Default ){
79750 pIdx->onError = pIndex->onError;
79753 goto exit_create_index;
79758 /* Link the new Index structure to its table and to the other
79759 ** in-memory database structures.
79761 if( db->init.busy ){
79762 Index *p;
79763 assert( sqlite3SchemaMutexHeld(db, 0, pIndex->pSchema) );
79764 p = sqlite3HashInsert(&pIndex->pSchema->idxHash,
79765 pIndex->zName, sqlite3Strlen30(pIndex->zName),
79766 pIndex);
79767 if( p ){
79768 assert( p==pIndex ); /* Malloc must have failed */
79769 db->mallocFailed = 1;
79770 goto exit_create_index;
79772 db->flags |= SQLITE_InternChanges;
79773 if( pTblName!=0 ){
79774 pIndex->tnum = db->init.newTnum;
79778 /* If the db->init.busy is 0 then create the index on disk. This
79779 ** involves writing the index into the master table and filling in the
79780 ** index with the current table contents.
79782 ** The db->init.busy is 0 when the user first enters a CREATE INDEX
79783 ** command. db->init.busy is 1 when a database is opened and
79784 ** CREATE INDEX statements are read out of the master table. In
79785 ** the latter case the index already exists on disk, which is why
79786 ** we don't want to recreate it.
79788 ** If pTblName==0 it means this index is generated as a primary key
79789 ** or UNIQUE constraint of a CREATE TABLE statement. Since the table
79790 ** has just been created, it contains no data and the index initialization
79791 ** step can be skipped.
79793 else{ /* if( db->init.busy==0 ) */
79794 Vdbe *v;
79795 char *zStmt;
79796 int iMem = ++pParse->nMem;
79798 v = sqlite3GetVdbe(pParse);
79799 if( v==0 ) goto exit_create_index;
79802 /* Create the rootpage for the index
79804 sqlite3BeginWriteOperation(pParse, 1, iDb);
79805 sqlite3VdbeAddOp2(v, OP_CreateIndex, iDb, iMem);
79807 /* Gather the complete text of the CREATE INDEX statement into
79808 ** the zStmt variable
79810 if( pStart ){
79811 assert( pEnd!=0 );
79812 /* A named index with an explicit CREATE INDEX statement */
79813 zStmt = sqlite3MPrintf(db, "CREATE%s INDEX %.*s",
79814 onError==OE_None ? "" : " UNIQUE",
79815 pEnd->z - pName->z + 1,
79816 pName->z);
79817 }else{
79818 /* An automatic index created by a PRIMARY KEY or UNIQUE constraint */
79819 /* zStmt = sqlite3MPrintf(""); */
79820 zStmt = 0;
79823 /* Add an entry in sqlite_master for this index
79825 sqlite3NestedParse(pParse,
79826 "INSERT INTO %Q.%s VALUES('index',%Q,%Q,#%d,%Q);",
79827 db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
79828 pIndex->zName,
79829 pTab->zName,
79830 iMem,
79831 zStmt
79833 sqlite3DbFree(db, zStmt);
79835 /* Fill the index with data and reparse the schema. Code an OP_Expire
79836 ** to invalidate all pre-compiled statements.
79838 if( pTblName ){
79839 sqlite3RefillIndex(pParse, pIndex, iMem);
79840 sqlite3ChangeCookie(pParse, iDb);
79841 sqlite3VdbeAddOp4(v, OP_ParseSchema, iDb, 0, 0,
79842 sqlite3MPrintf(db, "name='%q' AND type='index'", pIndex->zName),
79843 P4_DYNAMIC);
79844 sqlite3VdbeAddOp1(v, OP_Expire, 0);
79848 /* When adding an index to the list of indices for a table, make
79849 ** sure all indices labeled OE_Replace come after all those labeled
79850 ** OE_Ignore. This is necessary for the correct constraint check
79851 ** processing (in sqlite3GenerateConstraintChecks()) as part of
79852 ** UPDATE and INSERT statements.
79854 if( db->init.busy || pTblName==0 ){
79855 if( onError!=OE_Replace || pTab->pIndex==0
79856 || pTab->pIndex->onError==OE_Replace){
79857 pIndex->pNext = pTab->pIndex;
79858 pTab->pIndex = pIndex;
79859 }else{
79860 Index *pOther = pTab->pIndex;
79861 while( pOther->pNext && pOther->pNext->onError!=OE_Replace ){
79862 pOther = pOther->pNext;
79864 pIndex->pNext = pOther->pNext;
79865 pOther->pNext = pIndex;
79867 pRet = pIndex;
79868 pIndex = 0;
79871 /* Clean up before exiting */
79872 exit_create_index:
79873 if( pIndex ){
79874 sqlite3DbFree(db, pIndex->zColAff);
79875 sqlite3DbFree(db, pIndex);
79877 sqlite3ExprListDelete(db, pList);
79878 sqlite3SrcListDelete(db, pTblName);
79879 sqlite3DbFree(db, zName);
79880 return pRet;
79884 ** Fill the Index.aiRowEst[] array with default information - information
79885 ** to be used when we have not run the ANALYZE command.
79887 ** aiRowEst[0] is suppose to contain the number of elements in the index.
79888 ** Since we do not know, guess 1 million. aiRowEst[1] is an estimate of the
79889 ** number of rows in the table that match any particular value of the
79890 ** first column of the index. aiRowEst[2] is an estimate of the number
79891 ** of rows that match any particular combiniation of the first 2 columns
79892 ** of the index. And so forth. It must always be the case that
79894 ** aiRowEst[N]<=aiRowEst[N-1]
79895 ** aiRowEst[N]>=1
79897 ** Apart from that, we have little to go on besides intuition as to
79898 ** how aiRowEst[] should be initialized. The numbers generated here
79899 ** are based on typical values found in actual indices.
79901 SQLITE_PRIVATE void sqlite3DefaultRowEst(Index *pIdx){
79902 unsigned *a = pIdx->aiRowEst;
79903 int i;
79904 unsigned n;
79905 assert( a!=0 );
79906 a[0] = pIdx->pTable->nRowEst;
79907 if( a[0]<10 ) a[0] = 10;
79908 n = 10;
79909 for(i=1; i<=pIdx->nColumn; i++){
79910 a[i] = n;
79911 if( n>5 ) n--;
79913 if( pIdx->onError!=OE_None ){
79914 a[pIdx->nColumn] = 1;
79919 ** This routine will drop an existing named index. This routine
79920 ** implements the DROP INDEX statement.
79922 SQLITE_PRIVATE void sqlite3DropIndex(Parse *pParse, SrcList *pName, int ifExists){
79923 Index *pIndex;
79924 Vdbe *v;
79925 sqlite3 *db = pParse->db;
79926 int iDb;
79928 assert( pParse->nErr==0 ); /* Never called with prior errors */
79929 if( db->mallocFailed ){
79930 goto exit_drop_index;
79932 assert( pName->nSrc==1 );
79933 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
79934 goto exit_drop_index;
79936 pIndex = sqlite3FindIndex(db, pName->a[0].zName, pName->a[0].zDatabase);
79937 if( pIndex==0 ){
79938 if( !ifExists ){
79939 sqlite3ErrorMsg(pParse, "no such index: %S", pName, 0);
79940 }else{
79941 sqlite3CodeVerifyNamedSchema(pParse, pName->a[0].zDatabase);
79943 pParse->checkSchema = 1;
79944 goto exit_drop_index;
79946 if( pIndex->autoIndex ){
79947 sqlite3ErrorMsg(pParse, "index associated with UNIQUE "
79948 "or PRIMARY KEY constraint cannot be dropped", 0);
79949 goto exit_drop_index;
79951 iDb = sqlite3SchemaToIndex(db, pIndex->pSchema);
79952 #ifndef SQLITE_OMIT_AUTHORIZATION
79954 int code = SQLITE_DROP_INDEX;
79955 Table *pTab = pIndex->pTable;
79956 const char *zDb = db->aDb[iDb].zName;
79957 const char *zTab = SCHEMA_TABLE(iDb);
79958 if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb) ){
79959 goto exit_drop_index;
79961 if( !OMIT_TEMPDB && iDb ) code = SQLITE_DROP_TEMP_INDEX;
79962 if( sqlite3AuthCheck(pParse, code, pIndex->zName, pTab->zName, zDb) ){
79963 goto exit_drop_index;
79966 #endif
79968 /* Generate code to remove the index and from the master table */
79969 v = sqlite3GetVdbe(pParse);
79970 if( v ){
79971 sqlite3BeginWriteOperation(pParse, 1, iDb);
79972 sqlite3NestedParse(pParse,
79973 "DELETE FROM %Q.%s WHERE name=%Q AND type='index'",
79974 db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
79975 pIndex->zName
79977 if( sqlite3FindTable(db, "sqlite_stat1", db->aDb[iDb].zName) ){
79978 sqlite3NestedParse(pParse,
79979 "DELETE FROM %Q.sqlite_stat1 WHERE idx=%Q",
79980 db->aDb[iDb].zName, pIndex->zName
79983 sqlite3ChangeCookie(pParse, iDb);
79984 destroyRootPage(pParse, pIndex->tnum, iDb);
79985 sqlite3VdbeAddOp4(v, OP_DropIndex, iDb, 0, 0, pIndex->zName, 0);
79988 exit_drop_index:
79989 sqlite3SrcListDelete(db, pName);
79993 ** pArray is a pointer to an array of objects. Each object in the
79994 ** array is szEntry bytes in size. This routine allocates a new
79995 ** object on the end of the array.
79997 ** *pnEntry is the number of entries already in use. *pnAlloc is
79998 ** the previously allocated size of the array. initSize is the
79999 ** suggested initial array size allocation.
80001 ** The index of the new entry is returned in *pIdx.
80003 ** This routine returns a pointer to the array of objects. This
80004 ** might be the same as the pArray parameter or it might be a different
80005 ** pointer if the array was resized.
80007 SQLITE_PRIVATE void *sqlite3ArrayAllocate(
80008 sqlite3 *db, /* Connection to notify of malloc failures */
80009 void *pArray, /* Array of objects. Might be reallocated */
80010 int szEntry, /* Size of each object in the array */
80011 int initSize, /* Suggested initial allocation, in elements */
80012 int *pnEntry, /* Number of objects currently in use */
80013 int *pnAlloc, /* Current size of the allocation, in elements */
80014 int *pIdx /* Write the index of a new slot here */
80016 char *z;
80017 if( *pnEntry >= *pnAlloc ){
80018 void *pNew;
80019 int newSize;
80020 newSize = (*pnAlloc)*2 + initSize;
80021 pNew = sqlite3DbRealloc(db, pArray, newSize*szEntry);
80022 if( pNew==0 ){
80023 *pIdx = -1;
80024 return pArray;
80026 *pnAlloc = sqlite3DbMallocSize(db, pNew)/szEntry;
80027 pArray = pNew;
80029 z = (char*)pArray;
80030 memset(&z[*pnEntry * szEntry], 0, szEntry);
80031 *pIdx = *pnEntry;
80032 ++*pnEntry;
80033 return pArray;
80037 ** Append a new element to the given IdList. Create a new IdList if
80038 ** need be.
80040 ** A new IdList is returned, or NULL if malloc() fails.
80042 SQLITE_PRIVATE IdList *sqlite3IdListAppend(sqlite3 *db, IdList *pList, Token *pToken){
80043 int i;
80044 if( pList==0 ){
80045 pList = sqlite3DbMallocZero(db, sizeof(IdList) );
80046 if( pList==0 ) return 0;
80047 pList->nAlloc = 0;
80049 pList->a = sqlite3ArrayAllocate(
80051 pList->a,
80052 sizeof(pList->a[0]),
80054 &pList->nId,
80055 &pList->nAlloc,
80058 if( i<0 ){
80059 sqlite3IdListDelete(db, pList);
80060 return 0;
80062 pList->a[i].zName = sqlite3NameFromToken(db, pToken);
80063 return pList;
80067 ** Delete an IdList.
80069 SQLITE_PRIVATE void sqlite3IdListDelete(sqlite3 *db, IdList *pList){
80070 int i;
80071 if( pList==0 ) return;
80072 for(i=0; i<pList->nId; i++){
80073 sqlite3DbFree(db, pList->a[i].zName);
80075 sqlite3DbFree(db, pList->a);
80076 sqlite3DbFree(db, pList);
80080 ** Return the index in pList of the identifier named zId. Return -1
80081 ** if not found.
80083 SQLITE_PRIVATE int sqlite3IdListIndex(IdList *pList, const char *zName){
80084 int i;
80085 if( pList==0 ) return -1;
80086 for(i=0; i<pList->nId; i++){
80087 if( sqlite3StrICmp(pList->a[i].zName, zName)==0 ) return i;
80089 return -1;
80093 ** Expand the space allocated for the given SrcList object by
80094 ** creating nExtra new slots beginning at iStart. iStart is zero based.
80095 ** New slots are zeroed.
80097 ** For example, suppose a SrcList initially contains two entries: A,B.
80098 ** To append 3 new entries onto the end, do this:
80100 ** sqlite3SrcListEnlarge(db, pSrclist, 3, 2);
80102 ** After the call above it would contain: A, B, nil, nil, nil.
80103 ** If the iStart argument had been 1 instead of 2, then the result
80104 ** would have been: A, nil, nil, nil, B. To prepend the new slots,
80105 ** the iStart value would be 0. The result then would
80106 ** be: nil, nil, nil, A, B.
80108 ** If a memory allocation fails the SrcList is unchanged. The
80109 ** db->mallocFailed flag will be set to true.
80111 SQLITE_PRIVATE SrcList *sqlite3SrcListEnlarge(
80112 sqlite3 *db, /* Database connection to notify of OOM errors */
80113 SrcList *pSrc, /* The SrcList to be enlarged */
80114 int nExtra, /* Number of new slots to add to pSrc->a[] */
80115 int iStart /* Index in pSrc->a[] of first new slot */
80117 int i;
80119 /* Sanity checking on calling parameters */
80120 assert( iStart>=0 );
80121 assert( nExtra>=1 );
80122 assert( pSrc!=0 );
80123 assert( iStart<=pSrc->nSrc );
80125 /* Allocate additional space if needed */
80126 if( pSrc->nSrc+nExtra>pSrc->nAlloc ){
80127 SrcList *pNew;
80128 int nAlloc = pSrc->nSrc+nExtra;
80129 int nGot;
80130 pNew = sqlite3DbRealloc(db, pSrc,
80131 sizeof(*pSrc) + (nAlloc-1)*sizeof(pSrc->a[0]) );
80132 if( pNew==0 ){
80133 assert( db->mallocFailed );
80134 return pSrc;
80136 pSrc = pNew;
80137 nGot = (sqlite3DbMallocSize(db, pNew) - sizeof(*pSrc))/sizeof(pSrc->a[0])+1;
80138 pSrc->nAlloc = (u16)nGot;
80141 /* Move existing slots that come after the newly inserted slots
80142 ** out of the way */
80143 for(i=pSrc->nSrc-1; i>=iStart; i--){
80144 pSrc->a[i+nExtra] = pSrc->a[i];
80146 pSrc->nSrc += (i16)nExtra;
80148 /* Zero the newly allocated slots */
80149 memset(&pSrc->a[iStart], 0, sizeof(pSrc->a[0])*nExtra);
80150 for(i=iStart; i<iStart+nExtra; i++){
80151 pSrc->a[i].iCursor = -1;
80154 /* Return a pointer to the enlarged SrcList */
80155 return pSrc;
80160 ** Append a new table name to the given SrcList. Create a new SrcList if
80161 ** need be. A new entry is created in the SrcList even if pTable is NULL.
80163 ** A SrcList is returned, or NULL if there is an OOM error. The returned
80164 ** SrcList might be the same as the SrcList that was input or it might be
80165 ** a new one. If an OOM error does occurs, then the prior value of pList
80166 ** that is input to this routine is automatically freed.
80168 ** If pDatabase is not null, it means that the table has an optional
80169 ** database name prefix. Like this: "database.table". The pDatabase
80170 ** points to the table name and the pTable points to the database name.
80171 ** The SrcList.a[].zName field is filled with the table name which might
80172 ** come from pTable (if pDatabase is NULL) or from pDatabase.
80173 ** SrcList.a[].zDatabase is filled with the database name from pTable,
80174 ** or with NULL if no database is specified.
80176 ** In other words, if call like this:
80178 ** sqlite3SrcListAppend(D,A,B,0);
80180 ** Then B is a table name and the database name is unspecified. If called
80181 ** like this:
80183 ** sqlite3SrcListAppend(D,A,B,C);
80185 ** Then C is the table name and B is the database name. If C is defined
80186 ** then so is B. In other words, we never have a case where:
80188 ** sqlite3SrcListAppend(D,A,0,C);
80190 ** Both pTable and pDatabase are assumed to be quoted. They are dequoted
80191 ** before being added to the SrcList.
80193 SQLITE_PRIVATE SrcList *sqlite3SrcListAppend(
80194 sqlite3 *db, /* Connection to notify of malloc failures */
80195 SrcList *pList, /* Append to this SrcList. NULL creates a new SrcList */
80196 Token *pTable, /* Table to append */
80197 Token *pDatabase /* Database of the table */
80199 struct SrcList_item *pItem;
80200 assert( pDatabase==0 || pTable!=0 ); /* Cannot have C without B */
80201 if( pList==0 ){
80202 pList = sqlite3DbMallocZero(db, sizeof(SrcList) );
80203 if( pList==0 ) return 0;
80204 pList->nAlloc = 1;
80206 pList = sqlite3SrcListEnlarge(db, pList, 1, pList->nSrc);
80207 if( db->mallocFailed ){
80208 sqlite3SrcListDelete(db, pList);
80209 return 0;
80211 pItem = &pList->a[pList->nSrc-1];
80212 if( pDatabase && pDatabase->z==0 ){
80213 pDatabase = 0;
80215 if( pDatabase ){
80216 Token *pTemp = pDatabase;
80217 pDatabase = pTable;
80218 pTable = pTemp;
80220 pItem->zName = sqlite3NameFromToken(db, pTable);
80221 pItem->zDatabase = sqlite3NameFromToken(db, pDatabase);
80222 return pList;
80226 ** Assign VdbeCursor index numbers to all tables in a SrcList
80228 SQLITE_PRIVATE void sqlite3SrcListAssignCursors(Parse *pParse, SrcList *pList){
80229 int i;
80230 struct SrcList_item *pItem;
80231 assert(pList || pParse->db->mallocFailed );
80232 if( pList ){
80233 for(i=0, pItem=pList->a; i<pList->nSrc; i++, pItem++){
80234 if( pItem->iCursor>=0 ) break;
80235 pItem->iCursor = pParse->nTab++;
80236 if( pItem->pSelect ){
80237 sqlite3SrcListAssignCursors(pParse, pItem->pSelect->pSrc);
80244 ** Delete an entire SrcList including all its substructure.
80246 SQLITE_PRIVATE void sqlite3SrcListDelete(sqlite3 *db, SrcList *pList){
80247 int i;
80248 struct SrcList_item *pItem;
80249 if( pList==0 ) return;
80250 for(pItem=pList->a, i=0; i<pList->nSrc; i++, pItem++){
80251 sqlite3DbFree(db, pItem->zDatabase);
80252 sqlite3DbFree(db, pItem->zName);
80253 sqlite3DbFree(db, pItem->zAlias);
80254 sqlite3DbFree(db, pItem->zIndex);
80255 sqlite3DeleteTable(db, pItem->pTab);
80256 sqlite3SelectDelete(db, pItem->pSelect);
80257 sqlite3ExprDelete(db, pItem->pOn);
80258 sqlite3IdListDelete(db, pItem->pUsing);
80260 sqlite3DbFree(db, pList);
80264 ** This routine is called by the parser to add a new term to the
80265 ** end of a growing FROM clause. The "p" parameter is the part of
80266 ** the FROM clause that has already been constructed. "p" is NULL
80267 ** if this is the first term of the FROM clause. pTable and pDatabase
80268 ** are the name of the table and database named in the FROM clause term.
80269 ** pDatabase is NULL if the database name qualifier is missing - the
80270 ** usual case. If the term has a alias, then pAlias points to the
80271 ** alias token. If the term is a subquery, then pSubquery is the
80272 ** SELECT statement that the subquery encodes. The pTable and
80273 ** pDatabase parameters are NULL for subqueries. The pOn and pUsing
80274 ** parameters are the content of the ON and USING clauses.
80276 ** Return a new SrcList which encodes is the FROM with the new
80277 ** term added.
80279 SQLITE_PRIVATE SrcList *sqlite3SrcListAppendFromTerm(
80280 Parse *pParse, /* Parsing context */
80281 SrcList *p, /* The left part of the FROM clause already seen */
80282 Token *pTable, /* Name of the table to add to the FROM clause */
80283 Token *pDatabase, /* Name of the database containing pTable */
80284 Token *pAlias, /* The right-hand side of the AS subexpression */
80285 Select *pSubquery, /* A subquery used in place of a table name */
80286 Expr *pOn, /* The ON clause of a join */
80287 IdList *pUsing /* The USING clause of a join */
80289 struct SrcList_item *pItem;
80290 sqlite3 *db = pParse->db;
80291 if( !p && (pOn || pUsing) ){
80292 sqlite3ErrorMsg(pParse, "a JOIN clause is required before %s",
80293 (pOn ? "ON" : "USING")
80295 goto append_from_error;
80297 p = sqlite3SrcListAppend(db, p, pTable, pDatabase);
80298 if( p==0 || NEVER(p->nSrc==0) ){
80299 goto append_from_error;
80301 pItem = &p->a[p->nSrc-1];
80302 assert( pAlias!=0 );
80303 if( pAlias->n ){
80304 pItem->zAlias = sqlite3NameFromToken(db, pAlias);
80306 pItem->pSelect = pSubquery;
80307 pItem->pOn = pOn;
80308 pItem->pUsing = pUsing;
80309 return p;
80311 append_from_error:
80312 assert( p==0 );
80313 sqlite3ExprDelete(db, pOn);
80314 sqlite3IdListDelete(db, pUsing);
80315 sqlite3SelectDelete(db, pSubquery);
80316 return 0;
80320 ** Add an INDEXED BY or NOT INDEXED clause to the most recently added
80321 ** element of the source-list passed as the second argument.
80323 SQLITE_PRIVATE void sqlite3SrcListIndexedBy(Parse *pParse, SrcList *p, Token *pIndexedBy){
80324 assert( pIndexedBy!=0 );
80325 if( p && ALWAYS(p->nSrc>0) ){
80326 struct SrcList_item *pItem = &p->a[p->nSrc-1];
80327 assert( pItem->notIndexed==0 && pItem->zIndex==0 );
80328 if( pIndexedBy->n==1 && !pIndexedBy->z ){
80329 /* A "NOT INDEXED" clause was supplied. See parse.y
80330 ** construct "indexed_opt" for details. */
80331 pItem->notIndexed = 1;
80332 }else{
80333 pItem->zIndex = sqlite3NameFromToken(pParse->db, pIndexedBy);
80339 ** When building up a FROM clause in the parser, the join operator
80340 ** is initially attached to the left operand. But the code generator
80341 ** expects the join operator to be on the right operand. This routine
80342 ** Shifts all join operators from left to right for an entire FROM
80343 ** clause.
80345 ** Example: Suppose the join is like this:
80347 ** A natural cross join B
80349 ** The operator is "natural cross join". The A and B operands are stored
80350 ** in p->a[0] and p->a[1], respectively. The parser initially stores the
80351 ** operator with A. This routine shifts that operator over to B.
80353 SQLITE_PRIVATE void sqlite3SrcListShiftJoinType(SrcList *p){
80354 if( p && p->a ){
80355 int i;
80356 for(i=p->nSrc-1; i>0; i--){
80357 p->a[i].jointype = p->a[i-1].jointype;
80359 p->a[0].jointype = 0;
80364 ** Begin a transaction
80366 SQLITE_PRIVATE void sqlite3BeginTransaction(Parse *pParse, int type){
80367 sqlite3 *db;
80368 Vdbe *v;
80369 int i;
80371 assert( pParse!=0 );
80372 db = pParse->db;
80373 assert( db!=0 );
80374 /* if( db->aDb[0].pBt==0 ) return; */
80375 if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "BEGIN", 0, 0) ){
80376 return;
80378 v = sqlite3GetVdbe(pParse);
80379 if( !v ) return;
80380 if( type!=TK_DEFERRED ){
80381 for(i=0; i<db->nDb; i++){
80382 sqlite3VdbeAddOp2(v, OP_Transaction, i, (type==TK_EXCLUSIVE)+1);
80383 sqlite3VdbeUsesBtree(v, i);
80386 sqlite3VdbeAddOp2(v, OP_AutoCommit, 0, 0);
80390 ** Commit a transaction
80392 SQLITE_PRIVATE void sqlite3CommitTransaction(Parse *pParse){
80393 sqlite3 *db;
80394 Vdbe *v;
80396 assert( pParse!=0 );
80397 db = pParse->db;
80398 assert( db!=0 );
80399 /* if( db->aDb[0].pBt==0 ) return; */
80400 if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "COMMIT", 0, 0) ){
80401 return;
80403 v = sqlite3GetVdbe(pParse);
80404 if( v ){
80405 sqlite3VdbeAddOp2(v, OP_AutoCommit, 1, 0);
80410 ** Rollback a transaction
80412 SQLITE_PRIVATE void sqlite3RollbackTransaction(Parse *pParse){
80413 sqlite3 *db;
80414 Vdbe *v;
80416 assert( pParse!=0 );
80417 db = pParse->db;
80418 assert( db!=0 );
80419 /* if( db->aDb[0].pBt==0 ) return; */
80420 if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "ROLLBACK", 0, 0) ){
80421 return;
80423 v = sqlite3GetVdbe(pParse);
80424 if( v ){
80425 sqlite3VdbeAddOp2(v, OP_AutoCommit, 1, 1);
80430 ** This function is called by the parser when it parses a command to create,
80431 ** release or rollback an SQL savepoint.
80433 SQLITE_PRIVATE void sqlite3Savepoint(Parse *pParse, int op, Token *pName){
80434 char *zName = sqlite3NameFromToken(pParse->db, pName);
80435 if( zName ){
80436 Vdbe *v = sqlite3GetVdbe(pParse);
80437 #ifndef SQLITE_OMIT_AUTHORIZATION
80438 static const char * const az[] = { "BEGIN", "RELEASE", "ROLLBACK" };
80439 assert( !SAVEPOINT_BEGIN && SAVEPOINT_RELEASE==1 && SAVEPOINT_ROLLBACK==2 );
80440 #endif
80441 if( !v || sqlite3AuthCheck(pParse, SQLITE_SAVEPOINT, az[op], zName, 0) ){
80442 sqlite3DbFree(pParse->db, zName);
80443 return;
80445 sqlite3VdbeAddOp4(v, OP_Savepoint, op, 0, 0, zName, P4_DYNAMIC);
80450 ** Make sure the TEMP database is open and available for use. Return
80451 ** the number of errors. Leave any error messages in the pParse structure.
80453 SQLITE_PRIVATE int sqlite3OpenTempDatabase(Parse *pParse){
80454 sqlite3 *db = pParse->db;
80455 if( db->aDb[1].pBt==0 && !pParse->explain ){
80456 int rc;
80457 Btree *pBt;
80458 static const int flags =
80459 SQLITE_OPEN_READWRITE |
80460 SQLITE_OPEN_CREATE |
80461 SQLITE_OPEN_EXCLUSIVE |
80462 SQLITE_OPEN_DELETEONCLOSE |
80463 SQLITE_OPEN_TEMP_DB;
80465 rc = sqlite3BtreeOpen(0, db, &pBt, 0, flags);
80466 if( rc!=SQLITE_OK ){
80467 sqlite3ErrorMsg(pParse, "unable to open a temporary database "
80468 "file for storing temporary tables");
80469 pParse->rc = rc;
80470 return 1;
80472 db->aDb[1].pBt = pBt;
80473 assert( db->aDb[1].pSchema );
80474 if( SQLITE_NOMEM==sqlite3BtreeSetPageSize(pBt, db->nextPagesize, -1, 0) ){
80475 db->mallocFailed = 1;
80476 return 1;
80479 return 0;
80483 ** Generate VDBE code that will verify the schema cookie and start
80484 ** a read-transaction for all named database files.
80486 ** It is important that all schema cookies be verified and all
80487 ** read transactions be started before anything else happens in
80488 ** the VDBE program. But this routine can be called after much other
80489 ** code has been generated. So here is what we do:
80491 ** The first time this routine is called, we code an OP_Goto that
80492 ** will jump to a subroutine at the end of the program. Then we
80493 ** record every database that needs its schema verified in the
80494 ** pParse->cookieMask field. Later, after all other code has been
80495 ** generated, the subroutine that does the cookie verifications and
80496 ** starts the transactions will be coded and the OP_Goto P2 value
80497 ** will be made to point to that subroutine. The generation of the
80498 ** cookie verification subroutine code happens in sqlite3FinishCoding().
80500 ** If iDb<0 then code the OP_Goto only - don't set flag to verify the
80501 ** schema on any databases. This can be used to position the OP_Goto
80502 ** early in the code, before we know if any database tables will be used.
80504 SQLITE_PRIVATE void sqlite3CodeVerifySchema(Parse *pParse, int iDb){
80505 Parse *pToplevel = sqlite3ParseToplevel(pParse);
80507 if( pToplevel->cookieGoto==0 ){
80508 Vdbe *v = sqlite3GetVdbe(pToplevel);
80509 if( v==0 ) return; /* This only happens if there was a prior error */
80510 pToplevel->cookieGoto = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0)+1;
80512 if( iDb>=0 ){
80513 sqlite3 *db = pToplevel->db;
80514 yDbMask mask;
80516 assert( iDb<db->nDb );
80517 assert( db->aDb[iDb].pBt!=0 || iDb==1 );
80518 assert( iDb<SQLITE_MAX_ATTACHED+2 );
80519 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
80520 mask = ((yDbMask)1)<<iDb;
80521 if( (pToplevel->cookieMask & mask)==0 ){
80522 pToplevel->cookieMask |= mask;
80523 pToplevel->cookieValue[iDb] = db->aDb[iDb].pSchema->schema_cookie;
80524 if( !OMIT_TEMPDB && iDb==1 ){
80525 sqlite3OpenTempDatabase(pToplevel);
80532 ** If argument zDb is NULL, then call sqlite3CodeVerifySchema() for each
80533 ** attached database. Otherwise, invoke it for the database named zDb only.
80535 SQLITE_PRIVATE void sqlite3CodeVerifyNamedSchema(Parse *pParse, const char *zDb){
80536 sqlite3 *db = pParse->db;
80537 int i;
80538 for(i=0; i<db->nDb; i++){
80539 Db *pDb = &db->aDb[i];
80540 if( pDb->pBt && (!zDb || 0==sqlite3StrICmp(zDb, pDb->zName)) ){
80541 sqlite3CodeVerifySchema(pParse, i);
80547 ** Generate VDBE code that prepares for doing an operation that
80548 ** might change the database.
80550 ** This routine starts a new transaction if we are not already within
80551 ** a transaction. If we are already within a transaction, then a checkpoint
80552 ** is set if the setStatement parameter is true. A checkpoint should
80553 ** be set for operations that might fail (due to a constraint) part of
80554 ** the way through and which will need to undo some writes without having to
80555 ** rollback the whole transaction. For operations where all constraints
80556 ** can be checked before any changes are made to the database, it is never
80557 ** necessary to undo a write and the checkpoint should not be set.
80559 SQLITE_PRIVATE void sqlite3BeginWriteOperation(Parse *pParse, int setStatement, int iDb){
80560 Parse *pToplevel = sqlite3ParseToplevel(pParse);
80561 sqlite3CodeVerifySchema(pParse, iDb);
80562 pToplevel->writeMask |= ((yDbMask)1)<<iDb;
80563 pToplevel->isMultiWrite |= setStatement;
80567 ** Indicate that the statement currently under construction might write
80568 ** more than one entry (example: deleting one row then inserting another,
80569 ** inserting multiple rows in a table, or inserting a row and index entries.)
80570 ** If an abort occurs after some of these writes have completed, then it will
80571 ** be necessary to undo the completed writes.
80573 SQLITE_PRIVATE void sqlite3MultiWrite(Parse *pParse){
80574 Parse *pToplevel = sqlite3ParseToplevel(pParse);
80575 pToplevel->isMultiWrite = 1;
80579 ** The code generator calls this routine if is discovers that it is
80580 ** possible to abort a statement prior to completion. In order to
80581 ** perform this abort without corrupting the database, we need to make
80582 ** sure that the statement is protected by a statement transaction.
80584 ** Technically, we only need to set the mayAbort flag if the
80585 ** isMultiWrite flag was previously set. There is a time dependency
80586 ** such that the abort must occur after the multiwrite. This makes
80587 ** some statements involving the REPLACE conflict resolution algorithm
80588 ** go a little faster. But taking advantage of this time dependency
80589 ** makes it more difficult to prove that the code is correct (in
80590 ** particular, it prevents us from writing an effective
80591 ** implementation of sqlite3AssertMayAbort()) and so we have chosen
80592 ** to take the safe route and skip the optimization.
80594 SQLITE_PRIVATE void sqlite3MayAbort(Parse *pParse){
80595 Parse *pToplevel = sqlite3ParseToplevel(pParse);
80596 pToplevel->mayAbort = 1;
80600 ** Code an OP_Halt that causes the vdbe to return an SQLITE_CONSTRAINT
80601 ** error. The onError parameter determines which (if any) of the statement
80602 ** and/or current transaction is rolled back.
80604 SQLITE_PRIVATE void sqlite3HaltConstraint(Parse *pParse, int onError, char *p4, int p4type){
80605 Vdbe *v = sqlite3GetVdbe(pParse);
80606 if( onError==OE_Abort ){
80607 sqlite3MayAbort(pParse);
80609 sqlite3VdbeAddOp4(v, OP_Halt, SQLITE_CONSTRAINT, onError, 0, p4, p4type);
80613 ** Check to see if pIndex uses the collating sequence pColl. Return
80614 ** true if it does and false if it does not.
80616 #ifndef SQLITE_OMIT_REINDEX
80617 static int collationMatch(const char *zColl, Index *pIndex){
80618 int i;
80619 assert( zColl!=0 );
80620 for(i=0; i<pIndex->nColumn; i++){
80621 const char *z = pIndex->azColl[i];
80622 assert( z!=0 );
80623 if( 0==sqlite3StrICmp(z, zColl) ){
80624 return 1;
80627 return 0;
80629 #endif
80632 ** Recompute all indices of pTab that use the collating sequence pColl.
80633 ** If pColl==0 then recompute all indices of pTab.
80635 #ifndef SQLITE_OMIT_REINDEX
80636 static void reindexTable(Parse *pParse, Table *pTab, char const *zColl){
80637 Index *pIndex; /* An index associated with pTab */
80639 for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){
80640 if( zColl==0 || collationMatch(zColl, pIndex) ){
80641 int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
80642 sqlite3BeginWriteOperation(pParse, 0, iDb);
80643 sqlite3RefillIndex(pParse, pIndex, -1);
80647 #endif
80650 ** Recompute all indices of all tables in all databases where the
80651 ** indices use the collating sequence pColl. If pColl==0 then recompute
80652 ** all indices everywhere.
80654 #ifndef SQLITE_OMIT_REINDEX
80655 static void reindexDatabases(Parse *pParse, char const *zColl){
80656 Db *pDb; /* A single database */
80657 int iDb; /* The database index number */
80658 sqlite3 *db = pParse->db; /* The database connection */
80659 HashElem *k; /* For looping over tables in pDb */
80660 Table *pTab; /* A table in the database */
80662 assert( sqlite3BtreeHoldsAllMutexes(db) ); /* Needed for schema access */
80663 for(iDb=0, pDb=db->aDb; iDb<db->nDb; iDb++, pDb++){
80664 assert( pDb!=0 );
80665 for(k=sqliteHashFirst(&pDb->pSchema->tblHash); k; k=sqliteHashNext(k)){
80666 pTab = (Table*)sqliteHashData(k);
80667 reindexTable(pParse, pTab, zColl);
80671 #endif
80674 ** Generate code for the REINDEX command.
80676 ** REINDEX -- 1
80677 ** REINDEX <collation> -- 2
80678 ** REINDEX ?<database>.?<tablename> -- 3
80679 ** REINDEX ?<database>.?<indexname> -- 4
80681 ** Form 1 causes all indices in all attached databases to be rebuilt.
80682 ** Form 2 rebuilds all indices in all databases that use the named
80683 ** collating function. Forms 3 and 4 rebuild the named index or all
80684 ** indices associated with the named table.
80686 #ifndef SQLITE_OMIT_REINDEX
80687 SQLITE_PRIVATE void sqlite3Reindex(Parse *pParse, Token *pName1, Token *pName2){
80688 CollSeq *pColl; /* Collating sequence to be reindexed, or NULL */
80689 char *z; /* Name of a table or index */
80690 const char *zDb; /* Name of the database */
80691 Table *pTab; /* A table in the database */
80692 Index *pIndex; /* An index associated with pTab */
80693 int iDb; /* The database index number */
80694 sqlite3 *db = pParse->db; /* The database connection */
80695 Token *pObjName; /* Name of the table or index to be reindexed */
80697 /* Read the database schema. If an error occurs, leave an error message
80698 ** and code in pParse and return NULL. */
80699 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
80700 return;
80703 if( pName1==0 ){
80704 reindexDatabases(pParse, 0);
80705 return;
80706 }else if( NEVER(pName2==0) || pName2->z==0 ){
80707 char *zColl;
80708 assert( pName1->z );
80709 zColl = sqlite3NameFromToken(pParse->db, pName1);
80710 if( !zColl ) return;
80711 pColl = sqlite3FindCollSeq(db, ENC(db), zColl, 0);
80712 if( pColl ){
80713 reindexDatabases(pParse, zColl);
80714 sqlite3DbFree(db, zColl);
80715 return;
80717 sqlite3DbFree(db, zColl);
80719 iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pObjName);
80720 if( iDb<0 ) return;
80721 z = sqlite3NameFromToken(db, pObjName);
80722 if( z==0 ) return;
80723 zDb = db->aDb[iDb].zName;
80724 pTab = sqlite3FindTable(db, z, zDb);
80725 if( pTab ){
80726 reindexTable(pParse, pTab, 0);
80727 sqlite3DbFree(db, z);
80728 return;
80730 pIndex = sqlite3FindIndex(db, z, zDb);
80731 sqlite3DbFree(db, z);
80732 if( pIndex ){
80733 sqlite3BeginWriteOperation(pParse, 0, iDb);
80734 sqlite3RefillIndex(pParse, pIndex, -1);
80735 return;
80737 sqlite3ErrorMsg(pParse, "unable to identify the object to be reindexed");
80739 #endif
80742 ** Return a dynamicly allocated KeyInfo structure that can be used
80743 ** with OP_OpenRead or OP_OpenWrite to access database index pIdx.
80745 ** If successful, a pointer to the new structure is returned. In this case
80746 ** the caller is responsible for calling sqlite3DbFree(db, ) on the returned
80747 ** pointer. If an error occurs (out of memory or missing collation
80748 ** sequence), NULL is returned and the state of pParse updated to reflect
80749 ** the error.
80751 SQLITE_PRIVATE KeyInfo *sqlite3IndexKeyinfo(Parse *pParse, Index *pIdx){
80752 int i;
80753 int nCol = pIdx->nColumn;
80754 int nBytes = sizeof(KeyInfo) + (nCol-1)*sizeof(CollSeq*) + nCol;
80755 sqlite3 *db = pParse->db;
80756 KeyInfo *pKey = (KeyInfo *)sqlite3DbMallocZero(db, nBytes);
80758 if( pKey ){
80759 pKey->db = pParse->db;
80760 pKey->aSortOrder = (u8 *)&(pKey->aColl[nCol]);
80761 assert( &pKey->aSortOrder[nCol]==&(((u8 *)pKey)[nBytes]) );
80762 for(i=0; i<nCol; i++){
80763 char *zColl = pIdx->azColl[i];
80764 assert( zColl );
80765 pKey->aColl[i] = sqlite3LocateCollSeq(pParse, zColl);
80766 pKey->aSortOrder[i] = pIdx->aSortOrder[i];
80768 pKey->nField = (u16)nCol;
80771 if( pParse->nErr ){
80772 sqlite3DbFree(db, pKey);
80773 pKey = 0;
80775 return pKey;
80778 /* Begin preload-cache.patch for Chromium */
80779 /* See declaration in sqlite3.h for information */
80780 SQLITE_API int sqlite3_preload(sqlite3 *db)
80782 Pager *pPager;
80783 Btree *pBt;
80784 int rc;
80785 int i;
80786 int dbsLoaded = 0;
80788 for(i=0; i<db->nDb; i++) {
80789 pBt = db->aDb[i].pBt;
80790 if( !pBt )
80791 continue;
80792 pPager = sqlite3BtreePager(pBt);
80793 if( pPager ) {
80794 rc = sqlite3PagerLoadall(pPager);
80795 if (rc == SQLITE_OK)
80796 dbsLoaded++;
80799 if (dbsLoaded == 0)
80800 return SQLITE_ERROR;
80801 return SQLITE_OK;
80803 /* End preload-cache.patch for Chromium */
80805 /************** End of build.c ***********************************************/
80806 /************** Begin file callback.c ****************************************/
80808 ** 2005 May 23
80810 ** The author disclaims copyright to this source code. In place of
80811 ** a legal notice, here is a blessing:
80813 ** May you do good and not evil.
80814 ** May you find forgiveness for yourself and forgive others.
80815 ** May you share freely, never taking more than you give.
80817 *************************************************************************
80819 ** This file contains functions used to access the internal hash tables
80820 ** of user defined functions and collation sequences.
80825 ** Invoke the 'collation needed' callback to request a collation sequence
80826 ** in the encoding enc of name zName, length nName.
80828 static void callCollNeeded(sqlite3 *db, int enc, const char *zName){
80829 assert( !db->xCollNeeded || !db->xCollNeeded16 );
80830 if( db->xCollNeeded ){
80831 char *zExternal = sqlite3DbStrDup(db, zName);
80832 if( !zExternal ) return;
80833 db->xCollNeeded(db->pCollNeededArg, db, enc, zExternal);
80834 sqlite3DbFree(db, zExternal);
80836 #ifndef SQLITE_OMIT_UTF16
80837 if( db->xCollNeeded16 ){
80838 char const *zExternal;
80839 sqlite3_value *pTmp = sqlite3ValueNew(db);
80840 sqlite3ValueSetStr(pTmp, -1, zName, SQLITE_UTF8, SQLITE_STATIC);
80841 zExternal = sqlite3ValueText(pTmp, SQLITE_UTF16NATIVE);
80842 if( zExternal ){
80843 db->xCollNeeded16(db->pCollNeededArg, db, (int)ENC(db), zExternal);
80845 sqlite3ValueFree(pTmp);
80847 #endif
80851 ** This routine is called if the collation factory fails to deliver a
80852 ** collation function in the best encoding but there may be other versions
80853 ** of this collation function (for other text encodings) available. Use one
80854 ** of these instead if they exist. Avoid a UTF-8 <-> UTF-16 conversion if
80855 ** possible.
80857 static int synthCollSeq(sqlite3 *db, CollSeq *pColl){
80858 CollSeq *pColl2;
80859 char *z = pColl->zName;
80860 int i;
80861 static const u8 aEnc[] = { SQLITE_UTF16BE, SQLITE_UTF16LE, SQLITE_UTF8 };
80862 for(i=0; i<3; i++){
80863 pColl2 = sqlite3FindCollSeq(db, aEnc[i], z, 0);
80864 if( pColl2->xCmp!=0 ){
80865 memcpy(pColl, pColl2, sizeof(CollSeq));
80866 pColl->xDel = 0; /* Do not copy the destructor */
80867 return SQLITE_OK;
80870 return SQLITE_ERROR;
80874 ** This function is responsible for invoking the collation factory callback
80875 ** or substituting a collation sequence of a different encoding when the
80876 ** requested collation sequence is not available in the desired encoding.
80878 ** If it is not NULL, then pColl must point to the database native encoding
80879 ** collation sequence with name zName, length nName.
80881 ** The return value is either the collation sequence to be used in database
80882 ** db for collation type name zName, length nName, or NULL, if no collation
80883 ** sequence can be found.
80885 ** See also: sqlite3LocateCollSeq(), sqlite3FindCollSeq()
80887 SQLITE_PRIVATE CollSeq *sqlite3GetCollSeq(
80888 sqlite3* db, /* The database connection */
80889 u8 enc, /* The desired encoding for the collating sequence */
80890 CollSeq *pColl, /* Collating sequence with native encoding, or NULL */
80891 const char *zName /* Collating sequence name */
80893 CollSeq *p;
80895 p = pColl;
80896 if( !p ){
80897 p = sqlite3FindCollSeq(db, enc, zName, 0);
80899 if( !p || !p->xCmp ){
80900 /* No collation sequence of this type for this encoding is registered.
80901 ** Call the collation factory to see if it can supply us with one.
80903 callCollNeeded(db, enc, zName);
80904 p = sqlite3FindCollSeq(db, enc, zName, 0);
80906 if( p && !p->xCmp && synthCollSeq(db, p) ){
80907 p = 0;
80909 assert( !p || p->xCmp );
80910 return p;
80914 ** This routine is called on a collation sequence before it is used to
80915 ** check that it is defined. An undefined collation sequence exists when
80916 ** a database is loaded that contains references to collation sequences
80917 ** that have not been defined by sqlite3_create_collation() etc.
80919 ** If required, this routine calls the 'collation needed' callback to
80920 ** request a definition of the collating sequence. If this doesn't work,
80921 ** an equivalent collating sequence that uses a text encoding different
80922 ** from the main database is substituted, if one is available.
80924 SQLITE_PRIVATE int sqlite3CheckCollSeq(Parse *pParse, CollSeq *pColl){
80925 if( pColl ){
80926 const char *zName = pColl->zName;
80927 sqlite3 *db = pParse->db;
80928 CollSeq *p = sqlite3GetCollSeq(db, ENC(db), pColl, zName);
80929 if( !p ){
80930 sqlite3ErrorMsg(pParse, "no such collation sequence: %s", zName);
80931 pParse->nErr++;
80932 return SQLITE_ERROR;
80934 assert( p==pColl );
80936 return SQLITE_OK;
80942 ** Locate and return an entry from the db.aCollSeq hash table. If the entry
80943 ** specified by zName and nName is not found and parameter 'create' is
80944 ** true, then create a new entry. Otherwise return NULL.
80946 ** Each pointer stored in the sqlite3.aCollSeq hash table contains an
80947 ** array of three CollSeq structures. The first is the collation sequence
80948 ** prefferred for UTF-8, the second UTF-16le, and the third UTF-16be.
80950 ** Stored immediately after the three collation sequences is a copy of
80951 ** the collation sequence name. A pointer to this string is stored in
80952 ** each collation sequence structure.
80954 static CollSeq *findCollSeqEntry(
80955 sqlite3 *db, /* Database connection */
80956 const char *zName, /* Name of the collating sequence */
80957 int create /* Create a new entry if true */
80959 CollSeq *pColl;
80960 int nName = sqlite3Strlen30(zName);
80961 pColl = sqlite3HashFind(&db->aCollSeq, zName, nName);
80963 if( 0==pColl && create ){
80964 pColl = sqlite3DbMallocZero(db, 3*sizeof(*pColl) + nName + 1 );
80965 if( pColl ){
80966 CollSeq *pDel = 0;
80967 pColl[0].zName = (char*)&pColl[3];
80968 pColl[0].enc = SQLITE_UTF8;
80969 pColl[1].zName = (char*)&pColl[3];
80970 pColl[1].enc = SQLITE_UTF16LE;
80971 pColl[2].zName = (char*)&pColl[3];
80972 pColl[2].enc = SQLITE_UTF16BE;
80973 memcpy(pColl[0].zName, zName, nName);
80974 pColl[0].zName[nName] = 0;
80975 pDel = sqlite3HashInsert(&db->aCollSeq, pColl[0].zName, nName, pColl);
80977 /* If a malloc() failure occurred in sqlite3HashInsert(), it will
80978 ** return the pColl pointer to be deleted (because it wasn't added
80979 ** to the hash table).
80981 assert( pDel==0 || pDel==pColl );
80982 if( pDel!=0 ){
80983 db->mallocFailed = 1;
80984 sqlite3DbFree(db, pDel);
80985 pColl = 0;
80989 return pColl;
80993 ** Parameter zName points to a UTF-8 encoded string nName bytes long.
80994 ** Return the CollSeq* pointer for the collation sequence named zName
80995 ** for the encoding 'enc' from the database 'db'.
80997 ** If the entry specified is not found and 'create' is true, then create a
80998 ** new entry. Otherwise return NULL.
81000 ** A separate function sqlite3LocateCollSeq() is a wrapper around
81001 ** this routine. sqlite3LocateCollSeq() invokes the collation factory
81002 ** if necessary and generates an error message if the collating sequence
81003 ** cannot be found.
81005 ** See also: sqlite3LocateCollSeq(), sqlite3GetCollSeq()
81007 SQLITE_PRIVATE CollSeq *sqlite3FindCollSeq(
81008 sqlite3 *db,
81009 u8 enc,
81010 const char *zName,
81011 int create
81013 CollSeq *pColl;
81014 if( zName ){
81015 pColl = findCollSeqEntry(db, zName, create);
81016 }else{
81017 pColl = db->pDfltColl;
81019 assert( SQLITE_UTF8==1 && SQLITE_UTF16LE==2 && SQLITE_UTF16BE==3 );
81020 assert( enc>=SQLITE_UTF8 && enc<=SQLITE_UTF16BE );
81021 if( pColl ) pColl += enc-1;
81022 return pColl;
81025 /* During the search for the best function definition, this procedure
81026 ** is called to test how well the function passed as the first argument
81027 ** matches the request for a function with nArg arguments in a system
81028 ** that uses encoding enc. The value returned indicates how well the
81029 ** request is matched. A higher value indicates a better match.
81031 ** The returned value is always between 0 and 6, as follows:
81033 ** 0: Not a match, or if nArg<0 and the function is has no implementation.
81034 ** 1: A variable arguments function that prefers UTF-8 when a UTF-16
81035 ** encoding is requested, or vice versa.
81036 ** 2: A variable arguments function that uses UTF-16BE when UTF-16LE is
81037 ** requested, or vice versa.
81038 ** 3: A variable arguments function using the same text encoding.
81039 ** 4: A function with the exact number of arguments requested that
81040 ** prefers UTF-8 when a UTF-16 encoding is requested, or vice versa.
81041 ** 5: A function with the exact number of arguments requested that
81042 ** prefers UTF-16LE when UTF-16BE is requested, or vice versa.
81043 ** 6: An exact match.
81046 static int matchQuality(FuncDef *p, int nArg, u8 enc){
81047 int match = 0;
81048 if( p->nArg==-1 || p->nArg==nArg
81049 || (nArg==-1 && (p->xFunc!=0 || p->xStep!=0))
81051 match = 1;
81052 if( p->nArg==nArg || nArg==-1 ){
81053 match = 4;
81055 if( enc==p->iPrefEnc ){
81056 match += 2;
81058 else if( (enc==SQLITE_UTF16LE && p->iPrefEnc==SQLITE_UTF16BE) ||
81059 (enc==SQLITE_UTF16BE && p->iPrefEnc==SQLITE_UTF16LE) ){
81060 match += 1;
81063 return match;
81067 ** Search a FuncDefHash for a function with the given name. Return
81068 ** a pointer to the matching FuncDef if found, or 0 if there is no match.
81070 static FuncDef *functionSearch(
81071 FuncDefHash *pHash, /* Hash table to search */
81072 int h, /* Hash of the name */
81073 const char *zFunc, /* Name of function */
81074 int nFunc /* Number of bytes in zFunc */
81076 FuncDef *p;
81077 for(p=pHash->a[h]; p; p=p->pHash){
81078 if( sqlite3StrNICmp(p->zName, zFunc, nFunc)==0 && p->zName[nFunc]==0 ){
81079 return p;
81082 return 0;
81086 ** Insert a new FuncDef into a FuncDefHash hash table.
81088 SQLITE_PRIVATE void sqlite3FuncDefInsert(
81089 FuncDefHash *pHash, /* The hash table into which to insert */
81090 FuncDef *pDef /* The function definition to insert */
81092 FuncDef *pOther;
81093 int nName = sqlite3Strlen30(pDef->zName);
81094 u8 c1 = (u8)pDef->zName[0];
81095 int h = (sqlite3UpperToLower[c1] + nName) % ArraySize(pHash->a);
81096 pOther = functionSearch(pHash, h, pDef->zName, nName);
81097 if( pOther ){
81098 assert( pOther!=pDef && pOther->pNext!=pDef );
81099 pDef->pNext = pOther->pNext;
81100 pOther->pNext = pDef;
81101 }else{
81102 pDef->pNext = 0;
81103 pDef->pHash = pHash->a[h];
81104 pHash->a[h] = pDef;
81111 ** Locate a user function given a name, a number of arguments and a flag
81112 ** indicating whether the function prefers UTF-16 over UTF-8. Return a
81113 ** pointer to the FuncDef structure that defines that function, or return
81114 ** NULL if the function does not exist.
81116 ** If the createFlag argument is true, then a new (blank) FuncDef
81117 ** structure is created and liked into the "db" structure if a
81118 ** no matching function previously existed. When createFlag is true
81119 ** and the nArg parameter is -1, then only a function that accepts
81120 ** any number of arguments will be returned.
81122 ** If createFlag is false and nArg is -1, then the first valid
81123 ** function found is returned. A function is valid if either xFunc
81124 ** or xStep is non-zero.
81126 ** If createFlag is false, then a function with the required name and
81127 ** number of arguments may be returned even if the eTextRep flag does not
81128 ** match that requested.
81130 SQLITE_PRIVATE FuncDef *sqlite3FindFunction(
81131 sqlite3 *db, /* An open database */
81132 const char *zName, /* Name of the function. Not null-terminated */
81133 int nName, /* Number of characters in the name */
81134 int nArg, /* Number of arguments. -1 means any number */
81135 u8 enc, /* Preferred text encoding */
81136 int createFlag /* Create new entry if true and does not otherwise exist */
81138 FuncDef *p; /* Iterator variable */
81139 FuncDef *pBest = 0; /* Best match found so far */
81140 int bestScore = 0; /* Score of best match */
81141 int h; /* Hash value */
81144 assert( enc==SQLITE_UTF8 || enc==SQLITE_UTF16LE || enc==SQLITE_UTF16BE );
81145 h = (sqlite3UpperToLower[(u8)zName[0]] + nName) % ArraySize(db->aFunc.a);
81147 /* First search for a match amongst the application-defined functions.
81149 p = functionSearch(&db->aFunc, h, zName, nName);
81150 while( p ){
81151 int score = matchQuality(p, nArg, enc);
81152 if( score>bestScore ){
81153 pBest = p;
81154 bestScore = score;
81156 p = p->pNext;
81159 /* If no match is found, search the built-in functions.
81161 ** If the SQLITE_PreferBuiltin flag is set, then search the built-in
81162 ** functions even if a prior app-defined function was found. And give
81163 ** priority to built-in functions.
81165 ** Except, if createFlag is true, that means that we are trying to
81166 ** install a new function. Whatever FuncDef structure is returned it will
81167 ** have fields overwritten with new information appropriate for the
81168 ** new function. But the FuncDefs for built-in functions are read-only.
81169 ** So we must not search for built-ins when creating a new function.
81171 if( !createFlag && (pBest==0 || (db->flags & SQLITE_PreferBuiltin)!=0) ){
81172 FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
81173 bestScore = 0;
81174 p = functionSearch(pHash, h, zName, nName);
81175 while( p ){
81176 int score = matchQuality(p, nArg, enc);
81177 if( score>bestScore ){
81178 pBest = p;
81179 bestScore = score;
81181 p = p->pNext;
81185 /* If the createFlag parameter is true and the search did not reveal an
81186 ** exact match for the name, number of arguments and encoding, then add a
81187 ** new entry to the hash table and return it.
81189 if( createFlag && (bestScore<6 || pBest->nArg!=nArg) &&
81190 (pBest = sqlite3DbMallocZero(db, sizeof(*pBest)+nName+1))!=0 ){
81191 pBest->zName = (char *)&pBest[1];
81192 pBest->nArg = (u16)nArg;
81193 pBest->iPrefEnc = enc;
81194 memcpy(pBest->zName, zName, nName);
81195 pBest->zName[nName] = 0;
81196 sqlite3FuncDefInsert(&db->aFunc, pBest);
81199 if( pBest && (pBest->xStep || pBest->xFunc || createFlag) ){
81200 return pBest;
81202 return 0;
81206 ** Free all resources held by the schema structure. The void* argument points
81207 ** at a Schema struct. This function does not call sqlite3DbFree(db, ) on the
81208 ** pointer itself, it just cleans up subsidiary resources (i.e. the contents
81209 ** of the schema hash tables).
81211 ** The Schema.cache_size variable is not cleared.
81213 SQLITE_PRIVATE void sqlite3SchemaClear(void *p){
81214 Hash temp1;
81215 Hash temp2;
81216 HashElem *pElem;
81217 Schema *pSchema = (Schema *)p;
81219 temp1 = pSchema->tblHash;
81220 temp2 = pSchema->trigHash;
81221 sqlite3HashInit(&pSchema->trigHash);
81222 sqlite3HashClear(&pSchema->idxHash);
81223 for(pElem=sqliteHashFirst(&temp2); pElem; pElem=sqliteHashNext(pElem)){
81224 sqlite3DeleteTrigger(0, (Trigger*)sqliteHashData(pElem));
81226 sqlite3HashClear(&temp2);
81227 sqlite3HashInit(&pSchema->tblHash);
81228 for(pElem=sqliteHashFirst(&temp1); pElem; pElem=sqliteHashNext(pElem)){
81229 Table *pTab = sqliteHashData(pElem);
81230 sqlite3DeleteTable(0, pTab);
81232 sqlite3HashClear(&temp1);
81233 sqlite3HashClear(&pSchema->fkeyHash);
81234 pSchema->pSeqTab = 0;
81235 if( pSchema->flags & DB_SchemaLoaded ){
81236 pSchema->iGeneration++;
81237 pSchema->flags &= ~DB_SchemaLoaded;
81242 ** Find and return the schema associated with a BTree. Create
81243 ** a new one if necessary.
81245 SQLITE_PRIVATE Schema *sqlite3SchemaGet(sqlite3 *db, Btree *pBt){
81246 Schema * p;
81247 if( pBt ){
81248 p = (Schema *)sqlite3BtreeSchema(pBt, sizeof(Schema), sqlite3SchemaClear);
81249 }else{
81250 p = (Schema *)sqlite3DbMallocZero(0, sizeof(Schema));
81252 if( !p ){
81253 db->mallocFailed = 1;
81254 }else if ( 0==p->file_format ){
81255 sqlite3HashInit(&p->tblHash);
81256 sqlite3HashInit(&p->idxHash);
81257 sqlite3HashInit(&p->trigHash);
81258 sqlite3HashInit(&p->fkeyHash);
81259 p->enc = SQLITE_UTF8;
81261 return p;
81264 /************** End of callback.c ********************************************/
81265 /************** Begin file delete.c ******************************************/
81267 ** 2001 September 15
81269 ** The author disclaims copyright to this source code. In place of
81270 ** a legal notice, here is a blessing:
81272 ** May you do good and not evil.
81273 ** May you find forgiveness for yourself and forgive others.
81274 ** May you share freely, never taking more than you give.
81276 *************************************************************************
81277 ** This file contains C code routines that are called by the parser
81278 ** in order to generate code for DELETE FROM statements.
81282 ** While a SrcList can in general represent multiple tables and subqueries
81283 ** (as in the FROM clause of a SELECT statement) in this case it contains
81284 ** the name of a single table, as one might find in an INSERT, DELETE,
81285 ** or UPDATE statement. Look up that table in the symbol table and
81286 ** return a pointer. Set an error message and return NULL if the table
81287 ** name is not found or if any other error occurs.
81289 ** The following fields are initialized appropriate in pSrc:
81291 ** pSrc->a[0].pTab Pointer to the Table object
81292 ** pSrc->a[0].pIndex Pointer to the INDEXED BY index, if there is one
81295 SQLITE_PRIVATE Table *sqlite3SrcListLookup(Parse *pParse, SrcList *pSrc){
81296 struct SrcList_item *pItem = pSrc->a;
81297 Table *pTab;
81298 assert( pItem && pSrc->nSrc==1 );
81299 pTab = sqlite3LocateTable(pParse, 0, pItem->zName, pItem->zDatabase);
81300 sqlite3DeleteTable(pParse->db, pItem->pTab);
81301 pItem->pTab = pTab;
81302 if( pTab ){
81303 pTab->nRef++;
81305 if( sqlite3IndexedByLookup(pParse, pItem) ){
81306 pTab = 0;
81308 return pTab;
81312 ** Check to make sure the given table is writable. If it is not
81313 ** writable, generate an error message and return 1. If it is
81314 ** writable return 0;
81316 SQLITE_PRIVATE int sqlite3IsReadOnly(Parse *pParse, Table *pTab, int viewOk){
81317 /* A table is not writable under the following circumstances:
81319 ** 1) It is a virtual table and no implementation of the xUpdate method
81320 ** has been provided, or
81321 ** 2) It is a system table (i.e. sqlite_master), this call is not
81322 ** part of a nested parse and writable_schema pragma has not
81323 ** been specified.
81325 ** In either case leave an error message in pParse and return non-zero.
81327 if( ( IsVirtual(pTab)
81328 && sqlite3GetVTable(pParse->db, pTab)->pMod->pModule->xUpdate==0 )
81329 || ( (pTab->tabFlags & TF_Readonly)!=0
81330 && (pParse->db->flags & SQLITE_WriteSchema)==0
81331 && pParse->nested==0 )
81333 sqlite3ErrorMsg(pParse, "table %s may not be modified", pTab->zName);
81334 return 1;
81337 #ifndef SQLITE_OMIT_VIEW
81338 if( !viewOk && pTab->pSelect ){
81339 sqlite3ErrorMsg(pParse,"cannot modify %s because it is a view",pTab->zName);
81340 return 1;
81342 #endif
81343 return 0;
81347 #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
81349 ** Evaluate a view and store its result in an ephemeral table. The
81350 ** pWhere argument is an optional WHERE clause that restricts the
81351 ** set of rows in the view that are to be added to the ephemeral table.
81353 SQLITE_PRIVATE void sqlite3MaterializeView(
81354 Parse *pParse, /* Parsing context */
81355 Table *pView, /* View definition */
81356 Expr *pWhere, /* Optional WHERE clause to be added */
81357 int iCur /* Cursor number for ephemerial table */
81359 SelectDest dest;
81360 Select *pDup;
81361 sqlite3 *db = pParse->db;
81363 pDup = sqlite3SelectDup(db, pView->pSelect, 0);
81364 if( pWhere ){
81365 SrcList *pFrom;
81367 pWhere = sqlite3ExprDup(db, pWhere, 0);
81368 pFrom = sqlite3SrcListAppend(db, 0, 0, 0);
81369 if( pFrom ){
81370 assert( pFrom->nSrc==1 );
81371 pFrom->a[0].zAlias = sqlite3DbStrDup(db, pView->zName);
81372 pFrom->a[0].pSelect = pDup;
81373 assert( pFrom->a[0].pOn==0 );
81374 assert( pFrom->a[0].pUsing==0 );
81375 }else{
81376 sqlite3SelectDelete(db, pDup);
81378 pDup = sqlite3SelectNew(pParse, 0, pFrom, pWhere, 0, 0, 0, 0, 0, 0);
81380 sqlite3SelectDestInit(&dest, SRT_EphemTab, iCur);
81381 sqlite3Select(pParse, pDup, &dest);
81382 sqlite3SelectDelete(db, pDup);
81384 #endif /* !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER) */
81386 #if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY)
81388 ** Generate an expression tree to implement the WHERE, ORDER BY,
81389 ** and LIMIT/OFFSET portion of DELETE and UPDATE statements.
81391 ** DELETE FROM table_wxyz WHERE a<5 ORDER BY a LIMIT 1;
81392 ** \__________________________/
81393 ** pLimitWhere (pInClause)
81395 SQLITE_PRIVATE Expr *sqlite3LimitWhere(
81396 Parse *pParse, /* The parser context */
81397 SrcList *pSrc, /* the FROM clause -- which tables to scan */
81398 Expr *pWhere, /* The WHERE clause. May be null */
81399 ExprList *pOrderBy, /* The ORDER BY clause. May be null */
81400 Expr *pLimit, /* The LIMIT clause. May be null */
81401 Expr *pOffset, /* The OFFSET clause. May be null */
81402 char *zStmtType /* Either DELETE or UPDATE. For error messages. */
81404 Expr *pWhereRowid = NULL; /* WHERE rowid .. */
81405 Expr *pInClause = NULL; /* WHERE rowid IN ( select ) */
81406 Expr *pSelectRowid = NULL; /* SELECT rowid ... */
81407 ExprList *pEList = NULL; /* Expression list contaning only pSelectRowid */
81408 SrcList *pSelectSrc = NULL; /* SELECT rowid FROM x ... (dup of pSrc) */
81409 Select *pSelect = NULL; /* Complete SELECT tree */
81411 /* Check that there isn't an ORDER BY without a LIMIT clause.
81413 if( pOrderBy && (pLimit == 0) ) {
81414 sqlite3ErrorMsg(pParse, "ORDER BY without LIMIT on %s", zStmtType);
81415 pParse->parseError = 1;
81416 goto limit_where_cleanup_2;
81419 /* We only need to generate a select expression if there
81420 ** is a limit/offset term to enforce.
81422 if( pLimit == 0 ) {
81423 /* if pLimit is null, pOffset will always be null as well. */
81424 assert( pOffset == 0 );
81425 return pWhere;
81428 /* Generate a select expression tree to enforce the limit/offset
81429 ** term for the DELETE or UPDATE statement. For example:
81430 ** DELETE FROM table_a WHERE col1=1 ORDER BY col2 LIMIT 1 OFFSET 1
81431 ** becomes:
81432 ** DELETE FROM table_a WHERE rowid IN (
81433 ** SELECT rowid FROM table_a WHERE col1=1 ORDER BY col2 LIMIT 1 OFFSET 1
81434 ** );
81437 pSelectRowid = sqlite3PExpr(pParse, TK_ROW, 0, 0, 0);
81438 if( pSelectRowid == 0 ) goto limit_where_cleanup_2;
81439 pEList = sqlite3ExprListAppend(pParse, 0, pSelectRowid);
81440 if( pEList == 0 ) goto limit_where_cleanup_2;
81442 /* duplicate the FROM clause as it is needed by both the DELETE/UPDATE tree
81443 ** and the SELECT subtree. */
81444 pSelectSrc = sqlite3SrcListDup(pParse->db, pSrc, 0);
81445 if( pSelectSrc == 0 ) {
81446 sqlite3ExprListDelete(pParse->db, pEList);
81447 goto limit_where_cleanup_2;
81450 /* generate the SELECT expression tree. */
81451 pSelect = sqlite3SelectNew(pParse,pEList,pSelectSrc,pWhere,0,0,
81452 pOrderBy,0,pLimit,pOffset);
81453 if( pSelect == 0 ) return 0;
81455 /* now generate the new WHERE rowid IN clause for the DELETE/UDPATE */
81456 pWhereRowid = sqlite3PExpr(pParse, TK_ROW, 0, 0, 0);
81457 if( pWhereRowid == 0 ) goto limit_where_cleanup_1;
81458 pInClause = sqlite3PExpr(pParse, TK_IN, pWhereRowid, 0, 0);
81459 if( pInClause == 0 ) goto limit_where_cleanup_1;
81461 pInClause->x.pSelect = pSelect;
81462 pInClause->flags |= EP_xIsSelect;
81463 sqlite3ExprSetHeight(pParse, pInClause);
81464 return pInClause;
81466 /* something went wrong. clean up anything allocated. */
81467 limit_where_cleanup_1:
81468 sqlite3SelectDelete(pParse->db, pSelect);
81469 return 0;
81471 limit_where_cleanup_2:
81472 sqlite3ExprDelete(pParse->db, pWhere);
81473 sqlite3ExprListDelete(pParse->db, pOrderBy);
81474 sqlite3ExprDelete(pParse->db, pLimit);
81475 sqlite3ExprDelete(pParse->db, pOffset);
81476 return 0;
81478 #endif /* defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY) */
81481 ** Generate code for a DELETE FROM statement.
81483 ** DELETE FROM table_wxyz WHERE a<5 AND b NOT NULL;
81484 ** \________/ \________________/
81485 ** pTabList pWhere
81487 SQLITE_PRIVATE void sqlite3DeleteFrom(
81488 Parse *pParse, /* The parser context */
81489 SrcList *pTabList, /* The table from which we should delete things */
81490 Expr *pWhere /* The WHERE clause. May be null */
81492 Vdbe *v; /* The virtual database engine */
81493 Table *pTab; /* The table from which records will be deleted */
81494 const char *zDb; /* Name of database holding pTab */
81495 int end, addr = 0; /* A couple addresses of generated code */
81496 int i; /* Loop counter */
81497 WhereInfo *pWInfo; /* Information about the WHERE clause */
81498 Index *pIdx; /* For looping over indices of the table */
81499 int iCur; /* VDBE Cursor number for pTab */
81500 sqlite3 *db; /* Main database structure */
81501 AuthContext sContext; /* Authorization context */
81502 NameContext sNC; /* Name context to resolve expressions in */
81503 int iDb; /* Database number */
81504 int memCnt = -1; /* Memory cell used for change counting */
81505 int rcauth; /* Value returned by authorization callback */
81507 #ifndef SQLITE_OMIT_TRIGGER
81508 int isView; /* True if attempting to delete from a view */
81509 Trigger *pTrigger; /* List of table triggers, if required */
81510 #endif
81512 memset(&sContext, 0, sizeof(sContext));
81513 db = pParse->db;
81514 if( pParse->nErr || db->mallocFailed ){
81515 goto delete_from_cleanup;
81517 assert( pTabList->nSrc==1 );
81519 /* Locate the table which we want to delete. This table has to be
81520 ** put in an SrcList structure because some of the subroutines we
81521 ** will be calling are designed to work with multiple tables and expect
81522 ** an SrcList* parameter instead of just a Table* parameter.
81524 pTab = sqlite3SrcListLookup(pParse, pTabList);
81525 if( pTab==0 ) goto delete_from_cleanup;
81527 /* Figure out if we have any triggers and if the table being
81528 ** deleted from is a view
81530 #ifndef SQLITE_OMIT_TRIGGER
81531 pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
81532 isView = pTab->pSelect!=0;
81533 #else
81534 # define pTrigger 0
81535 # define isView 0
81536 #endif
81537 #ifdef SQLITE_OMIT_VIEW
81538 # undef isView
81539 # define isView 0
81540 #endif
81542 /* If pTab is really a view, make sure it has been initialized.
81544 if( sqlite3ViewGetColumnNames(pParse, pTab) ){
81545 goto delete_from_cleanup;
81548 if( sqlite3IsReadOnly(pParse, pTab, (pTrigger?1:0)) ){
81549 goto delete_from_cleanup;
81551 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
81552 assert( iDb<db->nDb );
81553 zDb = db->aDb[iDb].zName;
81554 rcauth = sqlite3AuthCheck(pParse, SQLITE_DELETE, pTab->zName, 0, zDb);
81555 assert( rcauth==SQLITE_OK || rcauth==SQLITE_DENY || rcauth==SQLITE_IGNORE );
81556 if( rcauth==SQLITE_DENY ){
81557 goto delete_from_cleanup;
81559 assert(!isView || pTrigger);
81561 /* Assign cursor number to the table and all its indices.
81563 assert( pTabList->nSrc==1 );
81564 iCur = pTabList->a[0].iCursor = pParse->nTab++;
81565 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
81566 pParse->nTab++;
81569 /* Start the view context
81571 if( isView ){
81572 sqlite3AuthContextPush(pParse, &sContext, pTab->zName);
81575 /* Begin generating code.
81577 v = sqlite3GetVdbe(pParse);
81578 if( v==0 ){
81579 goto delete_from_cleanup;
81581 if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
81582 sqlite3BeginWriteOperation(pParse, 1, iDb);
81584 /* If we are trying to delete from a view, realize that view into
81585 ** a ephemeral table.
81587 #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
81588 if( isView ){
81589 sqlite3MaterializeView(pParse, pTab, pWhere, iCur);
81591 #endif
81593 /* Resolve the column names in the WHERE clause.
81595 memset(&sNC, 0, sizeof(sNC));
81596 sNC.pParse = pParse;
81597 sNC.pSrcList = pTabList;
81598 if( sqlite3ResolveExprNames(&sNC, pWhere) ){
81599 goto delete_from_cleanup;
81602 /* Initialize the counter of the number of rows deleted, if
81603 ** we are counting rows.
81605 if( db->flags & SQLITE_CountRows ){
81606 memCnt = ++pParse->nMem;
81607 sqlite3VdbeAddOp2(v, OP_Integer, 0, memCnt);
81610 #ifndef SQLITE_OMIT_TRUNCATE_OPTIMIZATION
81611 /* Special case: A DELETE without a WHERE clause deletes everything.
81612 ** It is easier just to erase the whole table. Prior to version 3.6.5,
81613 ** this optimization caused the row change count (the value returned by
81614 ** API function sqlite3_count_changes) to be set incorrectly. */
81615 if( rcauth==SQLITE_OK && pWhere==0 && !pTrigger && !IsVirtual(pTab)
81616 && 0==sqlite3FkRequired(pParse, pTab, 0, 0)
81618 assert( !isView );
81619 sqlite3VdbeAddOp4(v, OP_Clear, pTab->tnum, iDb, memCnt,
81620 pTab->zName, P4_STATIC);
81621 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
81622 assert( pIdx->pSchema==pTab->pSchema );
81623 sqlite3VdbeAddOp2(v, OP_Clear, pIdx->tnum, iDb);
81625 }else
81626 #endif /* SQLITE_OMIT_TRUNCATE_OPTIMIZATION */
81627 /* The usual case: There is a WHERE clause so we have to scan through
81628 ** the table and pick which records to delete.
81631 int iRowSet = ++pParse->nMem; /* Register for rowset of rows to delete */
81632 int iRowid = ++pParse->nMem; /* Used for storing rowid values. */
81633 int regRowid; /* Actual register containing rowids */
81635 /* Collect rowids of every row to be deleted.
81637 sqlite3VdbeAddOp2(v, OP_Null, 0, iRowSet);
81638 pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere,0,WHERE_DUPLICATES_OK);
81639 if( pWInfo==0 ) goto delete_from_cleanup;
81640 regRowid = sqlite3ExprCodeGetColumn(pParse, pTab, -1, iCur, iRowid);
81641 sqlite3VdbeAddOp2(v, OP_RowSetAdd, iRowSet, regRowid);
81642 if( db->flags & SQLITE_CountRows ){
81643 sqlite3VdbeAddOp2(v, OP_AddImm, memCnt, 1);
81645 sqlite3WhereEnd(pWInfo);
81647 /* Delete every item whose key was written to the list during the
81648 ** database scan. We have to delete items after the scan is complete
81649 ** because deleting an item can change the scan order. */
81650 end = sqlite3VdbeMakeLabel(v);
81652 /* Unless this is a view, open cursors for the table we are
81653 ** deleting from and all its indices. If this is a view, then the
81654 ** only effect this statement has is to fire the INSTEAD OF
81655 ** triggers. */
81656 if( !isView ){
81657 sqlite3OpenTableAndIndices(pParse, pTab, iCur, OP_OpenWrite);
81660 addr = sqlite3VdbeAddOp3(v, OP_RowSetRead, iRowSet, end, iRowid);
81662 /* Delete the row */
81663 #ifndef SQLITE_OMIT_VIRTUALTABLE
81664 if( IsVirtual(pTab) ){
81665 const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
81666 sqlite3VtabMakeWritable(pParse, pTab);
81667 sqlite3VdbeAddOp4(v, OP_VUpdate, 0, 1, iRowid, pVTab, P4_VTAB);
81668 sqlite3MayAbort(pParse);
81669 }else
81670 #endif
81672 int count = (pParse->nested==0); /* True to count changes */
81673 sqlite3GenerateRowDelete(pParse, pTab, iCur, iRowid, count, pTrigger, OE_Default);
81676 /* End of the delete loop */
81677 sqlite3VdbeAddOp2(v, OP_Goto, 0, addr);
81678 sqlite3VdbeResolveLabel(v, end);
81680 /* Close the cursors open on the table and its indexes. */
81681 if( !isView && !IsVirtual(pTab) ){
81682 for(i=1, pIdx=pTab->pIndex; pIdx; i++, pIdx=pIdx->pNext){
81683 sqlite3VdbeAddOp2(v, OP_Close, iCur + i, pIdx->tnum);
81685 sqlite3VdbeAddOp1(v, OP_Close, iCur);
81689 /* Update the sqlite_sequence table by storing the content of the
81690 ** maximum rowid counter values recorded while inserting into
81691 ** autoincrement tables.
81693 if( pParse->nested==0 && pParse->pTriggerTab==0 ){
81694 sqlite3AutoincrementEnd(pParse);
81697 /* Return the number of rows that were deleted. If this routine is
81698 ** generating code because of a call to sqlite3NestedParse(), do not
81699 ** invoke the callback function.
81701 if( (db->flags&SQLITE_CountRows) && !pParse->nested && !pParse->pTriggerTab ){
81702 sqlite3VdbeAddOp2(v, OP_ResultRow, memCnt, 1);
81703 sqlite3VdbeSetNumCols(v, 1);
81704 sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows deleted", SQLITE_STATIC);
81707 delete_from_cleanup:
81708 sqlite3AuthContextPop(&sContext);
81709 sqlite3SrcListDelete(db, pTabList);
81710 sqlite3ExprDelete(db, pWhere);
81711 return;
81713 /* Make sure "isView" and other macros defined above are undefined. Otherwise
81714 ** thely may interfere with compilation of other functions in this file
81715 ** (or in another file, if this file becomes part of the amalgamation). */
81716 #ifdef isView
81717 #undef isView
81718 #endif
81719 #ifdef pTrigger
81720 #undef pTrigger
81721 #endif
81724 ** This routine generates VDBE code that causes a single row of a
81725 ** single table to be deleted.
81727 ** The VDBE must be in a particular state when this routine is called.
81728 ** These are the requirements:
81730 ** 1. A read/write cursor pointing to pTab, the table containing the row
81731 ** to be deleted, must be opened as cursor number $iCur.
81733 ** 2. Read/write cursors for all indices of pTab must be open as
81734 ** cursor number base+i for the i-th index.
81736 ** 3. The record number of the row to be deleted must be stored in
81737 ** memory cell iRowid.
81739 ** This routine generates code to remove both the table record and all
81740 ** index entries that point to that record.
81742 SQLITE_PRIVATE void sqlite3GenerateRowDelete(
81743 Parse *pParse, /* Parsing context */
81744 Table *pTab, /* Table containing the row to be deleted */
81745 int iCur, /* Cursor number for the table */
81746 int iRowid, /* Memory cell that contains the rowid to delete */
81747 int count, /* If non-zero, increment the row change counter */
81748 Trigger *pTrigger, /* List of triggers to (potentially) fire */
81749 int onconf /* Default ON CONFLICT policy for triggers */
81751 Vdbe *v = pParse->pVdbe; /* Vdbe */
81752 int iOld = 0; /* First register in OLD.* array */
81753 int iLabel; /* Label resolved to end of generated code */
81755 /* Vdbe is guaranteed to have been allocated by this stage. */
81756 assert( v );
81758 /* Seek cursor iCur to the row to delete. If this row no longer exists
81759 ** (this can happen if a trigger program has already deleted it), do
81760 ** not attempt to delete it or fire any DELETE triggers. */
81761 iLabel = sqlite3VdbeMakeLabel(v);
81762 sqlite3VdbeAddOp3(v, OP_NotExists, iCur, iLabel, iRowid);
81764 /* If there are any triggers to fire, allocate a range of registers to
81765 ** use for the old.* references in the triggers. */
81766 if( sqlite3FkRequired(pParse, pTab, 0, 0) || pTrigger ){
81767 u32 mask; /* Mask of OLD.* columns in use */
81768 int iCol; /* Iterator used while populating OLD.* */
81770 /* TODO: Could use temporary registers here. Also could attempt to
81771 ** avoid copying the contents of the rowid register. */
81772 mask = sqlite3TriggerColmask(
81773 pParse, pTrigger, 0, 0, TRIGGER_BEFORE|TRIGGER_AFTER, pTab, onconf
81775 mask |= sqlite3FkOldmask(pParse, pTab);
81776 iOld = pParse->nMem+1;
81777 pParse->nMem += (1 + pTab->nCol);
81779 /* Populate the OLD.* pseudo-table register array. These values will be
81780 ** used by any BEFORE and AFTER triggers that exist. */
81781 sqlite3VdbeAddOp2(v, OP_Copy, iRowid, iOld);
81782 for(iCol=0; iCol<pTab->nCol; iCol++){
81783 if( mask==0xffffffff || mask&(1<<iCol) ){
81784 sqlite3ExprCodeGetColumnOfTable(v, pTab, iCur, iCol, iOld+iCol+1);
81788 /* Invoke BEFORE DELETE trigger programs. */
81789 sqlite3CodeRowTrigger(pParse, pTrigger,
81790 TK_DELETE, 0, TRIGGER_BEFORE, pTab, iOld, onconf, iLabel
81793 /* Seek the cursor to the row to be deleted again. It may be that
81794 ** the BEFORE triggers coded above have already removed the row
81795 ** being deleted. Do not attempt to delete the row a second time, and
81796 ** do not fire AFTER triggers. */
81797 sqlite3VdbeAddOp3(v, OP_NotExists, iCur, iLabel, iRowid);
81799 /* Do FK processing. This call checks that any FK constraints that
81800 ** refer to this table (i.e. constraints attached to other tables)
81801 ** are not violated by deleting this row. */
81802 sqlite3FkCheck(pParse, pTab, iOld, 0);
81805 /* Delete the index and table entries. Skip this step if pTab is really
81806 ** a view (in which case the only effect of the DELETE statement is to
81807 ** fire the INSTEAD OF triggers). */
81808 if( pTab->pSelect==0 ){
81809 sqlite3GenerateRowIndexDelete(pParse, pTab, iCur, 0);
81810 sqlite3VdbeAddOp2(v, OP_Delete, iCur, (count?OPFLAG_NCHANGE:0));
81811 if( count ){
81812 sqlite3VdbeChangeP4(v, -1, pTab->zName, P4_TRANSIENT);
81816 /* Do any ON CASCADE, SET NULL or SET DEFAULT operations required to
81817 ** handle rows (possibly in other tables) that refer via a foreign key
81818 ** to the row just deleted. */
81819 sqlite3FkActions(pParse, pTab, 0, iOld);
81821 /* Invoke AFTER DELETE trigger programs. */
81822 sqlite3CodeRowTrigger(pParse, pTrigger,
81823 TK_DELETE, 0, TRIGGER_AFTER, pTab, iOld, onconf, iLabel
81826 /* Jump here if the row had already been deleted before any BEFORE
81827 ** trigger programs were invoked. Or if a trigger program throws a
81828 ** RAISE(IGNORE) exception. */
81829 sqlite3VdbeResolveLabel(v, iLabel);
81833 ** This routine generates VDBE code that causes the deletion of all
81834 ** index entries associated with a single row of a single table.
81836 ** The VDBE must be in a particular state when this routine is called.
81837 ** These are the requirements:
81839 ** 1. A read/write cursor pointing to pTab, the table containing the row
81840 ** to be deleted, must be opened as cursor number "iCur".
81842 ** 2. Read/write cursors for all indices of pTab must be open as
81843 ** cursor number iCur+i for the i-th index.
81845 ** 3. The "iCur" cursor must be pointing to the row that is to be
81846 ** deleted.
81848 SQLITE_PRIVATE void sqlite3GenerateRowIndexDelete(
81849 Parse *pParse, /* Parsing and code generating context */
81850 Table *pTab, /* Table containing the row to be deleted */
81851 int iCur, /* Cursor number for the table */
81852 int *aRegIdx /* Only delete if aRegIdx!=0 && aRegIdx[i]>0 */
81854 int i;
81855 Index *pIdx;
81856 int r1;
81858 for(i=1, pIdx=pTab->pIndex; pIdx; i++, pIdx=pIdx->pNext){
81859 if( aRegIdx!=0 && aRegIdx[i-1]==0 ) continue;
81860 r1 = sqlite3GenerateIndexKey(pParse, pIdx, iCur, 0, 0);
81861 sqlite3VdbeAddOp3(pParse->pVdbe, OP_IdxDelete, iCur+i, r1,pIdx->nColumn+1);
81866 ** Generate code that will assemble an index key and put it in register
81867 ** regOut. The key with be for index pIdx which is an index on pTab.
81868 ** iCur is the index of a cursor open on the pTab table and pointing to
81869 ** the entry that needs indexing.
81871 ** Return a register number which is the first in a block of
81872 ** registers that holds the elements of the index key. The
81873 ** block of registers has already been deallocated by the time
81874 ** this routine returns.
81876 SQLITE_PRIVATE int sqlite3GenerateIndexKey(
81877 Parse *pParse, /* Parsing context */
81878 Index *pIdx, /* The index for which to generate a key */
81879 int iCur, /* Cursor number for the pIdx->pTable table */
81880 int regOut, /* Write the new index key to this register */
81881 int doMakeRec /* Run the OP_MakeRecord instruction if true */
81883 Vdbe *v = pParse->pVdbe;
81884 int j;
81885 Table *pTab = pIdx->pTable;
81886 int regBase;
81887 int nCol;
81889 nCol = pIdx->nColumn;
81890 regBase = sqlite3GetTempRange(pParse, nCol+1);
81891 sqlite3VdbeAddOp2(v, OP_Rowid, iCur, regBase+nCol);
81892 for(j=0; j<nCol; j++){
81893 int idx = pIdx->aiColumn[j];
81894 if( idx==pTab->iPKey ){
81895 sqlite3VdbeAddOp2(v, OP_SCopy, regBase+nCol, regBase+j);
81896 }else{
81897 sqlite3VdbeAddOp3(v, OP_Column, iCur, idx, regBase+j);
81898 sqlite3ColumnDefault(v, pTab, idx, -1);
81901 if( doMakeRec ){
81902 sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nCol+1, regOut);
81903 sqlite3VdbeChangeP4(v, -1, sqlite3IndexAffinityStr(v, pIdx), P4_TRANSIENT);
81905 sqlite3ReleaseTempRange(pParse, regBase, nCol+1);
81906 return regBase;
81909 /************** End of delete.c **********************************************/
81910 /************** Begin file func.c ********************************************/
81912 ** 2002 February 23
81914 ** The author disclaims copyright to this source code. In place of
81915 ** a legal notice, here is a blessing:
81917 ** May you do good and not evil.
81918 ** May you find forgiveness for yourself and forgive others.
81919 ** May you share freely, never taking more than you give.
81921 *************************************************************************
81922 ** This file contains the C functions that implement various SQL
81923 ** functions of SQLite.
81925 ** There is only one exported symbol in this file - the function
81926 ** sqliteRegisterBuildinFunctions() found at the bottom of the file.
81927 ** All other code has file scope.
81931 ** Return the collating function associated with a function.
81933 static CollSeq *sqlite3GetFuncCollSeq(sqlite3_context *context){
81934 return context->pColl;
81938 ** Implementation of the non-aggregate min() and max() functions
81940 static void minmaxFunc(
81941 sqlite3_context *context,
81942 int argc,
81943 sqlite3_value **argv
81945 int i;
81946 int mask; /* 0 for min() or 0xffffffff for max() */
81947 int iBest;
81948 CollSeq *pColl;
81950 assert( argc>1 );
81951 mask = sqlite3_user_data(context)==0 ? 0 : -1;
81952 pColl = sqlite3GetFuncCollSeq(context);
81953 assert( pColl );
81954 assert( mask==-1 || mask==0 );
81955 iBest = 0;
81956 if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
81957 for(i=1; i<argc; i++){
81958 if( sqlite3_value_type(argv[i])==SQLITE_NULL ) return;
81959 if( (sqlite3MemCompare(argv[iBest], argv[i], pColl)^mask)>=0 ){
81960 testcase( mask==0 );
81961 iBest = i;
81964 sqlite3_result_value(context, argv[iBest]);
81968 ** Return the type of the argument.
81970 static void typeofFunc(
81971 sqlite3_context *context,
81972 int NotUsed,
81973 sqlite3_value **argv
81975 const char *z = 0;
81976 UNUSED_PARAMETER(NotUsed);
81977 switch( sqlite3_value_type(argv[0]) ){
81978 case SQLITE_INTEGER: z = "integer"; break;
81979 case SQLITE_TEXT: z = "text"; break;
81980 case SQLITE_FLOAT: z = "real"; break;
81981 case SQLITE_BLOB: z = "blob"; break;
81982 default: z = "null"; break;
81984 sqlite3_result_text(context, z, -1, SQLITE_STATIC);
81989 ** Implementation of the length() function
81991 static void lengthFunc(
81992 sqlite3_context *context,
81993 int argc,
81994 sqlite3_value **argv
81996 int len;
81998 assert( argc==1 );
81999 UNUSED_PARAMETER(argc);
82000 switch( sqlite3_value_type(argv[0]) ){
82001 case SQLITE_BLOB:
82002 case SQLITE_INTEGER:
82003 case SQLITE_FLOAT: {
82004 sqlite3_result_int(context, sqlite3_value_bytes(argv[0]));
82005 break;
82007 case SQLITE_TEXT: {
82008 const unsigned char *z = sqlite3_value_text(argv[0]);
82009 if( z==0 ) return;
82010 len = 0;
82011 while( *z ){
82012 len++;
82013 SQLITE_SKIP_UTF8(z);
82015 sqlite3_result_int(context, len);
82016 break;
82018 default: {
82019 sqlite3_result_null(context);
82020 break;
82026 ** Implementation of the abs() function.
82028 ** IMP: R-23979-26855 The abs(X) function returns the absolute value of
82029 ** the numeric argument X.
82031 static void absFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
82032 assert( argc==1 );
82033 UNUSED_PARAMETER(argc);
82034 switch( sqlite3_value_type(argv[0]) ){
82035 case SQLITE_INTEGER: {
82036 i64 iVal = sqlite3_value_int64(argv[0]);
82037 if( iVal<0 ){
82038 if( (iVal<<1)==0 ){
82039 /* IMP: R-35460-15084 If X is the integer -9223372036854775807 then
82040 ** abs(X) throws an integer overflow error since there is no
82041 ** equivalent positive 64-bit two complement value. */
82042 sqlite3_result_error(context, "integer overflow", -1);
82043 return;
82045 iVal = -iVal;
82047 sqlite3_result_int64(context, iVal);
82048 break;
82050 case SQLITE_NULL: {
82051 /* IMP: R-37434-19929 Abs(X) returns NULL if X is NULL. */
82052 sqlite3_result_null(context);
82053 break;
82055 default: {
82056 /* Because sqlite3_value_double() returns 0.0 if the argument is not
82057 ** something that can be converted into a number, we have:
82058 ** IMP: R-57326-31541 Abs(X) return 0.0 if X is a string or blob that
82059 ** cannot be converted to a numeric value.
82061 double rVal = sqlite3_value_double(argv[0]);
82062 if( rVal<0 ) rVal = -rVal;
82063 sqlite3_result_double(context, rVal);
82064 break;
82070 ** Implementation of the substr() function.
82072 ** substr(x,p1,p2) returns p2 characters of x[] beginning with p1.
82073 ** p1 is 1-indexed. So substr(x,1,1) returns the first character
82074 ** of x. If x is text, then we actually count UTF-8 characters.
82075 ** If x is a blob, then we count bytes.
82077 ** If p1 is negative, then we begin abs(p1) from the end of x[].
82079 ** If p2 is negative, return the p2 characters preceeding p1.
82081 static void substrFunc(
82082 sqlite3_context *context,
82083 int argc,
82084 sqlite3_value **argv
82086 const unsigned char *z;
82087 const unsigned char *z2;
82088 int len;
82089 int p0type;
82090 i64 p1, p2;
82091 int negP2 = 0;
82093 assert( argc==3 || argc==2 );
82094 if( sqlite3_value_type(argv[1])==SQLITE_NULL
82095 || (argc==3 && sqlite3_value_type(argv[2])==SQLITE_NULL)
82097 return;
82099 p0type = sqlite3_value_type(argv[0]);
82100 p1 = sqlite3_value_int(argv[1]);
82101 if( p0type==SQLITE_BLOB ){
82102 len = sqlite3_value_bytes(argv[0]);
82103 z = sqlite3_value_blob(argv[0]);
82104 if( z==0 ) return;
82105 assert( len==sqlite3_value_bytes(argv[0]) );
82106 }else{
82107 z = sqlite3_value_text(argv[0]);
82108 if( z==0 ) return;
82109 len = 0;
82110 if( p1<0 ){
82111 for(z2=z; *z2; len++){
82112 SQLITE_SKIP_UTF8(z2);
82116 if( argc==3 ){
82117 p2 = sqlite3_value_int(argv[2]);
82118 if( p2<0 ){
82119 p2 = -p2;
82120 negP2 = 1;
82122 }else{
82123 p2 = sqlite3_context_db_handle(context)->aLimit[SQLITE_LIMIT_LENGTH];
82125 if( p1<0 ){
82126 p1 += len;
82127 if( p1<0 ){
82128 p2 += p1;
82129 if( p2<0 ) p2 = 0;
82130 p1 = 0;
82132 }else if( p1>0 ){
82133 p1--;
82134 }else if( p2>0 ){
82135 p2--;
82137 if( negP2 ){
82138 p1 -= p2;
82139 if( p1<0 ){
82140 p2 += p1;
82141 p1 = 0;
82144 assert( p1>=0 && p2>=0 );
82145 if( p0type!=SQLITE_BLOB ){
82146 while( *z && p1 ){
82147 SQLITE_SKIP_UTF8(z);
82148 p1--;
82150 for(z2=z; *z2 && p2; p2--){
82151 SQLITE_SKIP_UTF8(z2);
82153 sqlite3_result_text(context, (char*)z, (int)(z2-z), SQLITE_TRANSIENT);
82154 }else{
82155 if( p1+p2>len ){
82156 p2 = len-p1;
82157 if( p2<0 ) p2 = 0;
82159 sqlite3_result_blob(context, (char*)&z[p1], (int)p2, SQLITE_TRANSIENT);
82164 ** Implementation of the round() function
82166 #ifndef SQLITE_OMIT_FLOATING_POINT
82167 static void roundFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
82168 int n = 0;
82169 double r;
82170 char *zBuf;
82171 assert( argc==1 || argc==2 );
82172 if( argc==2 ){
82173 if( SQLITE_NULL==sqlite3_value_type(argv[1]) ) return;
82174 n = sqlite3_value_int(argv[1]);
82175 if( n>30 ) n = 30;
82176 if( n<0 ) n = 0;
82178 if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
82179 r = sqlite3_value_double(argv[0]);
82180 /* If Y==0 and X will fit in a 64-bit int,
82181 ** handle the rounding directly,
82182 ** otherwise use printf.
82184 if( n==0 && r>=0 && r<LARGEST_INT64-1 ){
82185 r = (double)((sqlite_int64)(r+0.5));
82186 }else if( n==0 && r<0 && (-r)<LARGEST_INT64-1 ){
82187 r = -(double)((sqlite_int64)((-r)+0.5));
82188 }else{
82189 zBuf = sqlite3_mprintf("%.*f",n,r);
82190 if( zBuf==0 ){
82191 sqlite3_result_error_nomem(context);
82192 return;
82194 sqlite3AtoF(zBuf, &r, sqlite3Strlen30(zBuf), SQLITE_UTF8);
82195 sqlite3_free(zBuf);
82197 sqlite3_result_double(context, r);
82199 #endif
82202 ** Allocate nByte bytes of space using sqlite3_malloc(). If the
82203 ** allocation fails, call sqlite3_result_error_nomem() to notify
82204 ** the database handle that malloc() has failed and return NULL.
82205 ** If nByte is larger than the maximum string or blob length, then
82206 ** raise an SQLITE_TOOBIG exception and return NULL.
82208 static void *contextMalloc(sqlite3_context *context, i64 nByte){
82209 char *z;
82210 sqlite3 *db = sqlite3_context_db_handle(context);
82211 assert( nByte>0 );
82212 testcase( nByte==db->aLimit[SQLITE_LIMIT_LENGTH] );
82213 testcase( nByte==db->aLimit[SQLITE_LIMIT_LENGTH]+1 );
82214 if( nByte>db->aLimit[SQLITE_LIMIT_LENGTH] ){
82215 sqlite3_result_error_toobig(context);
82216 z = 0;
82217 }else{
82218 z = sqlite3Malloc((int)nByte);
82219 if( !z ){
82220 sqlite3_result_error_nomem(context);
82223 return z;
82227 ** Implementation of the upper() and lower() SQL functions.
82229 static void upperFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
82230 char *z1;
82231 const char *z2;
82232 int i, n;
82233 UNUSED_PARAMETER(argc);
82234 z2 = (char*)sqlite3_value_text(argv[0]);
82235 n = sqlite3_value_bytes(argv[0]);
82236 /* Verify that the call to _bytes() does not invalidate the _text() pointer */
82237 assert( z2==(char*)sqlite3_value_text(argv[0]) );
82238 if( z2 ){
82239 z1 = contextMalloc(context, ((i64)n)+1);
82240 if( z1 ){
82241 memcpy(z1, z2, n+1);
82242 for(i=0; z1[i]; i++){
82243 z1[i] = (char)sqlite3Toupper(z1[i]);
82245 sqlite3_result_text(context, z1, -1, sqlite3_free);
82249 static void lowerFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
82250 u8 *z1;
82251 const char *z2;
82252 int i, n;
82253 UNUSED_PARAMETER(argc);
82254 z2 = (char*)sqlite3_value_text(argv[0]);
82255 n = sqlite3_value_bytes(argv[0]);
82256 /* Verify that the call to _bytes() does not invalidate the _text() pointer */
82257 assert( z2==(char*)sqlite3_value_text(argv[0]) );
82258 if( z2 ){
82259 z1 = contextMalloc(context, ((i64)n)+1);
82260 if( z1 ){
82261 memcpy(z1, z2, n+1);
82262 for(i=0; z1[i]; i++){
82263 z1[i] = sqlite3Tolower(z1[i]);
82265 sqlite3_result_text(context, (char *)z1, -1, sqlite3_free);
82271 #if 0 /* This function is never used. */
82273 ** The COALESCE() and IFNULL() functions used to be implemented as shown
82274 ** here. But now they are implemented as VDBE code so that unused arguments
82275 ** do not have to be computed. This legacy implementation is retained as
82276 ** comment.
82279 ** Implementation of the IFNULL(), NVL(), and COALESCE() functions.
82280 ** All three do the same thing. They return the first non-NULL
82281 ** argument.
82283 static void ifnullFunc(
82284 sqlite3_context *context,
82285 int argc,
82286 sqlite3_value **argv
82288 int i;
82289 for(i=0; i<argc; i++){
82290 if( SQLITE_NULL!=sqlite3_value_type(argv[i]) ){
82291 sqlite3_result_value(context, argv[i]);
82292 break;
82296 #endif /* NOT USED */
82297 #define ifnullFunc versionFunc /* Substitute function - never called */
82300 ** Implementation of random(). Return a random integer.
82302 static void randomFunc(
82303 sqlite3_context *context,
82304 int NotUsed,
82305 sqlite3_value **NotUsed2
82307 sqlite_int64 r;
82308 UNUSED_PARAMETER2(NotUsed, NotUsed2);
82309 sqlite3_randomness(sizeof(r), &r);
82310 if( r<0 ){
82311 /* We need to prevent a random number of 0x8000000000000000
82312 ** (or -9223372036854775808) since when you do abs() of that
82313 ** number of you get the same value back again. To do this
82314 ** in a way that is testable, mask the sign bit off of negative
82315 ** values, resulting in a positive value. Then take the
82316 ** 2s complement of that positive value. The end result can
82317 ** therefore be no less than -9223372036854775807.
82319 r = -(r ^ (((sqlite3_int64)1)<<63));
82321 sqlite3_result_int64(context, r);
82325 ** Implementation of randomblob(N). Return a random blob
82326 ** that is N bytes long.
82328 static void randomBlob(
82329 sqlite3_context *context,
82330 int argc,
82331 sqlite3_value **argv
82333 int n;
82334 unsigned char *p;
82335 assert( argc==1 );
82336 UNUSED_PARAMETER(argc);
82337 n = sqlite3_value_int(argv[0]);
82338 if( n<1 ){
82339 n = 1;
82341 p = contextMalloc(context, n);
82342 if( p ){
82343 sqlite3_randomness(n, p);
82344 sqlite3_result_blob(context, (char*)p, n, sqlite3_free);
82349 ** Implementation of the last_insert_rowid() SQL function. The return
82350 ** value is the same as the sqlite3_last_insert_rowid() API function.
82352 static void last_insert_rowid(
82353 sqlite3_context *context,
82354 int NotUsed,
82355 sqlite3_value **NotUsed2
82357 sqlite3 *db = sqlite3_context_db_handle(context);
82358 UNUSED_PARAMETER2(NotUsed, NotUsed2);
82359 /* IMP: R-51513-12026 The last_insert_rowid() SQL function is a
82360 ** wrapper around the sqlite3_last_insert_rowid() C/C++ interface
82361 ** function. */
82362 sqlite3_result_int64(context, sqlite3_last_insert_rowid(db));
82366 ** Implementation of the changes() SQL function.
82368 ** IMP: R-62073-11209 The changes() SQL function is a wrapper
82369 ** around the sqlite3_changes() C/C++ function and hence follows the same
82370 ** rules for counting changes.
82372 static void changes(
82373 sqlite3_context *context,
82374 int NotUsed,
82375 sqlite3_value **NotUsed2
82377 sqlite3 *db = sqlite3_context_db_handle(context);
82378 UNUSED_PARAMETER2(NotUsed, NotUsed2);
82379 sqlite3_result_int(context, sqlite3_changes(db));
82383 ** Implementation of the total_changes() SQL function. The return value is
82384 ** the same as the sqlite3_total_changes() API function.
82386 static void total_changes(
82387 sqlite3_context *context,
82388 int NotUsed,
82389 sqlite3_value **NotUsed2
82391 sqlite3 *db = sqlite3_context_db_handle(context);
82392 UNUSED_PARAMETER2(NotUsed, NotUsed2);
82393 /* IMP: R-52756-41993 This function is a wrapper around the
82394 ** sqlite3_total_changes() C/C++ interface. */
82395 sqlite3_result_int(context, sqlite3_total_changes(db));
82399 ** A structure defining how to do GLOB-style comparisons.
82401 struct compareInfo {
82402 u8 matchAll;
82403 u8 matchOne;
82404 u8 matchSet;
82405 u8 noCase;
82409 ** For LIKE and GLOB matching on EBCDIC machines, assume that every
82410 ** character is exactly one byte in size. Also, all characters are
82411 ** able to participate in upper-case-to-lower-case mappings in EBCDIC
82412 ** whereas only characters less than 0x80 do in ASCII.
82414 #if defined(SQLITE_EBCDIC)
82415 # define sqlite3Utf8Read(A,C) (*(A++))
82416 # define GlogUpperToLower(A) A = sqlite3UpperToLower[A]
82417 #else
82418 # define GlogUpperToLower(A) if( A<0x80 ){ A = sqlite3UpperToLower[A]; }
82419 #endif
82421 static const struct compareInfo globInfo = { '*', '?', '[', 0 };
82422 /* The correct SQL-92 behavior is for the LIKE operator to ignore
82423 ** case. Thus 'a' LIKE 'A' would be true. */
82424 static const struct compareInfo likeInfoNorm = { '%', '_', 0, 1 };
82425 /* If SQLITE_CASE_SENSITIVE_LIKE is defined, then the LIKE operator
82426 ** is case sensitive causing 'a' LIKE 'A' to be false */
82427 static const struct compareInfo likeInfoAlt = { '%', '_', 0, 0 };
82430 ** Compare two UTF-8 strings for equality where the first string can
82431 ** potentially be a "glob" expression. Return true (1) if they
82432 ** are the same and false (0) if they are different.
82434 ** Globbing rules:
82436 ** '*' Matches any sequence of zero or more characters.
82438 ** '?' Matches exactly one character.
82440 ** [...] Matches one character from the enclosed list of
82441 ** characters.
82443 ** [^...] Matches one character not in the enclosed list.
82445 ** With the [...] and [^...] matching, a ']' character can be included
82446 ** in the list by making it the first character after '[' or '^'. A
82447 ** range of characters can be specified using '-'. Example:
82448 ** "[a-z]" matches any single lower-case letter. To match a '-', make
82449 ** it the last character in the list.
82451 ** This routine is usually quick, but can be N**2 in the worst case.
82453 ** Hints: to match '*' or '?', put them in "[]". Like this:
82455 ** abc[*]xyz Matches "abc*xyz" only
82457 static int patternCompare(
82458 const u8 *zPattern, /* The glob pattern */
82459 const u8 *zString, /* The string to compare against the glob */
82460 const struct compareInfo *pInfo, /* Information about how to do the compare */
82461 const int esc /* The escape character */
82463 int c, c2;
82464 int invert;
82465 int seen;
82466 u8 matchOne = pInfo->matchOne;
82467 u8 matchAll = pInfo->matchAll;
82468 u8 matchSet = pInfo->matchSet;
82469 u8 noCase = pInfo->noCase;
82470 int prevEscape = 0; /* True if the previous character was 'escape' */
82472 while( (c = sqlite3Utf8Read(zPattern,&zPattern))!=0 ){
82473 if( !prevEscape && c==matchAll ){
82474 while( (c=sqlite3Utf8Read(zPattern,&zPattern)) == matchAll
82475 || c == matchOne ){
82476 if( c==matchOne && sqlite3Utf8Read(zString, &zString)==0 ){
82477 return 0;
82480 if( c==0 ){
82481 return 1;
82482 }else if( c==esc ){
82483 c = sqlite3Utf8Read(zPattern, &zPattern);
82484 if( c==0 ){
82485 return 0;
82487 }else if( c==matchSet ){
82488 assert( esc==0 ); /* This is GLOB, not LIKE */
82489 assert( matchSet<0x80 ); /* '[' is a single-byte character */
82490 while( *zString && patternCompare(&zPattern[-1],zString,pInfo,esc)==0 ){
82491 SQLITE_SKIP_UTF8(zString);
82493 return *zString!=0;
82495 while( (c2 = sqlite3Utf8Read(zString,&zString))!=0 ){
82496 if( noCase ){
82497 GlogUpperToLower(c2);
82498 GlogUpperToLower(c);
82499 while( c2 != 0 && c2 != c ){
82500 c2 = sqlite3Utf8Read(zString, &zString);
82501 GlogUpperToLower(c2);
82503 }else{
82504 while( c2 != 0 && c2 != c ){
82505 c2 = sqlite3Utf8Read(zString, &zString);
82508 if( c2==0 ) return 0;
82509 if( patternCompare(zPattern,zString,pInfo,esc) ) return 1;
82511 return 0;
82512 }else if( !prevEscape && c==matchOne ){
82513 if( sqlite3Utf8Read(zString, &zString)==0 ){
82514 return 0;
82516 }else if( c==matchSet ){
82517 int prior_c = 0;
82518 assert( esc==0 ); /* This only occurs for GLOB, not LIKE */
82519 seen = 0;
82520 invert = 0;
82521 c = sqlite3Utf8Read(zString, &zString);
82522 if( c==0 ) return 0;
82523 c2 = sqlite3Utf8Read(zPattern, &zPattern);
82524 if( c2=='^' ){
82525 invert = 1;
82526 c2 = sqlite3Utf8Read(zPattern, &zPattern);
82528 if( c2==']' ){
82529 if( c==']' ) seen = 1;
82530 c2 = sqlite3Utf8Read(zPattern, &zPattern);
82532 while( c2 && c2!=']' ){
82533 if( c2=='-' && zPattern[0]!=']' && zPattern[0]!=0 && prior_c>0 ){
82534 c2 = sqlite3Utf8Read(zPattern, &zPattern);
82535 if( c>=prior_c && c<=c2 ) seen = 1;
82536 prior_c = 0;
82537 }else{
82538 if( c==c2 ){
82539 seen = 1;
82541 prior_c = c2;
82543 c2 = sqlite3Utf8Read(zPattern, &zPattern);
82545 if( c2==0 || (seen ^ invert)==0 ){
82546 return 0;
82548 }else if( esc==c && !prevEscape ){
82549 prevEscape = 1;
82550 }else{
82551 c2 = sqlite3Utf8Read(zString, &zString);
82552 if( noCase ){
82553 GlogUpperToLower(c);
82554 GlogUpperToLower(c2);
82556 if( c!=c2 ){
82557 return 0;
82559 prevEscape = 0;
82562 return *zString==0;
82566 ** Count the number of times that the LIKE operator (or GLOB which is
82567 ** just a variation of LIKE) gets called. This is used for testing
82568 ** only.
82570 #ifdef SQLITE_TEST
82571 SQLITE_API int sqlite3_like_count = 0;
82572 #endif
82576 ** Implementation of the like() SQL function. This function implements
82577 ** the build-in LIKE operator. The first argument to the function is the
82578 ** pattern and the second argument is the string. So, the SQL statements:
82580 ** A LIKE B
82582 ** is implemented as like(B,A).
82584 ** This same function (with a different compareInfo structure) computes
82585 ** the GLOB operator.
82587 static void likeFunc(
82588 sqlite3_context *context,
82589 int argc,
82590 sqlite3_value **argv
82592 const unsigned char *zA, *zB;
82593 int escape = 0;
82594 int nPat;
82595 sqlite3 *db = sqlite3_context_db_handle(context);
82597 zB = sqlite3_value_text(argv[0]);
82598 zA = sqlite3_value_text(argv[1]);
82600 /* Limit the length of the LIKE or GLOB pattern to avoid problems
82601 ** of deep recursion and N*N behavior in patternCompare().
82603 nPat = sqlite3_value_bytes(argv[0]);
82604 testcase( nPat==db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH] );
82605 testcase( nPat==db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH]+1 );
82606 if( nPat > db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH] ){
82607 sqlite3_result_error(context, "LIKE or GLOB pattern too complex", -1);
82608 return;
82610 assert( zB==sqlite3_value_text(argv[0]) ); /* Encoding did not change */
82612 if( argc==3 ){
82613 /* The escape character string must consist of a single UTF-8 character.
82614 ** Otherwise, return an error.
82616 const unsigned char *zEsc = sqlite3_value_text(argv[2]);
82617 if( zEsc==0 ) return;
82618 if( sqlite3Utf8CharLen((char*)zEsc, -1)!=1 ){
82619 sqlite3_result_error(context,
82620 "ESCAPE expression must be a single character", -1);
82621 return;
82623 escape = sqlite3Utf8Read(zEsc, &zEsc);
82625 if( zA && zB ){
82626 struct compareInfo *pInfo = sqlite3_user_data(context);
82627 #ifdef SQLITE_TEST
82628 sqlite3_like_count++;
82629 #endif
82631 sqlite3_result_int(context, patternCompare(zB, zA, pInfo, escape));
82636 ** Implementation of the NULLIF(x,y) function. The result is the first
82637 ** argument if the arguments are different. The result is NULL if the
82638 ** arguments are equal to each other.
82640 static void nullifFunc(
82641 sqlite3_context *context,
82642 int NotUsed,
82643 sqlite3_value **argv
82645 CollSeq *pColl = sqlite3GetFuncCollSeq(context);
82646 UNUSED_PARAMETER(NotUsed);
82647 if( sqlite3MemCompare(argv[0], argv[1], pColl)!=0 ){
82648 sqlite3_result_value(context, argv[0]);
82653 ** Implementation of the sqlite_version() function. The result is the version
82654 ** of the SQLite library that is running.
82656 static void versionFunc(
82657 sqlite3_context *context,
82658 int NotUsed,
82659 sqlite3_value **NotUsed2
82661 UNUSED_PARAMETER2(NotUsed, NotUsed2);
82662 /* IMP: R-48699-48617 This function is an SQL wrapper around the
82663 ** sqlite3_libversion() C-interface. */
82664 sqlite3_result_text(context, sqlite3_libversion(), -1, SQLITE_STATIC);
82668 ** Implementation of the sqlite_source_id() function. The result is a string
82669 ** that identifies the particular version of the source code used to build
82670 ** SQLite.
82672 static void sourceidFunc(
82673 sqlite3_context *context,
82674 int NotUsed,
82675 sqlite3_value **NotUsed2
82677 UNUSED_PARAMETER2(NotUsed, NotUsed2);
82678 /* IMP: R-24470-31136 This function is an SQL wrapper around the
82679 ** sqlite3_sourceid() C interface. */
82680 sqlite3_result_text(context, sqlite3_sourceid(), -1, SQLITE_STATIC);
82684 ** Implementation of the sqlite_compileoption_used() function.
82685 ** The result is an integer that identifies if the compiler option
82686 ** was used to build SQLite.
82688 #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
82689 static void compileoptionusedFunc(
82690 sqlite3_context *context,
82691 int argc,
82692 sqlite3_value **argv
82694 const char *zOptName;
82695 assert( argc==1 );
82696 UNUSED_PARAMETER(argc);
82697 /* IMP: R-39564-36305 The sqlite_compileoption_used() SQL
82698 ** function is a wrapper around the sqlite3_compileoption_used() C/C++
82699 ** function.
82701 if( (zOptName = (const char*)sqlite3_value_text(argv[0]))!=0 ){
82702 sqlite3_result_int(context, sqlite3_compileoption_used(zOptName));
82705 #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
82708 ** Implementation of the sqlite_compileoption_get() function.
82709 ** The result is a string that identifies the compiler options
82710 ** used to build SQLite.
82712 #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
82713 static void compileoptiongetFunc(
82714 sqlite3_context *context,
82715 int argc,
82716 sqlite3_value **argv
82718 int n;
82719 assert( argc==1 );
82720 UNUSED_PARAMETER(argc);
82721 /* IMP: R-04922-24076 The sqlite_compileoption_get() SQL function
82722 ** is a wrapper around the sqlite3_compileoption_get() C/C++ function.
82724 n = sqlite3_value_int(argv[0]);
82725 sqlite3_result_text(context, sqlite3_compileoption_get(n), -1, SQLITE_STATIC);
82727 #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
82729 /* Array for converting from half-bytes (nybbles) into ASCII hex
82730 ** digits. */
82731 static const char hexdigits[] = {
82732 '0', '1', '2', '3', '4', '5', '6', '7',
82733 '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'
82737 ** EXPERIMENTAL - This is not an official function. The interface may
82738 ** change. This function may disappear. Do not write code that depends
82739 ** on this function.
82741 ** Implementation of the QUOTE() function. This function takes a single
82742 ** argument. If the argument is numeric, the return value is the same as
82743 ** the argument. If the argument is NULL, the return value is the string
82744 ** "NULL". Otherwise, the argument is enclosed in single quotes with
82745 ** single-quote escapes.
82747 static void quoteFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
82748 assert( argc==1 );
82749 UNUSED_PARAMETER(argc);
82750 switch( sqlite3_value_type(argv[0]) ){
82751 case SQLITE_INTEGER:
82752 case SQLITE_FLOAT: {
82753 sqlite3_result_value(context, argv[0]);
82754 break;
82756 case SQLITE_BLOB: {
82757 char *zText = 0;
82758 char const *zBlob = sqlite3_value_blob(argv[0]);
82759 int nBlob = sqlite3_value_bytes(argv[0]);
82760 assert( zBlob==sqlite3_value_blob(argv[0]) ); /* No encoding change */
82761 zText = (char *)contextMalloc(context, (2*(i64)nBlob)+4);
82762 if( zText ){
82763 int i;
82764 for(i=0; i<nBlob; i++){
82765 zText[(i*2)+2] = hexdigits[(zBlob[i]>>4)&0x0F];
82766 zText[(i*2)+3] = hexdigits[(zBlob[i])&0x0F];
82768 zText[(nBlob*2)+2] = '\'';
82769 zText[(nBlob*2)+3] = '\0';
82770 zText[0] = 'X';
82771 zText[1] = '\'';
82772 sqlite3_result_text(context, zText, -1, SQLITE_TRANSIENT);
82773 sqlite3_free(zText);
82775 break;
82777 case SQLITE_TEXT: {
82778 int i,j;
82779 u64 n;
82780 const unsigned char *zArg = sqlite3_value_text(argv[0]);
82781 char *z;
82783 if( zArg==0 ) return;
82784 for(i=0, n=0; zArg[i]; i++){ if( zArg[i]=='\'' ) n++; }
82785 z = contextMalloc(context, ((i64)i)+((i64)n)+3);
82786 if( z ){
82787 z[0] = '\'';
82788 for(i=0, j=1; zArg[i]; i++){
82789 z[j++] = zArg[i];
82790 if( zArg[i]=='\'' ){
82791 z[j++] = '\'';
82794 z[j++] = '\'';
82795 z[j] = 0;
82796 sqlite3_result_text(context, z, j, sqlite3_free);
82798 break;
82800 default: {
82801 assert( sqlite3_value_type(argv[0])==SQLITE_NULL );
82802 sqlite3_result_text(context, "NULL", 4, SQLITE_STATIC);
82803 break;
82809 ** The hex() function. Interpret the argument as a blob. Return
82810 ** a hexadecimal rendering as text.
82812 static void hexFunc(
82813 sqlite3_context *context,
82814 int argc,
82815 sqlite3_value **argv
82817 int i, n;
82818 const unsigned char *pBlob;
82819 char *zHex, *z;
82820 assert( argc==1 );
82821 UNUSED_PARAMETER(argc);
82822 pBlob = sqlite3_value_blob(argv[0]);
82823 n = sqlite3_value_bytes(argv[0]);
82824 assert( pBlob==sqlite3_value_blob(argv[0]) ); /* No encoding change */
82825 z = zHex = contextMalloc(context, ((i64)n)*2 + 1);
82826 if( zHex ){
82827 for(i=0; i<n; i++, pBlob++){
82828 unsigned char c = *pBlob;
82829 *(z++) = hexdigits[(c>>4)&0xf];
82830 *(z++) = hexdigits[c&0xf];
82832 *z = 0;
82833 sqlite3_result_text(context, zHex, n*2, sqlite3_free);
82838 ** The zeroblob(N) function returns a zero-filled blob of size N bytes.
82840 static void zeroblobFunc(
82841 sqlite3_context *context,
82842 int argc,
82843 sqlite3_value **argv
82845 i64 n;
82846 sqlite3 *db = sqlite3_context_db_handle(context);
82847 assert( argc==1 );
82848 UNUSED_PARAMETER(argc);
82849 n = sqlite3_value_int64(argv[0]);
82850 testcase( n==db->aLimit[SQLITE_LIMIT_LENGTH] );
82851 testcase( n==db->aLimit[SQLITE_LIMIT_LENGTH]+1 );
82852 if( n>db->aLimit[SQLITE_LIMIT_LENGTH] ){
82853 sqlite3_result_error_toobig(context);
82854 }else{
82855 sqlite3_result_zeroblob(context, (int)n); /* IMP: R-00293-64994 */
82860 ** The replace() function. Three arguments are all strings: call
82861 ** them A, B, and C. The result is also a string which is derived
82862 ** from A by replacing every occurance of B with C. The match
82863 ** must be exact. Collating sequences are not used.
82865 static void replaceFunc(
82866 sqlite3_context *context,
82867 int argc,
82868 sqlite3_value **argv
82870 const unsigned char *zStr; /* The input string A */
82871 const unsigned char *zPattern; /* The pattern string B */
82872 const unsigned char *zRep; /* The replacement string C */
82873 unsigned char *zOut; /* The output */
82874 int nStr; /* Size of zStr */
82875 int nPattern; /* Size of zPattern */
82876 int nRep; /* Size of zRep */
82877 i64 nOut; /* Maximum size of zOut */
82878 int loopLimit; /* Last zStr[] that might match zPattern[] */
82879 int i, j; /* Loop counters */
82881 assert( argc==3 );
82882 UNUSED_PARAMETER(argc);
82883 zStr = sqlite3_value_text(argv[0]);
82884 if( zStr==0 ) return;
82885 nStr = sqlite3_value_bytes(argv[0]);
82886 assert( zStr==sqlite3_value_text(argv[0]) ); /* No encoding change */
82887 zPattern = sqlite3_value_text(argv[1]);
82888 if( zPattern==0 ){
82889 assert( sqlite3_value_type(argv[1])==SQLITE_NULL
82890 || sqlite3_context_db_handle(context)->mallocFailed );
82891 return;
82893 if( zPattern[0]==0 ){
82894 assert( sqlite3_value_type(argv[1])!=SQLITE_NULL );
82895 sqlite3_result_value(context, argv[0]);
82896 return;
82898 nPattern = sqlite3_value_bytes(argv[1]);
82899 assert( zPattern==sqlite3_value_text(argv[1]) ); /* No encoding change */
82900 zRep = sqlite3_value_text(argv[2]);
82901 if( zRep==0 ) return;
82902 nRep = sqlite3_value_bytes(argv[2]);
82903 assert( zRep==sqlite3_value_text(argv[2]) );
82904 nOut = nStr + 1;
82905 assert( nOut<SQLITE_MAX_LENGTH );
82906 zOut = contextMalloc(context, (i64)nOut);
82907 if( zOut==0 ){
82908 return;
82910 loopLimit = nStr - nPattern;
82911 for(i=j=0; i<=loopLimit; i++){
82912 if( zStr[i]!=zPattern[0] || memcmp(&zStr[i], zPattern, nPattern) ){
82913 zOut[j++] = zStr[i];
82914 }else{
82915 u8 *zOld;
82916 sqlite3 *db = sqlite3_context_db_handle(context);
82917 nOut += nRep - nPattern;
82918 testcase( nOut-1==db->aLimit[SQLITE_LIMIT_LENGTH] );
82919 testcase( nOut-2==db->aLimit[SQLITE_LIMIT_LENGTH] );
82920 if( nOut-1>db->aLimit[SQLITE_LIMIT_LENGTH] ){
82921 sqlite3_result_error_toobig(context);
82922 sqlite3_free(zOut);
82923 return;
82925 zOld = zOut;
82926 zOut = sqlite3_realloc(zOut, (int)nOut);
82927 if( zOut==0 ){
82928 sqlite3_result_error_nomem(context);
82929 sqlite3_free(zOld);
82930 return;
82932 memcpy(&zOut[j], zRep, nRep);
82933 j += nRep;
82934 i += nPattern-1;
82937 assert( j+nStr-i+1==nOut );
82938 memcpy(&zOut[j], &zStr[i], nStr-i);
82939 j += nStr - i;
82940 assert( j<=nOut );
82941 zOut[j] = 0;
82942 sqlite3_result_text(context, (char*)zOut, j, sqlite3_free);
82946 ** Implementation of the TRIM(), LTRIM(), and RTRIM() functions.
82947 ** The userdata is 0x1 for left trim, 0x2 for right trim, 0x3 for both.
82949 static void trimFunc(
82950 sqlite3_context *context,
82951 int argc,
82952 sqlite3_value **argv
82954 const unsigned char *zIn; /* Input string */
82955 const unsigned char *zCharSet; /* Set of characters to trim */
82956 int nIn; /* Number of bytes in input */
82957 int flags; /* 1: trimleft 2: trimright 3: trim */
82958 int i; /* Loop counter */
82959 unsigned char *aLen = 0; /* Length of each character in zCharSet */
82960 unsigned char **azChar = 0; /* Individual characters in zCharSet */
82961 int nChar; /* Number of characters in zCharSet */
82963 if( sqlite3_value_type(argv[0])==SQLITE_NULL ){
82964 return;
82966 zIn = sqlite3_value_text(argv[0]);
82967 if( zIn==0 ) return;
82968 nIn = sqlite3_value_bytes(argv[0]);
82969 assert( zIn==sqlite3_value_text(argv[0]) );
82970 if( argc==1 ){
82971 static const unsigned char lenOne[] = { 1 };
82972 static unsigned char * const azOne[] = { (u8*)" " };
82973 nChar = 1;
82974 aLen = (u8*)lenOne;
82975 azChar = (unsigned char **)azOne;
82976 zCharSet = 0;
82977 }else if( (zCharSet = sqlite3_value_text(argv[1]))==0 ){
82978 return;
82979 }else{
82980 const unsigned char *z;
82981 for(z=zCharSet, nChar=0; *z; nChar++){
82982 SQLITE_SKIP_UTF8(z);
82984 if( nChar>0 ){
82985 azChar = contextMalloc(context, ((i64)nChar)*(sizeof(char*)+1));
82986 if( azChar==0 ){
82987 return;
82989 aLen = (unsigned char*)&azChar[nChar];
82990 for(z=zCharSet, nChar=0; *z; nChar++){
82991 azChar[nChar] = (unsigned char *)z;
82992 SQLITE_SKIP_UTF8(z);
82993 aLen[nChar] = (u8)(z - azChar[nChar]);
82997 if( nChar>0 ){
82998 flags = SQLITE_PTR_TO_INT(sqlite3_user_data(context));
82999 if( flags & 1 ){
83000 while( nIn>0 ){
83001 int len = 0;
83002 for(i=0; i<nChar; i++){
83003 len = aLen[i];
83004 if( len<=nIn && memcmp(zIn, azChar[i], len)==0 ) break;
83006 if( i>=nChar ) break;
83007 zIn += len;
83008 nIn -= len;
83011 if( flags & 2 ){
83012 while( nIn>0 ){
83013 int len = 0;
83014 for(i=0; i<nChar; i++){
83015 len = aLen[i];
83016 if( len<=nIn && memcmp(&zIn[nIn-len],azChar[i],len)==0 ) break;
83018 if( i>=nChar ) break;
83019 nIn -= len;
83022 if( zCharSet ){
83023 sqlite3_free((void*)azChar);
83026 sqlite3_result_text(context, (char*)zIn, nIn, SQLITE_TRANSIENT);
83030 /* IMP: R-25361-16150 This function is omitted from SQLite by default. It
83031 ** is only available if the SQLITE_SOUNDEX compile-time option is used
83032 ** when SQLite is built.
83034 #ifdef SQLITE_SOUNDEX
83036 ** Compute the soundex encoding of a word.
83038 ** IMP: R-59782-00072 The soundex(X) function returns a string that is the
83039 ** soundex encoding of the string X.
83041 static void soundexFunc(
83042 sqlite3_context *context,
83043 int argc,
83044 sqlite3_value **argv
83046 char zResult[8];
83047 const u8 *zIn;
83048 int i, j;
83049 static const unsigned char iCode[] = {
83050 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
83051 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
83052 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
83053 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
83054 0, 0, 1, 2, 3, 0, 1, 2, 0, 0, 2, 2, 4, 5, 5, 0,
83055 1, 2, 6, 2, 3, 0, 1, 0, 2, 0, 2, 0, 0, 0, 0, 0,
83056 0, 0, 1, 2, 3, 0, 1, 2, 0, 0, 2, 2, 4, 5, 5, 0,
83057 1, 2, 6, 2, 3, 0, 1, 0, 2, 0, 2, 0, 0, 0, 0, 0,
83059 assert( argc==1 );
83060 zIn = (u8*)sqlite3_value_text(argv[0]);
83061 if( zIn==0 ) zIn = (u8*)"";
83062 for(i=0; zIn[i] && !sqlite3Isalpha(zIn[i]); i++){}
83063 if( zIn[i] ){
83064 u8 prevcode = iCode[zIn[i]&0x7f];
83065 zResult[0] = sqlite3Toupper(zIn[i]);
83066 for(j=1; j<4 && zIn[i]; i++){
83067 int code = iCode[zIn[i]&0x7f];
83068 if( code>0 ){
83069 if( code!=prevcode ){
83070 prevcode = code;
83071 zResult[j++] = code + '0';
83073 }else{
83074 prevcode = 0;
83077 while( j<4 ){
83078 zResult[j++] = '0';
83080 zResult[j] = 0;
83081 sqlite3_result_text(context, zResult, 4, SQLITE_TRANSIENT);
83082 }else{
83083 /* IMP: R-64894-50321 The string "?000" is returned if the argument
83084 ** is NULL or contains no ASCII alphabetic characters. */
83085 sqlite3_result_text(context, "?000", 4, SQLITE_STATIC);
83088 #endif /* SQLITE_SOUNDEX */
83090 #ifndef SQLITE_OMIT_LOAD_EXTENSION
83092 ** A function that loads a shared-library extension then returns NULL.
83094 static void loadExt(sqlite3_context *context, int argc, sqlite3_value **argv){
83095 const char *zFile = (const char *)sqlite3_value_text(argv[0]);
83096 const char *zProc;
83097 sqlite3 *db = sqlite3_context_db_handle(context);
83098 char *zErrMsg = 0;
83100 if( argc==2 ){
83101 zProc = (const char *)sqlite3_value_text(argv[1]);
83102 }else{
83103 zProc = 0;
83105 if( zFile && sqlite3_load_extension(db, zFile, zProc, &zErrMsg) ){
83106 sqlite3_result_error(context, zErrMsg, -1);
83107 sqlite3_free(zErrMsg);
83110 #endif
83114 ** An instance of the following structure holds the context of a
83115 ** sum() or avg() aggregate computation.
83117 typedef struct SumCtx SumCtx;
83118 struct SumCtx {
83119 double rSum; /* Floating point sum */
83120 i64 iSum; /* Integer sum */
83121 i64 cnt; /* Number of elements summed */
83122 u8 overflow; /* True if integer overflow seen */
83123 u8 approx; /* True if non-integer value was input to the sum */
83127 ** Routines used to compute the sum, average, and total.
83129 ** The SUM() function follows the (broken) SQL standard which means
83130 ** that it returns NULL if it sums over no inputs. TOTAL returns
83131 ** 0.0 in that case. In addition, TOTAL always returns a float where
83132 ** SUM might return an integer if it never encounters a floating point
83133 ** value. TOTAL never fails, but SUM might through an exception if
83134 ** it overflows an integer.
83136 static void sumStep(sqlite3_context *context, int argc, sqlite3_value **argv){
83137 SumCtx *p;
83138 int type;
83139 assert( argc==1 );
83140 UNUSED_PARAMETER(argc);
83141 p = sqlite3_aggregate_context(context, sizeof(*p));
83142 type = sqlite3_value_numeric_type(argv[0]);
83143 if( p && type!=SQLITE_NULL ){
83144 p->cnt++;
83145 if( type==SQLITE_INTEGER ){
83146 i64 v = sqlite3_value_int64(argv[0]);
83147 p->rSum += v;
83148 if( (p->approx|p->overflow)==0 && sqlite3AddInt64(&p->iSum, v) ){
83149 p->overflow = 1;
83151 }else{
83152 p->rSum += sqlite3_value_double(argv[0]);
83153 p->approx = 1;
83157 static void sumFinalize(sqlite3_context *context){
83158 SumCtx *p;
83159 p = sqlite3_aggregate_context(context, 0);
83160 if( p && p->cnt>0 ){
83161 if( p->overflow ){
83162 sqlite3_result_error(context,"integer overflow",-1);
83163 }else if( p->approx ){
83164 sqlite3_result_double(context, p->rSum);
83165 }else{
83166 sqlite3_result_int64(context, p->iSum);
83170 static void avgFinalize(sqlite3_context *context){
83171 SumCtx *p;
83172 p = sqlite3_aggregate_context(context, 0);
83173 if( p && p->cnt>0 ){
83174 sqlite3_result_double(context, p->rSum/(double)p->cnt);
83177 static void totalFinalize(sqlite3_context *context){
83178 SumCtx *p;
83179 p = sqlite3_aggregate_context(context, 0);
83180 /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
83181 sqlite3_result_double(context, p ? p->rSum : (double)0);
83185 ** The following structure keeps track of state information for the
83186 ** count() aggregate function.
83188 typedef struct CountCtx CountCtx;
83189 struct CountCtx {
83190 i64 n;
83194 ** Routines to implement the count() aggregate function.
83196 static void countStep(sqlite3_context *context, int argc, sqlite3_value **argv){
83197 CountCtx *p;
83198 p = sqlite3_aggregate_context(context, sizeof(*p));
83199 if( (argc==0 || SQLITE_NULL!=sqlite3_value_type(argv[0])) && p ){
83200 p->n++;
83203 #ifndef SQLITE_OMIT_DEPRECATED
83204 /* The sqlite3_aggregate_count() function is deprecated. But just to make
83205 ** sure it still operates correctly, verify that its count agrees with our
83206 ** internal count when using count(*) and when the total count can be
83207 ** expressed as a 32-bit integer. */
83208 assert( argc==1 || p==0 || p->n>0x7fffffff
83209 || p->n==sqlite3_aggregate_count(context) );
83210 #endif
83212 static void countFinalize(sqlite3_context *context){
83213 CountCtx *p;
83214 p = sqlite3_aggregate_context(context, 0);
83215 sqlite3_result_int64(context, p ? p->n : 0);
83219 ** Routines to implement min() and max() aggregate functions.
83221 static void minmaxStep(
83222 sqlite3_context *context,
83223 int NotUsed,
83224 sqlite3_value **argv
83226 Mem *pArg = (Mem *)argv[0];
83227 Mem *pBest;
83228 UNUSED_PARAMETER(NotUsed);
83230 if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
83231 pBest = (Mem *)sqlite3_aggregate_context(context, sizeof(*pBest));
83232 if( !pBest ) return;
83234 if( pBest->flags ){
83235 int max;
83236 int cmp;
83237 CollSeq *pColl = sqlite3GetFuncCollSeq(context);
83238 /* This step function is used for both the min() and max() aggregates,
83239 ** the only difference between the two being that the sense of the
83240 ** comparison is inverted. For the max() aggregate, the
83241 ** sqlite3_user_data() function returns (void *)-1. For min() it
83242 ** returns (void *)db, where db is the sqlite3* database pointer.
83243 ** Therefore the next statement sets variable 'max' to 1 for the max()
83244 ** aggregate, or 0 for min().
83246 max = sqlite3_user_data(context)!=0;
83247 cmp = sqlite3MemCompare(pBest, pArg, pColl);
83248 if( (max && cmp<0) || (!max && cmp>0) ){
83249 sqlite3VdbeMemCopy(pBest, pArg);
83251 }else{
83252 sqlite3VdbeMemCopy(pBest, pArg);
83255 static void minMaxFinalize(sqlite3_context *context){
83256 sqlite3_value *pRes;
83257 pRes = (sqlite3_value *)sqlite3_aggregate_context(context, 0);
83258 if( pRes ){
83259 if( ALWAYS(pRes->flags) ){
83260 sqlite3_result_value(context, pRes);
83262 sqlite3VdbeMemRelease(pRes);
83267 ** group_concat(EXPR, ?SEPARATOR?)
83269 static void groupConcatStep(
83270 sqlite3_context *context,
83271 int argc,
83272 sqlite3_value **argv
83274 const char *zVal;
83275 StrAccum *pAccum;
83276 const char *zSep;
83277 int nVal, nSep;
83278 assert( argc==1 || argc==2 );
83279 if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
83280 pAccum = (StrAccum*)sqlite3_aggregate_context(context, sizeof(*pAccum));
83282 if( pAccum ){
83283 sqlite3 *db = sqlite3_context_db_handle(context);
83284 int firstTerm = pAccum->useMalloc==0;
83285 pAccum->useMalloc = 2;
83286 pAccum->mxAlloc = db->aLimit[SQLITE_LIMIT_LENGTH];
83287 if( !firstTerm ){
83288 if( argc==2 ){
83289 zSep = (char*)sqlite3_value_text(argv[1]);
83290 nSep = sqlite3_value_bytes(argv[1]);
83291 }else{
83292 zSep = ",";
83293 nSep = 1;
83295 sqlite3StrAccumAppend(pAccum, zSep, nSep);
83297 zVal = (char*)sqlite3_value_text(argv[0]);
83298 nVal = sqlite3_value_bytes(argv[0]);
83299 sqlite3StrAccumAppend(pAccum, zVal, nVal);
83302 static void groupConcatFinalize(sqlite3_context *context){
83303 StrAccum *pAccum;
83304 pAccum = sqlite3_aggregate_context(context, 0);
83305 if( pAccum ){
83306 if( pAccum->tooBig ){
83307 sqlite3_result_error_toobig(context);
83308 }else if( pAccum->mallocFailed ){
83309 sqlite3_result_error_nomem(context);
83310 }else{
83311 sqlite3_result_text(context, sqlite3StrAccumFinish(pAccum), -1,
83312 sqlite3_free);
83318 ** This routine does per-connection function registration. Most
83319 ** of the built-in functions above are part of the global function set.
83320 ** This routine only deals with those that are not global.
83322 SQLITE_PRIVATE void sqlite3RegisterBuiltinFunctions(sqlite3 *db){
83323 int rc = sqlite3_overload_function(db, "MATCH", 2);
83324 assert( rc==SQLITE_NOMEM || rc==SQLITE_OK );
83325 if( rc==SQLITE_NOMEM ){
83326 db->mallocFailed = 1;
83331 ** Set the LIKEOPT flag on the 2-argument function with the given name.
83333 static void setLikeOptFlag(sqlite3 *db, const char *zName, u8 flagVal){
83334 FuncDef *pDef;
83335 pDef = sqlite3FindFunction(db, zName, sqlite3Strlen30(zName),
83336 2, SQLITE_UTF8, 0);
83337 if( ALWAYS(pDef) ){
83338 pDef->flags = flagVal;
83343 ** Register the built-in LIKE and GLOB functions. The caseSensitive
83344 ** parameter determines whether or not the LIKE operator is case
83345 ** sensitive. GLOB is always case sensitive.
83347 SQLITE_PRIVATE void sqlite3RegisterLikeFunctions(sqlite3 *db, int caseSensitive){
83348 struct compareInfo *pInfo;
83349 if( caseSensitive ){
83350 pInfo = (struct compareInfo*)&likeInfoAlt;
83351 }else{
83352 pInfo = (struct compareInfo*)&likeInfoNorm;
83354 sqlite3CreateFunc(db, "like", 2, SQLITE_UTF8, pInfo, likeFunc, 0, 0, 0);
83355 sqlite3CreateFunc(db, "like", 3, SQLITE_UTF8, pInfo, likeFunc, 0, 0, 0);
83356 sqlite3CreateFunc(db, "glob", 2, SQLITE_UTF8,
83357 (struct compareInfo*)&globInfo, likeFunc, 0, 0, 0);
83358 setLikeOptFlag(db, "glob", SQLITE_FUNC_LIKE | SQLITE_FUNC_CASE);
83359 setLikeOptFlag(db, "like",
83360 caseSensitive ? (SQLITE_FUNC_LIKE | SQLITE_FUNC_CASE) : SQLITE_FUNC_LIKE);
83364 ** pExpr points to an expression which implements a function. If
83365 ** it is appropriate to apply the LIKE optimization to that function
83366 ** then set aWc[0] through aWc[2] to the wildcard characters and
83367 ** return TRUE. If the function is not a LIKE-style function then
83368 ** return FALSE.
83370 SQLITE_PRIVATE int sqlite3IsLikeFunction(sqlite3 *db, Expr *pExpr, int *pIsNocase, char *aWc){
83371 FuncDef *pDef;
83372 if( pExpr->op!=TK_FUNCTION
83373 || !pExpr->x.pList
83374 || pExpr->x.pList->nExpr!=2
83376 return 0;
83378 assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
83379 pDef = sqlite3FindFunction(db, pExpr->u.zToken,
83380 sqlite3Strlen30(pExpr->u.zToken),
83381 2, SQLITE_UTF8, 0);
83382 if( NEVER(pDef==0) || (pDef->flags & SQLITE_FUNC_LIKE)==0 ){
83383 return 0;
83386 /* The memcpy() statement assumes that the wildcard characters are
83387 ** the first three statements in the compareInfo structure. The
83388 ** asserts() that follow verify that assumption
83390 memcpy(aWc, pDef->pUserData, 3);
83391 assert( (char*)&likeInfoAlt == (char*)&likeInfoAlt.matchAll );
83392 assert( &((char*)&likeInfoAlt)[1] == (char*)&likeInfoAlt.matchOne );
83393 assert( &((char*)&likeInfoAlt)[2] == (char*)&likeInfoAlt.matchSet );
83394 *pIsNocase = (pDef->flags & SQLITE_FUNC_CASE)==0;
83395 return 1;
83399 ** All all of the FuncDef structures in the aBuiltinFunc[] array above
83400 ** to the global function hash table. This occurs at start-time (as
83401 ** a consequence of calling sqlite3_initialize()).
83403 ** After this routine runs
83405 SQLITE_PRIVATE void sqlite3RegisterGlobalFunctions(void){
83407 ** The following array holds FuncDef structures for all of the functions
83408 ** defined in this file.
83410 ** The array cannot be constant since changes are made to the
83411 ** FuncDef.pHash elements at start-time. The elements of this array
83412 ** are read-only after initialization is complete.
83414 static SQLITE_WSD FuncDef aBuiltinFunc[] = {
83415 FUNCTION(ltrim, 1, 1, 0, trimFunc ),
83416 FUNCTION(ltrim, 2, 1, 0, trimFunc ),
83417 FUNCTION(rtrim, 1, 2, 0, trimFunc ),
83418 FUNCTION(rtrim, 2, 2, 0, trimFunc ),
83419 FUNCTION(trim, 1, 3, 0, trimFunc ),
83420 FUNCTION(trim, 2, 3, 0, trimFunc ),
83421 FUNCTION(min, -1, 0, 1, minmaxFunc ),
83422 FUNCTION(min, 0, 0, 1, 0 ),
83423 AGGREGATE(min, 1, 0, 1, minmaxStep, minMaxFinalize ),
83424 FUNCTION(max, -1, 1, 1, minmaxFunc ),
83425 FUNCTION(max, 0, 1, 1, 0 ),
83426 AGGREGATE(max, 1, 1, 1, minmaxStep, minMaxFinalize ),
83427 FUNCTION(typeof, 1, 0, 0, typeofFunc ),
83428 FUNCTION(length, 1, 0, 0, lengthFunc ),
83429 FUNCTION(substr, 2, 0, 0, substrFunc ),
83430 FUNCTION(substr, 3, 0, 0, substrFunc ),
83431 FUNCTION(abs, 1, 0, 0, absFunc ),
83432 #ifndef SQLITE_OMIT_FLOATING_POINT
83433 FUNCTION(round, 1, 0, 0, roundFunc ),
83434 FUNCTION(round, 2, 0, 0, roundFunc ),
83435 #endif
83436 FUNCTION(upper, 1, 0, 0, upperFunc ),
83437 FUNCTION(lower, 1, 0, 0, lowerFunc ),
83438 FUNCTION(coalesce, 1, 0, 0, 0 ),
83439 FUNCTION(coalesce, 0, 0, 0, 0 ),
83440 /* FUNCTION(coalesce, -1, 0, 0, ifnullFunc ), */
83441 {-1,SQLITE_UTF8,SQLITE_FUNC_COALESCE,0,0,ifnullFunc,0,0,"coalesce",0,0},
83442 FUNCTION(hex, 1, 0, 0, hexFunc ),
83443 /* FUNCTION(ifnull, 2, 0, 0, ifnullFunc ), */
83444 {2,SQLITE_UTF8,SQLITE_FUNC_COALESCE,0,0,ifnullFunc,0,0,"ifnull",0,0},
83445 FUNCTION(random, 0, 0, 0, randomFunc ),
83446 FUNCTION(randomblob, 1, 0, 0, randomBlob ),
83447 FUNCTION(nullif, 2, 0, 1, nullifFunc ),
83448 FUNCTION(sqlite_version, 0, 0, 0, versionFunc ),
83449 FUNCTION(sqlite_source_id, 0, 0, 0, sourceidFunc ),
83450 #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
83451 FUNCTION(sqlite_compileoption_used,1, 0, 0, compileoptionusedFunc ),
83452 FUNCTION(sqlite_compileoption_get, 1, 0, 0, compileoptiongetFunc ),
83453 #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
83454 FUNCTION(quote, 1, 0, 0, quoteFunc ),
83455 FUNCTION(last_insert_rowid, 0, 0, 0, last_insert_rowid),
83456 FUNCTION(changes, 0, 0, 0, changes ),
83457 FUNCTION(total_changes, 0, 0, 0, total_changes ),
83458 FUNCTION(replace, 3, 0, 0, replaceFunc ),
83459 FUNCTION(zeroblob, 1, 0, 0, zeroblobFunc ),
83460 #ifdef SQLITE_SOUNDEX
83461 FUNCTION(soundex, 1, 0, 0, soundexFunc ),
83462 #endif
83463 #ifndef SQLITE_OMIT_LOAD_EXTENSION
83464 FUNCTION(load_extension, 1, 0, 0, loadExt ),
83465 FUNCTION(load_extension, 2, 0, 0, loadExt ),
83466 #endif
83467 AGGREGATE(sum, 1, 0, 0, sumStep, sumFinalize ),
83468 AGGREGATE(total, 1, 0, 0, sumStep, totalFinalize ),
83469 AGGREGATE(avg, 1, 0, 0, sumStep, avgFinalize ),
83470 /* AGGREGATE(count, 0, 0, 0, countStep, countFinalize ), */
83471 {0,SQLITE_UTF8,SQLITE_FUNC_COUNT,0,0,0,countStep,countFinalize,"count",0,0},
83472 AGGREGATE(count, 1, 0, 0, countStep, countFinalize ),
83473 AGGREGATE(group_concat, 1, 0, 0, groupConcatStep, groupConcatFinalize),
83474 AGGREGATE(group_concat, 2, 0, 0, groupConcatStep, groupConcatFinalize),
83476 LIKEFUNC(glob, 2, &globInfo, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE),
83477 #ifdef SQLITE_CASE_SENSITIVE_LIKE
83478 LIKEFUNC(like, 2, &likeInfoAlt, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE),
83479 LIKEFUNC(like, 3, &likeInfoAlt, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE),
83480 #else
83481 LIKEFUNC(like, 2, &likeInfoNorm, SQLITE_FUNC_LIKE),
83482 LIKEFUNC(like, 3, &likeInfoNorm, SQLITE_FUNC_LIKE),
83483 #endif
83486 int i;
83487 FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
83488 FuncDef *aFunc = (FuncDef*)&GLOBAL(FuncDef, aBuiltinFunc);
83490 for(i=0; i<ArraySize(aBuiltinFunc); i++){
83491 sqlite3FuncDefInsert(pHash, &aFunc[i]);
83493 sqlite3RegisterDateTimeFunctions();
83494 #ifndef SQLITE_OMIT_ALTERTABLE
83495 sqlite3AlterFunctions();
83496 #endif
83499 /************** End of func.c ************************************************/
83500 /************** Begin file fkey.c ********************************************/
83503 ** The author disclaims copyright to this source code. In place of
83504 ** a legal notice, here is a blessing:
83506 ** May you do good and not evil.
83507 ** May you find forgiveness for yourself and forgive others.
83508 ** May you share freely, never taking more than you give.
83510 *************************************************************************
83511 ** This file contains code used by the compiler to add foreign key
83512 ** support to compiled SQL statements.
83515 #ifndef SQLITE_OMIT_FOREIGN_KEY
83516 #ifndef SQLITE_OMIT_TRIGGER
83519 ** Deferred and Immediate FKs
83520 ** --------------------------
83522 ** Foreign keys in SQLite come in two flavours: deferred and immediate.
83523 ** If an immediate foreign key constraint is violated, SQLITE_CONSTRAINT
83524 ** is returned and the current statement transaction rolled back. If a
83525 ** deferred foreign key constraint is violated, no action is taken
83526 ** immediately. However if the application attempts to commit the
83527 ** transaction before fixing the constraint violation, the attempt fails.
83529 ** Deferred constraints are implemented using a simple counter associated
83530 ** with the database handle. The counter is set to zero each time a
83531 ** database transaction is opened. Each time a statement is executed
83532 ** that causes a foreign key violation, the counter is incremented. Each
83533 ** time a statement is executed that removes an existing violation from
83534 ** the database, the counter is decremented. When the transaction is
83535 ** committed, the commit fails if the current value of the counter is
83536 ** greater than zero. This scheme has two big drawbacks:
83538 ** * When a commit fails due to a deferred foreign key constraint,
83539 ** there is no way to tell which foreign constraint is not satisfied,
83540 ** or which row it is not satisfied for.
83542 ** * If the database contains foreign key violations when the
83543 ** transaction is opened, this may cause the mechanism to malfunction.
83545 ** Despite these problems, this approach is adopted as it seems simpler
83546 ** than the alternatives.
83548 ** INSERT operations:
83550 ** I.1) For each FK for which the table is the child table, search
83551 ** the parent table for a match. If none is found increment the
83552 ** constraint counter.
83554 ** I.2) For each FK for which the table is the parent table,
83555 ** search the child table for rows that correspond to the new
83556 ** row in the parent table. Decrement the counter for each row
83557 ** found (as the constraint is now satisfied).
83559 ** DELETE operations:
83561 ** D.1) For each FK for which the table is the child table,
83562 ** search the parent table for a row that corresponds to the
83563 ** deleted row in the child table. If such a row is not found,
83564 ** decrement the counter.
83566 ** D.2) For each FK for which the table is the parent table, search
83567 ** the child table for rows that correspond to the deleted row
83568 ** in the parent table. For each found increment the counter.
83570 ** UPDATE operations:
83572 ** An UPDATE command requires that all 4 steps above are taken, but only
83573 ** for FK constraints for which the affected columns are actually
83574 ** modified (values must be compared at runtime).
83576 ** Note that I.1 and D.1 are very similar operations, as are I.2 and D.2.
83577 ** This simplifies the implementation a bit.
83579 ** For the purposes of immediate FK constraints, the OR REPLACE conflict
83580 ** resolution is considered to delete rows before the new row is inserted.
83581 ** If a delete caused by OR REPLACE violates an FK constraint, an exception
83582 ** is thrown, even if the FK constraint would be satisfied after the new
83583 ** row is inserted.
83585 ** Immediate constraints are usually handled similarly. The only difference
83586 ** is that the counter used is stored as part of each individual statement
83587 ** object (struct Vdbe). If, after the statement has run, its immediate
83588 ** constraint counter is greater than zero, it returns SQLITE_CONSTRAINT
83589 ** and the statement transaction is rolled back. An exception is an INSERT
83590 ** statement that inserts a single row only (no triggers). In this case,
83591 ** instead of using a counter, an exception is thrown immediately if the
83592 ** INSERT violates a foreign key constraint. This is necessary as such
83593 ** an INSERT does not open a statement transaction.
83595 ** TODO: How should dropping a table be handled? How should renaming a
83596 ** table be handled?
83599 ** Query API Notes
83600 ** ---------------
83602 ** Before coding an UPDATE or DELETE row operation, the code-generator
83603 ** for those two operations needs to know whether or not the operation
83604 ** requires any FK processing and, if so, which columns of the original
83605 ** row are required by the FK processing VDBE code (i.e. if FKs were
83606 ** implemented using triggers, which of the old.* columns would be
83607 ** accessed). No information is required by the code-generator before
83608 ** coding an INSERT operation. The functions used by the UPDATE/DELETE
83609 ** generation code to query for this information are:
83611 ** sqlite3FkRequired() - Test to see if FK processing is required.
83612 ** sqlite3FkOldmask() - Query for the set of required old.* columns.
83615 ** Externally accessible module functions
83616 ** --------------------------------------
83618 ** sqlite3FkCheck() - Check for foreign key violations.
83619 ** sqlite3FkActions() - Code triggers for ON UPDATE/ON DELETE actions.
83620 ** sqlite3FkDelete() - Delete an FKey structure.
83624 ** VDBE Calling Convention
83625 ** -----------------------
83627 ** Example:
83629 ** For the following INSERT statement:
83631 ** CREATE TABLE t1(a, b INTEGER PRIMARY KEY, c);
83632 ** INSERT INTO t1 VALUES(1, 2, 3.1);
83634 ** Register (x): 2 (type integer)
83635 ** Register (x+1): 1 (type integer)
83636 ** Register (x+2): NULL (type NULL)
83637 ** Register (x+3): 3.1 (type real)
83641 ** A foreign key constraint requires that the key columns in the parent
83642 ** table are collectively subject to a UNIQUE or PRIMARY KEY constraint.
83643 ** Given that pParent is the parent table for foreign key constraint pFKey,
83644 ** search the schema a unique index on the parent key columns.
83646 ** If successful, zero is returned. If the parent key is an INTEGER PRIMARY
83647 ** KEY column, then output variable *ppIdx is set to NULL. Otherwise, *ppIdx
83648 ** is set to point to the unique index.
83650 ** If the parent key consists of a single column (the foreign key constraint
83651 ** is not a composite foreign key), output variable *paiCol is set to NULL.
83652 ** Otherwise, it is set to point to an allocated array of size N, where
83653 ** N is the number of columns in the parent key. The first element of the
83654 ** array is the index of the child table column that is mapped by the FK
83655 ** constraint to the parent table column stored in the left-most column
83656 ** of index *ppIdx. The second element of the array is the index of the
83657 ** child table column that corresponds to the second left-most column of
83658 ** *ppIdx, and so on.
83660 ** If the required index cannot be found, either because:
83662 ** 1) The named parent key columns do not exist, or
83664 ** 2) The named parent key columns do exist, but are not subject to a
83665 ** UNIQUE or PRIMARY KEY constraint, or
83667 ** 3) No parent key columns were provided explicitly as part of the
83668 ** foreign key definition, and the parent table does not have a
83669 ** PRIMARY KEY, or
83671 ** 4) No parent key columns were provided explicitly as part of the
83672 ** foreign key definition, and the PRIMARY KEY of the parent table
83673 ** consists of a a different number of columns to the child key in
83674 ** the child table.
83676 ** then non-zero is returned, and a "foreign key mismatch" error loaded
83677 ** into pParse. If an OOM error occurs, non-zero is returned and the
83678 ** pParse->db->mallocFailed flag is set.
83680 static int locateFkeyIndex(
83681 Parse *pParse, /* Parse context to store any error in */
83682 Table *pParent, /* Parent table of FK constraint pFKey */
83683 FKey *pFKey, /* Foreign key to find index for */
83684 Index **ppIdx, /* OUT: Unique index on parent table */
83685 int **paiCol /* OUT: Map of index columns in pFKey */
83687 Index *pIdx = 0; /* Value to return via *ppIdx */
83688 int *aiCol = 0; /* Value to return via *paiCol */
83689 int nCol = pFKey->nCol; /* Number of columns in parent key */
83690 char *zKey = pFKey->aCol[0].zCol; /* Name of left-most parent key column */
83692 /* The caller is responsible for zeroing output parameters. */
83693 assert( ppIdx && *ppIdx==0 );
83694 assert( !paiCol || *paiCol==0 );
83695 assert( pParse );
83697 /* If this is a non-composite (single column) foreign key, check if it
83698 ** maps to the INTEGER PRIMARY KEY of table pParent. If so, leave *ppIdx
83699 ** and *paiCol set to zero and return early.
83701 ** Otherwise, for a composite foreign key (more than one column), allocate
83702 ** space for the aiCol array (returned via output parameter *paiCol).
83703 ** Non-composite foreign keys do not require the aiCol array.
83705 if( nCol==1 ){
83706 /* The FK maps to the IPK if any of the following are true:
83708 ** 1) There is an INTEGER PRIMARY KEY column and the FK is implicitly
83709 ** mapped to the primary key of table pParent, or
83710 ** 2) The FK is explicitly mapped to a column declared as INTEGER
83711 ** PRIMARY KEY.
83713 if( pParent->iPKey>=0 ){
83714 if( !zKey ) return 0;
83715 if( !sqlite3StrICmp(pParent->aCol[pParent->iPKey].zName, zKey) ) return 0;
83717 }else if( paiCol ){
83718 assert( nCol>1 );
83719 aiCol = (int *)sqlite3DbMallocRaw(pParse->db, nCol*sizeof(int));
83720 if( !aiCol ) return 1;
83721 *paiCol = aiCol;
83724 for(pIdx=pParent->pIndex; pIdx; pIdx=pIdx->pNext){
83725 if( pIdx->nColumn==nCol && pIdx->onError!=OE_None ){
83726 /* pIdx is a UNIQUE index (or a PRIMARY KEY) and has the right number
83727 ** of columns. If each indexed column corresponds to a foreign key
83728 ** column of pFKey, then this index is a winner. */
83730 if( zKey==0 ){
83731 /* If zKey is NULL, then this foreign key is implicitly mapped to
83732 ** the PRIMARY KEY of table pParent. The PRIMARY KEY index may be
83733 ** identified by the test (Index.autoIndex==2). */
83734 if( pIdx->autoIndex==2 ){
83735 if( aiCol ){
83736 int i;
83737 for(i=0; i<nCol; i++) aiCol[i] = pFKey->aCol[i].iFrom;
83739 break;
83741 }else{
83742 /* If zKey is non-NULL, then this foreign key was declared to
83743 ** map to an explicit list of columns in table pParent. Check if this
83744 ** index matches those columns. Also, check that the index uses
83745 ** the default collation sequences for each column. */
83746 int i, j;
83747 for(i=0; i<nCol; i++){
83748 int iCol = pIdx->aiColumn[i]; /* Index of column in parent tbl */
83749 char *zDfltColl; /* Def. collation for column */
83750 char *zIdxCol; /* Name of indexed column */
83752 /* If the index uses a collation sequence that is different from
83753 ** the default collation sequence for the column, this index is
83754 ** unusable. Bail out early in this case. */
83755 zDfltColl = pParent->aCol[iCol].zColl;
83756 if( !zDfltColl ){
83757 zDfltColl = "BINARY";
83759 if( sqlite3StrICmp(pIdx->azColl[i], zDfltColl) ) break;
83761 zIdxCol = pParent->aCol[iCol].zName;
83762 for(j=0; j<nCol; j++){
83763 if( sqlite3StrICmp(pFKey->aCol[j].zCol, zIdxCol)==0 ){
83764 if( aiCol ) aiCol[i] = pFKey->aCol[j].iFrom;
83765 break;
83768 if( j==nCol ) break;
83770 if( i==nCol ) break; /* pIdx is usable */
83775 if( !pIdx ){
83776 if( !pParse->disableTriggers ){
83777 sqlite3ErrorMsg(pParse, "foreign key mismatch");
83779 sqlite3DbFree(pParse->db, aiCol);
83780 return 1;
83783 *ppIdx = pIdx;
83784 return 0;
83788 ** This function is called when a row is inserted into or deleted from the
83789 ** child table of foreign key constraint pFKey. If an SQL UPDATE is executed
83790 ** on the child table of pFKey, this function is invoked twice for each row
83791 ** affected - once to "delete" the old row, and then again to "insert" the
83792 ** new row.
83794 ** Each time it is called, this function generates VDBE code to locate the
83795 ** row in the parent table that corresponds to the row being inserted into
83796 ** or deleted from the child table. If the parent row can be found, no
83797 ** special action is taken. Otherwise, if the parent row can *not* be
83798 ** found in the parent table:
83800 ** Operation | FK type | Action taken
83801 ** --------------------------------------------------------------------------
83802 ** INSERT immediate Increment the "immediate constraint counter".
83804 ** DELETE immediate Decrement the "immediate constraint counter".
83806 ** INSERT deferred Increment the "deferred constraint counter".
83808 ** DELETE deferred Decrement the "deferred constraint counter".
83810 ** These operations are identified in the comment at the top of this file
83811 ** (fkey.c) as "I.1" and "D.1".
83813 static void fkLookupParent(
83814 Parse *pParse, /* Parse context */
83815 int iDb, /* Index of database housing pTab */
83816 Table *pTab, /* Parent table of FK pFKey */
83817 Index *pIdx, /* Unique index on parent key columns in pTab */
83818 FKey *pFKey, /* Foreign key constraint */
83819 int *aiCol, /* Map from parent key columns to child table columns */
83820 int regData, /* Address of array containing child table row */
83821 int nIncr, /* Increment constraint counter by this */
83822 int isIgnore /* If true, pretend pTab contains all NULL values */
83824 int i; /* Iterator variable */
83825 Vdbe *v = sqlite3GetVdbe(pParse); /* Vdbe to add code to */
83826 int iCur = pParse->nTab - 1; /* Cursor number to use */
83827 int iOk = sqlite3VdbeMakeLabel(v); /* jump here if parent key found */
83829 /* If nIncr is less than zero, then check at runtime if there are any
83830 ** outstanding constraints to resolve. If there are not, there is no need
83831 ** to check if deleting this row resolves any outstanding violations.
83833 ** Check if any of the key columns in the child table row are NULL. If
83834 ** any are, then the constraint is considered satisfied. No need to
83835 ** search for a matching row in the parent table. */
83836 if( nIncr<0 ){
83837 sqlite3VdbeAddOp2(v, OP_FkIfZero, pFKey->isDeferred, iOk);
83839 for(i=0; i<pFKey->nCol; i++){
83840 int iReg = aiCol[i] + regData + 1;
83841 sqlite3VdbeAddOp2(v, OP_IsNull, iReg, iOk);
83844 if( isIgnore==0 ){
83845 if( pIdx==0 ){
83846 /* If pIdx is NULL, then the parent key is the INTEGER PRIMARY KEY
83847 ** column of the parent table (table pTab). */
83848 int iMustBeInt; /* Address of MustBeInt instruction */
83849 int regTemp = sqlite3GetTempReg(pParse);
83851 /* Invoke MustBeInt to coerce the child key value to an integer (i.e.
83852 ** apply the affinity of the parent key). If this fails, then there
83853 ** is no matching parent key. Before using MustBeInt, make a copy of
83854 ** the value. Otherwise, the value inserted into the child key column
83855 ** will have INTEGER affinity applied to it, which may not be correct. */
83856 sqlite3VdbeAddOp2(v, OP_SCopy, aiCol[0]+1+regData, regTemp);
83857 iMustBeInt = sqlite3VdbeAddOp2(v, OP_MustBeInt, regTemp, 0);
83859 /* If the parent table is the same as the child table, and we are about
83860 ** to increment the constraint-counter (i.e. this is an INSERT operation),
83861 ** then check if the row being inserted matches itself. If so, do not
83862 ** increment the constraint-counter. */
83863 if( pTab==pFKey->pFrom && nIncr==1 ){
83864 sqlite3VdbeAddOp3(v, OP_Eq, regData, iOk, regTemp);
83867 sqlite3OpenTable(pParse, iCur, iDb, pTab, OP_OpenRead);
83868 sqlite3VdbeAddOp3(v, OP_NotExists, iCur, 0, regTemp);
83869 sqlite3VdbeAddOp2(v, OP_Goto, 0, iOk);
83870 sqlite3VdbeJumpHere(v, sqlite3VdbeCurrentAddr(v)-2);
83871 sqlite3VdbeJumpHere(v, iMustBeInt);
83872 sqlite3ReleaseTempReg(pParse, regTemp);
83873 }else{
83874 int nCol = pFKey->nCol;
83875 int regTemp = sqlite3GetTempRange(pParse, nCol);
83876 int regRec = sqlite3GetTempReg(pParse);
83877 KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIdx);
83879 sqlite3VdbeAddOp3(v, OP_OpenRead, iCur, pIdx->tnum, iDb);
83880 sqlite3VdbeChangeP4(v, -1, (char*)pKey, P4_KEYINFO_HANDOFF);
83881 for(i=0; i<nCol; i++){
83882 sqlite3VdbeAddOp2(v, OP_Copy, aiCol[i]+1+regData, regTemp+i);
83885 /* If the parent table is the same as the child table, and we are about
83886 ** to increment the constraint-counter (i.e. this is an INSERT operation),
83887 ** then check if the row being inserted matches itself. If so, do not
83888 ** increment the constraint-counter. */
83889 if( pTab==pFKey->pFrom && nIncr==1 ){
83890 int iJump = sqlite3VdbeCurrentAddr(v) + nCol + 1;
83891 for(i=0; i<nCol; i++){
83892 int iChild = aiCol[i]+1+regData;
83893 int iParent = pIdx->aiColumn[i]+1+regData;
83894 sqlite3VdbeAddOp3(v, OP_Ne, iChild, iJump, iParent);
83896 sqlite3VdbeAddOp2(v, OP_Goto, 0, iOk);
83899 sqlite3VdbeAddOp3(v, OP_MakeRecord, regTemp, nCol, regRec);
83900 sqlite3VdbeChangeP4(v, -1, sqlite3IndexAffinityStr(v,pIdx), P4_TRANSIENT);
83901 sqlite3VdbeAddOp4Int(v, OP_Found, iCur, iOk, regRec, 0);
83903 sqlite3ReleaseTempReg(pParse, regRec);
83904 sqlite3ReleaseTempRange(pParse, regTemp, nCol);
83908 if( !pFKey->isDeferred && !pParse->pToplevel && !pParse->isMultiWrite ){
83909 /* Special case: If this is an INSERT statement that will insert exactly
83910 ** one row into the table, raise a constraint immediately instead of
83911 ** incrementing a counter. This is necessary as the VM code is being
83912 ** generated for will not open a statement transaction. */
83913 assert( nIncr==1 );
83914 sqlite3HaltConstraint(
83915 pParse, OE_Abort, "foreign key constraint failed", P4_STATIC
83917 }else{
83918 if( nIncr>0 && pFKey->isDeferred==0 ){
83919 sqlite3ParseToplevel(pParse)->mayAbort = 1;
83921 sqlite3VdbeAddOp2(v, OP_FkCounter, pFKey->isDeferred, nIncr);
83924 sqlite3VdbeResolveLabel(v, iOk);
83925 sqlite3VdbeAddOp1(v, OP_Close, iCur);
83929 ** This function is called to generate code executed when a row is deleted
83930 ** from the parent table of foreign key constraint pFKey and, if pFKey is
83931 ** deferred, when a row is inserted into the same table. When generating
83932 ** code for an SQL UPDATE operation, this function may be called twice -
83933 ** once to "delete" the old row and once to "insert" the new row.
83935 ** The code generated by this function scans through the rows in the child
83936 ** table that correspond to the parent table row being deleted or inserted.
83937 ** For each child row found, one of the following actions is taken:
83939 ** Operation | FK type | Action taken
83940 ** --------------------------------------------------------------------------
83941 ** DELETE immediate Increment the "immediate constraint counter".
83942 ** Or, if the ON (UPDATE|DELETE) action is RESTRICT,
83943 ** throw a "foreign key constraint failed" exception.
83945 ** INSERT immediate Decrement the "immediate constraint counter".
83947 ** DELETE deferred Increment the "deferred constraint counter".
83948 ** Or, if the ON (UPDATE|DELETE) action is RESTRICT,
83949 ** throw a "foreign key constraint failed" exception.
83951 ** INSERT deferred Decrement the "deferred constraint counter".
83953 ** These operations are identified in the comment at the top of this file
83954 ** (fkey.c) as "I.2" and "D.2".
83956 static void fkScanChildren(
83957 Parse *pParse, /* Parse context */
83958 SrcList *pSrc, /* SrcList containing the table to scan */
83959 Table *pTab,
83960 Index *pIdx, /* Foreign key index */
83961 FKey *pFKey, /* Foreign key relationship */
83962 int *aiCol, /* Map from pIdx cols to child table cols */
83963 int regData, /* Referenced table data starts here */
83964 int nIncr /* Amount to increment deferred counter by */
83966 sqlite3 *db = pParse->db; /* Database handle */
83967 int i; /* Iterator variable */
83968 Expr *pWhere = 0; /* WHERE clause to scan with */
83969 NameContext sNameContext; /* Context used to resolve WHERE clause */
83970 WhereInfo *pWInfo; /* Context used by sqlite3WhereXXX() */
83971 int iFkIfZero = 0; /* Address of OP_FkIfZero */
83972 Vdbe *v = sqlite3GetVdbe(pParse);
83974 assert( !pIdx || pIdx->pTable==pTab );
83976 if( nIncr<0 ){
83977 iFkIfZero = sqlite3VdbeAddOp2(v, OP_FkIfZero, pFKey->isDeferred, 0);
83980 /* Create an Expr object representing an SQL expression like:
83982 ** <parent-key1> = <child-key1> AND <parent-key2> = <child-key2> ...
83984 ** The collation sequence used for the comparison should be that of
83985 ** the parent key columns. The affinity of the parent key column should
83986 ** be applied to each child key value before the comparison takes place.
83988 for(i=0; i<pFKey->nCol; i++){
83989 Expr *pLeft; /* Value from parent table row */
83990 Expr *pRight; /* Column ref to child table */
83991 Expr *pEq; /* Expression (pLeft = pRight) */
83992 int iCol; /* Index of column in child table */
83993 const char *zCol; /* Name of column in child table */
83995 pLeft = sqlite3Expr(db, TK_REGISTER, 0);
83996 if( pLeft ){
83997 /* Set the collation sequence and affinity of the LHS of each TK_EQ
83998 ** expression to the parent key column defaults. */
83999 if( pIdx ){
84000 Column *pCol;
84001 iCol = pIdx->aiColumn[i];
84002 pCol = &pTab->aCol[iCol];
84003 if( pTab->iPKey==iCol ) iCol = -1;
84004 pLeft->iTable = regData+iCol+1;
84005 pLeft->affinity = pCol->affinity;
84006 pLeft->pColl = sqlite3LocateCollSeq(pParse, pCol->zColl);
84007 }else{
84008 pLeft->iTable = regData;
84009 pLeft->affinity = SQLITE_AFF_INTEGER;
84012 iCol = aiCol ? aiCol[i] : pFKey->aCol[0].iFrom;
84013 assert( iCol>=0 );
84014 zCol = pFKey->pFrom->aCol[iCol].zName;
84015 pRight = sqlite3Expr(db, TK_ID, zCol);
84016 pEq = sqlite3PExpr(pParse, TK_EQ, pLeft, pRight, 0);
84017 pWhere = sqlite3ExprAnd(db, pWhere, pEq);
84020 /* If the child table is the same as the parent table, and this scan
84021 ** is taking place as part of a DELETE operation (operation D.2), omit the
84022 ** row being deleted from the scan by adding ($rowid != rowid) to the WHERE
84023 ** clause, where $rowid is the rowid of the row being deleted. */
84024 if( pTab==pFKey->pFrom && nIncr>0 ){
84025 Expr *pEq; /* Expression (pLeft = pRight) */
84026 Expr *pLeft; /* Value from parent table row */
84027 Expr *pRight; /* Column ref to child table */
84028 pLeft = sqlite3Expr(db, TK_REGISTER, 0);
84029 pRight = sqlite3Expr(db, TK_COLUMN, 0);
84030 if( pLeft && pRight ){
84031 pLeft->iTable = regData;
84032 pLeft->affinity = SQLITE_AFF_INTEGER;
84033 pRight->iTable = pSrc->a[0].iCursor;
84034 pRight->iColumn = -1;
84036 pEq = sqlite3PExpr(pParse, TK_NE, pLeft, pRight, 0);
84037 pWhere = sqlite3ExprAnd(db, pWhere, pEq);
84040 /* Resolve the references in the WHERE clause. */
84041 memset(&sNameContext, 0, sizeof(NameContext));
84042 sNameContext.pSrcList = pSrc;
84043 sNameContext.pParse = pParse;
84044 sqlite3ResolveExprNames(&sNameContext, pWhere);
84046 /* Create VDBE to loop through the entries in pSrc that match the WHERE
84047 ** clause. If the constraint is not deferred, throw an exception for
84048 ** each row found. Otherwise, for deferred constraints, increment the
84049 ** deferred constraint counter by nIncr for each row selected. */
84050 pWInfo = sqlite3WhereBegin(pParse, pSrc, pWhere, 0, 0);
84051 if( nIncr>0 && pFKey->isDeferred==0 ){
84052 sqlite3ParseToplevel(pParse)->mayAbort = 1;
84054 sqlite3VdbeAddOp2(v, OP_FkCounter, pFKey->isDeferred, nIncr);
84055 if( pWInfo ){
84056 sqlite3WhereEnd(pWInfo);
84059 /* Clean up the WHERE clause constructed above. */
84060 sqlite3ExprDelete(db, pWhere);
84061 if( iFkIfZero ){
84062 sqlite3VdbeJumpHere(v, iFkIfZero);
84067 ** This function returns a pointer to the head of a linked list of FK
84068 ** constraints for which table pTab is the parent table. For example,
84069 ** given the following schema:
84071 ** CREATE TABLE t1(a PRIMARY KEY);
84072 ** CREATE TABLE t2(b REFERENCES t1(a);
84074 ** Calling this function with table "t1" as an argument returns a pointer
84075 ** to the FKey structure representing the foreign key constraint on table
84076 ** "t2". Calling this function with "t2" as the argument would return a
84077 ** NULL pointer (as there are no FK constraints for which t2 is the parent
84078 ** table).
84080 SQLITE_PRIVATE FKey *sqlite3FkReferences(Table *pTab){
84081 int nName = sqlite3Strlen30(pTab->zName);
84082 return (FKey *)sqlite3HashFind(&pTab->pSchema->fkeyHash, pTab->zName, nName);
84086 ** The second argument is a Trigger structure allocated by the
84087 ** fkActionTrigger() routine. This function deletes the Trigger structure
84088 ** and all of its sub-components.
84090 ** The Trigger structure or any of its sub-components may be allocated from
84091 ** the lookaside buffer belonging to database handle dbMem.
84093 static void fkTriggerDelete(sqlite3 *dbMem, Trigger *p){
84094 if( p ){
84095 TriggerStep *pStep = p->step_list;
84096 sqlite3ExprDelete(dbMem, pStep->pWhere);
84097 sqlite3ExprListDelete(dbMem, pStep->pExprList);
84098 sqlite3SelectDelete(dbMem, pStep->pSelect);
84099 sqlite3ExprDelete(dbMem, p->pWhen);
84100 sqlite3DbFree(dbMem, p);
84105 ** This function is called to generate code that runs when table pTab is
84106 ** being dropped from the database. The SrcList passed as the second argument
84107 ** to this function contains a single entry guaranteed to resolve to
84108 ** table pTab.
84110 ** Normally, no code is required. However, if either
84112 ** (a) The table is the parent table of a FK constraint, or
84113 ** (b) The table is the child table of a deferred FK constraint and it is
84114 ** determined at runtime that there are outstanding deferred FK
84115 ** constraint violations in the database,
84117 ** then the equivalent of "DELETE FROM <tbl>" is executed before dropping
84118 ** the table from the database. Triggers are disabled while running this
84119 ** DELETE, but foreign key actions are not.
84121 SQLITE_PRIVATE void sqlite3FkDropTable(Parse *pParse, SrcList *pName, Table *pTab){
84122 sqlite3 *db = pParse->db;
84123 if( (db->flags&SQLITE_ForeignKeys) && !IsVirtual(pTab) && !pTab->pSelect ){
84124 int iSkip = 0;
84125 Vdbe *v = sqlite3GetVdbe(pParse);
84127 assert( v ); /* VDBE has already been allocated */
84128 if( sqlite3FkReferences(pTab)==0 ){
84129 /* Search for a deferred foreign key constraint for which this table
84130 ** is the child table. If one cannot be found, return without
84131 ** generating any VDBE code. If one can be found, then jump over
84132 ** the entire DELETE if there are no outstanding deferred constraints
84133 ** when this statement is run. */
84134 FKey *p;
84135 for(p=pTab->pFKey; p; p=p->pNextFrom){
84136 if( p->isDeferred ) break;
84138 if( !p ) return;
84139 iSkip = sqlite3VdbeMakeLabel(v);
84140 sqlite3VdbeAddOp2(v, OP_FkIfZero, 1, iSkip);
84143 pParse->disableTriggers = 1;
84144 sqlite3DeleteFrom(pParse, sqlite3SrcListDup(db, pName, 0), 0);
84145 pParse->disableTriggers = 0;
84147 /* If the DELETE has generated immediate foreign key constraint
84148 ** violations, halt the VDBE and return an error at this point, before
84149 ** any modifications to the schema are made. This is because statement
84150 ** transactions are not able to rollback schema changes. */
84151 sqlite3VdbeAddOp2(v, OP_FkIfZero, 0, sqlite3VdbeCurrentAddr(v)+2);
84152 sqlite3HaltConstraint(
84153 pParse, OE_Abort, "foreign key constraint failed", P4_STATIC
84156 if( iSkip ){
84157 sqlite3VdbeResolveLabel(v, iSkip);
84163 ** This function is called when inserting, deleting or updating a row of
84164 ** table pTab to generate VDBE code to perform foreign key constraint
84165 ** processing for the operation.
84167 ** For a DELETE operation, parameter regOld is passed the index of the
84168 ** first register in an array of (pTab->nCol+1) registers containing the
84169 ** rowid of the row being deleted, followed by each of the column values
84170 ** of the row being deleted, from left to right. Parameter regNew is passed
84171 ** zero in this case.
84173 ** For an INSERT operation, regOld is passed zero and regNew is passed the
84174 ** first register of an array of (pTab->nCol+1) registers containing the new
84175 ** row data.
84177 ** For an UPDATE operation, this function is called twice. Once before
84178 ** the original record is deleted from the table using the calling convention
84179 ** described for DELETE. Then again after the original record is deleted
84180 ** but before the new record is inserted using the INSERT convention.
84182 SQLITE_PRIVATE void sqlite3FkCheck(
84183 Parse *pParse, /* Parse context */
84184 Table *pTab, /* Row is being deleted from this table */
84185 int regOld, /* Previous row data is stored here */
84186 int regNew /* New row data is stored here */
84188 sqlite3 *db = pParse->db; /* Database handle */
84189 FKey *pFKey; /* Used to iterate through FKs */
84190 int iDb; /* Index of database containing pTab */
84191 const char *zDb; /* Name of database containing pTab */
84192 int isIgnoreErrors = pParse->disableTriggers;
84194 /* Exactly one of regOld and regNew should be non-zero. */
84195 assert( (regOld==0)!=(regNew==0) );
84197 /* If foreign-keys are disabled, this function is a no-op. */
84198 if( (db->flags&SQLITE_ForeignKeys)==0 ) return;
84200 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
84201 zDb = db->aDb[iDb].zName;
84203 /* Loop through all the foreign key constraints for which pTab is the
84204 ** child table (the table that the foreign key definition is part of). */
84205 for(pFKey=pTab->pFKey; pFKey; pFKey=pFKey->pNextFrom){
84206 Table *pTo; /* Parent table of foreign key pFKey */
84207 Index *pIdx = 0; /* Index on key columns in pTo */
84208 int *aiFree = 0;
84209 int *aiCol;
84210 int iCol;
84211 int i;
84212 int isIgnore = 0;
84214 /* Find the parent table of this foreign key. Also find a unique index
84215 ** on the parent key columns in the parent table. If either of these
84216 ** schema items cannot be located, set an error in pParse and return
84217 ** early. */
84218 if( pParse->disableTriggers ){
84219 pTo = sqlite3FindTable(db, pFKey->zTo, zDb);
84220 }else{
84221 pTo = sqlite3LocateTable(pParse, 0, pFKey->zTo, zDb);
84223 if( !pTo || locateFkeyIndex(pParse, pTo, pFKey, &pIdx, &aiFree) ){
84224 if( !isIgnoreErrors || db->mallocFailed ) return;
84225 continue;
84227 assert( pFKey->nCol==1 || (aiFree && pIdx) );
84229 if( aiFree ){
84230 aiCol = aiFree;
84231 }else{
84232 iCol = pFKey->aCol[0].iFrom;
84233 aiCol = &iCol;
84235 for(i=0; i<pFKey->nCol; i++){
84236 if( aiCol[i]==pTab->iPKey ){
84237 aiCol[i] = -1;
84239 #ifndef SQLITE_OMIT_AUTHORIZATION
84240 /* Request permission to read the parent key columns. If the
84241 ** authorization callback returns SQLITE_IGNORE, behave as if any
84242 ** values read from the parent table are NULL. */
84243 if( db->xAuth ){
84244 int rcauth;
84245 char *zCol = pTo->aCol[pIdx ? pIdx->aiColumn[i] : pTo->iPKey].zName;
84246 rcauth = sqlite3AuthReadCol(pParse, pTo->zName, zCol, iDb);
84247 isIgnore = (rcauth==SQLITE_IGNORE);
84249 #endif
84252 /* Take a shared-cache advisory read-lock on the parent table. Allocate
84253 ** a cursor to use to search the unique index on the parent key columns
84254 ** in the parent table. */
84255 sqlite3TableLock(pParse, iDb, pTo->tnum, 0, pTo->zName);
84256 pParse->nTab++;
84258 if( regOld!=0 ){
84259 /* A row is being removed from the child table. Search for the parent.
84260 ** If the parent does not exist, removing the child row resolves an
84261 ** outstanding foreign key constraint violation. */
84262 fkLookupParent(pParse, iDb, pTo, pIdx, pFKey, aiCol, regOld, -1,isIgnore);
84264 if( regNew!=0 ){
84265 /* A row is being added to the child table. If a parent row cannot
84266 ** be found, adding the child row has violated the FK constraint. */
84267 fkLookupParent(pParse, iDb, pTo, pIdx, pFKey, aiCol, regNew, +1,isIgnore);
84270 sqlite3DbFree(db, aiFree);
84273 /* Loop through all the foreign key constraints that refer to this table */
84274 for(pFKey = sqlite3FkReferences(pTab); pFKey; pFKey=pFKey->pNextTo){
84275 Index *pIdx = 0; /* Foreign key index for pFKey */
84276 SrcList *pSrc;
84277 int *aiCol = 0;
84279 if( !pFKey->isDeferred && !pParse->pToplevel && !pParse->isMultiWrite ){
84280 assert( regOld==0 && regNew!=0 );
84281 /* Inserting a single row into a parent table cannot cause an immediate
84282 ** foreign key violation. So do nothing in this case. */
84283 continue;
84286 if( locateFkeyIndex(pParse, pTab, pFKey, &pIdx, &aiCol) ){
84287 if( !isIgnoreErrors || db->mallocFailed ) return;
84288 continue;
84290 assert( aiCol || pFKey->nCol==1 );
84292 /* Create a SrcList structure containing a single table (the table
84293 ** the foreign key that refers to this table is attached to). This
84294 ** is required for the sqlite3WhereXXX() interface. */
84295 pSrc = sqlite3SrcListAppend(db, 0, 0, 0);
84296 if( pSrc ){
84297 struct SrcList_item *pItem = pSrc->a;
84298 pItem->pTab = pFKey->pFrom;
84299 pItem->zName = pFKey->pFrom->zName;
84300 pItem->pTab->nRef++;
84301 pItem->iCursor = pParse->nTab++;
84303 if( regNew!=0 ){
84304 fkScanChildren(pParse, pSrc, pTab, pIdx, pFKey, aiCol, regNew, -1);
84306 if( regOld!=0 ){
84307 /* If there is a RESTRICT action configured for the current operation
84308 ** on the parent table of this FK, then throw an exception
84309 ** immediately if the FK constraint is violated, even if this is a
84310 ** deferred trigger. That's what RESTRICT means. To defer checking
84311 ** the constraint, the FK should specify NO ACTION (represented
84312 ** using OE_None). NO ACTION is the default. */
84313 fkScanChildren(pParse, pSrc, pTab, pIdx, pFKey, aiCol, regOld, 1);
84315 pItem->zName = 0;
84316 sqlite3SrcListDelete(db, pSrc);
84318 sqlite3DbFree(db, aiCol);
84322 #define COLUMN_MASK(x) (((x)>31) ? 0xffffffff : ((u32)1<<(x)))
84325 ** This function is called before generating code to update or delete a
84326 ** row contained in table pTab.
84328 SQLITE_PRIVATE u32 sqlite3FkOldmask(
84329 Parse *pParse, /* Parse context */
84330 Table *pTab /* Table being modified */
84332 u32 mask = 0;
84333 if( pParse->db->flags&SQLITE_ForeignKeys ){
84334 FKey *p;
84335 int i;
84336 for(p=pTab->pFKey; p; p=p->pNextFrom){
84337 for(i=0; i<p->nCol; i++) mask |= COLUMN_MASK(p->aCol[i].iFrom);
84339 for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
84340 Index *pIdx = 0;
84341 locateFkeyIndex(pParse, pTab, p, &pIdx, 0);
84342 if( pIdx ){
84343 for(i=0; i<pIdx->nColumn; i++) mask |= COLUMN_MASK(pIdx->aiColumn[i]);
84347 return mask;
84351 ** This function is called before generating code to update or delete a
84352 ** row contained in table pTab. If the operation is a DELETE, then
84353 ** parameter aChange is passed a NULL value. For an UPDATE, aChange points
84354 ** to an array of size N, where N is the number of columns in table pTab.
84355 ** If the i'th column is not modified by the UPDATE, then the corresponding
84356 ** entry in the aChange[] array is set to -1. If the column is modified,
84357 ** the value is 0 or greater. Parameter chngRowid is set to true if the
84358 ** UPDATE statement modifies the rowid fields of the table.
84360 ** If any foreign key processing will be required, this function returns
84361 ** true. If there is no foreign key related processing, this function
84362 ** returns false.
84364 SQLITE_PRIVATE int sqlite3FkRequired(
84365 Parse *pParse, /* Parse context */
84366 Table *pTab, /* Table being modified */
84367 int *aChange, /* Non-NULL for UPDATE operations */
84368 int chngRowid /* True for UPDATE that affects rowid */
84370 if( pParse->db->flags&SQLITE_ForeignKeys ){
84371 if( !aChange ){
84372 /* A DELETE operation. Foreign key processing is required if the
84373 ** table in question is either the child or parent table for any
84374 ** foreign key constraint. */
84375 return (sqlite3FkReferences(pTab) || pTab->pFKey);
84376 }else{
84377 /* This is an UPDATE. Foreign key processing is only required if the
84378 ** operation modifies one or more child or parent key columns. */
84379 int i;
84380 FKey *p;
84382 /* Check if any child key columns are being modified. */
84383 for(p=pTab->pFKey; p; p=p->pNextFrom){
84384 for(i=0; i<p->nCol; i++){
84385 int iChildKey = p->aCol[i].iFrom;
84386 if( aChange[iChildKey]>=0 ) return 1;
84387 if( iChildKey==pTab->iPKey && chngRowid ) return 1;
84391 /* Check if any parent key columns are being modified. */
84392 for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
84393 for(i=0; i<p->nCol; i++){
84394 char *zKey = p->aCol[i].zCol;
84395 int iKey;
84396 for(iKey=0; iKey<pTab->nCol; iKey++){
84397 Column *pCol = &pTab->aCol[iKey];
84398 if( (zKey ? !sqlite3StrICmp(pCol->zName, zKey) : pCol->isPrimKey) ){
84399 if( aChange[iKey]>=0 ) return 1;
84400 if( iKey==pTab->iPKey && chngRowid ) return 1;
84407 return 0;
84411 ** This function is called when an UPDATE or DELETE operation is being
84412 ** compiled on table pTab, which is the parent table of foreign-key pFKey.
84413 ** If the current operation is an UPDATE, then the pChanges parameter is
84414 ** passed a pointer to the list of columns being modified. If it is a
84415 ** DELETE, pChanges is passed a NULL pointer.
84417 ** It returns a pointer to a Trigger structure containing a trigger
84418 ** equivalent to the ON UPDATE or ON DELETE action specified by pFKey.
84419 ** If the action is "NO ACTION" or "RESTRICT", then a NULL pointer is
84420 ** returned (these actions require no special handling by the triggers
84421 ** sub-system, code for them is created by fkScanChildren()).
84423 ** For example, if pFKey is the foreign key and pTab is table "p" in
84424 ** the following schema:
84426 ** CREATE TABLE p(pk PRIMARY KEY);
84427 ** CREATE TABLE c(ck REFERENCES p ON DELETE CASCADE);
84429 ** then the returned trigger structure is equivalent to:
84431 ** CREATE TRIGGER ... DELETE ON p BEGIN
84432 ** DELETE FROM c WHERE ck = old.pk;
84433 ** END;
84435 ** The returned pointer is cached as part of the foreign key object. It
84436 ** is eventually freed along with the rest of the foreign key object by
84437 ** sqlite3FkDelete().
84439 static Trigger *fkActionTrigger(
84440 Parse *pParse, /* Parse context */
84441 Table *pTab, /* Table being updated or deleted from */
84442 FKey *pFKey, /* Foreign key to get action for */
84443 ExprList *pChanges /* Change-list for UPDATE, NULL for DELETE */
84445 sqlite3 *db = pParse->db; /* Database handle */
84446 int action; /* One of OE_None, OE_Cascade etc. */
84447 Trigger *pTrigger; /* Trigger definition to return */
84448 int iAction = (pChanges!=0); /* 1 for UPDATE, 0 for DELETE */
84450 action = pFKey->aAction[iAction];
84451 pTrigger = pFKey->apTrigger[iAction];
84453 if( action!=OE_None && !pTrigger ){
84454 u8 enableLookaside; /* Copy of db->lookaside.bEnabled */
84455 char const *zFrom; /* Name of child table */
84456 int nFrom; /* Length in bytes of zFrom */
84457 Index *pIdx = 0; /* Parent key index for this FK */
84458 int *aiCol = 0; /* child table cols -> parent key cols */
84459 TriggerStep *pStep = 0; /* First (only) step of trigger program */
84460 Expr *pWhere = 0; /* WHERE clause of trigger step */
84461 ExprList *pList = 0; /* Changes list if ON UPDATE CASCADE */
84462 Select *pSelect = 0; /* If RESTRICT, "SELECT RAISE(...)" */
84463 int i; /* Iterator variable */
84464 Expr *pWhen = 0; /* WHEN clause for the trigger */
84466 if( locateFkeyIndex(pParse, pTab, pFKey, &pIdx, &aiCol) ) return 0;
84467 assert( aiCol || pFKey->nCol==1 );
84469 for(i=0; i<pFKey->nCol; i++){
84470 Token tOld = { "old", 3 }; /* Literal "old" token */
84471 Token tNew = { "new", 3 }; /* Literal "new" token */
84472 Token tFromCol; /* Name of column in child table */
84473 Token tToCol; /* Name of column in parent table */
84474 int iFromCol; /* Idx of column in child table */
84475 Expr *pEq; /* tFromCol = OLD.tToCol */
84477 iFromCol = aiCol ? aiCol[i] : pFKey->aCol[0].iFrom;
84478 assert( iFromCol>=0 );
84479 tToCol.z = pIdx ? pTab->aCol[pIdx->aiColumn[i]].zName : "oid";
84480 tFromCol.z = pFKey->pFrom->aCol[iFromCol].zName;
84482 tToCol.n = sqlite3Strlen30(tToCol.z);
84483 tFromCol.n = sqlite3Strlen30(tFromCol.z);
84485 /* Create the expression "OLD.zToCol = zFromCol". It is important
84486 ** that the "OLD.zToCol" term is on the LHS of the = operator, so
84487 ** that the affinity and collation sequence associated with the
84488 ** parent table are used for the comparison. */
84489 pEq = sqlite3PExpr(pParse, TK_EQ,
84490 sqlite3PExpr(pParse, TK_DOT,
84491 sqlite3PExpr(pParse, TK_ID, 0, 0, &tOld),
84492 sqlite3PExpr(pParse, TK_ID, 0, 0, &tToCol)
84493 , 0),
84494 sqlite3PExpr(pParse, TK_ID, 0, 0, &tFromCol)
84495 , 0);
84496 pWhere = sqlite3ExprAnd(db, pWhere, pEq);
84498 /* For ON UPDATE, construct the next term of the WHEN clause.
84499 ** The final WHEN clause will be like this:
84501 ** WHEN NOT(old.col1 IS new.col1 AND ... AND old.colN IS new.colN)
84503 if( pChanges ){
84504 pEq = sqlite3PExpr(pParse, TK_IS,
84505 sqlite3PExpr(pParse, TK_DOT,
84506 sqlite3PExpr(pParse, TK_ID, 0, 0, &tOld),
84507 sqlite3PExpr(pParse, TK_ID, 0, 0, &tToCol),
84509 sqlite3PExpr(pParse, TK_DOT,
84510 sqlite3PExpr(pParse, TK_ID, 0, 0, &tNew),
84511 sqlite3PExpr(pParse, TK_ID, 0, 0, &tToCol),
84514 pWhen = sqlite3ExprAnd(db, pWhen, pEq);
84517 if( action!=OE_Restrict && (action!=OE_Cascade || pChanges) ){
84518 Expr *pNew;
84519 if( action==OE_Cascade ){
84520 pNew = sqlite3PExpr(pParse, TK_DOT,
84521 sqlite3PExpr(pParse, TK_ID, 0, 0, &tNew),
84522 sqlite3PExpr(pParse, TK_ID, 0, 0, &tToCol)
84523 , 0);
84524 }else if( action==OE_SetDflt ){
84525 Expr *pDflt = pFKey->pFrom->aCol[iFromCol].pDflt;
84526 if( pDflt ){
84527 pNew = sqlite3ExprDup(db, pDflt, 0);
84528 }else{
84529 pNew = sqlite3PExpr(pParse, TK_NULL, 0, 0, 0);
84531 }else{
84532 pNew = sqlite3PExpr(pParse, TK_NULL, 0, 0, 0);
84534 pList = sqlite3ExprListAppend(pParse, pList, pNew);
84535 sqlite3ExprListSetName(pParse, pList, &tFromCol, 0);
84538 sqlite3DbFree(db, aiCol);
84540 zFrom = pFKey->pFrom->zName;
84541 nFrom = sqlite3Strlen30(zFrom);
84543 if( action==OE_Restrict ){
84544 Token tFrom;
84545 Expr *pRaise;
84547 tFrom.z = zFrom;
84548 tFrom.n = nFrom;
84549 pRaise = sqlite3Expr(db, TK_RAISE, "foreign key constraint failed");
84550 if( pRaise ){
84551 pRaise->affinity = OE_Abort;
84553 pSelect = sqlite3SelectNew(pParse,
84554 sqlite3ExprListAppend(pParse, 0, pRaise),
84555 sqlite3SrcListAppend(db, 0, &tFrom, 0),
84556 pWhere,
84557 0, 0, 0, 0, 0, 0
84559 pWhere = 0;
84562 /* Disable lookaside memory allocation */
84563 enableLookaside = db->lookaside.bEnabled;
84564 db->lookaside.bEnabled = 0;
84566 pTrigger = (Trigger *)sqlite3DbMallocZero(db,
84567 sizeof(Trigger) + /* struct Trigger */
84568 sizeof(TriggerStep) + /* Single step in trigger program */
84569 nFrom + 1 /* Space for pStep->target.z */
84571 if( pTrigger ){
84572 pStep = pTrigger->step_list = (TriggerStep *)&pTrigger[1];
84573 pStep->target.z = (char *)&pStep[1];
84574 pStep->target.n = nFrom;
84575 memcpy((char *)pStep->target.z, zFrom, nFrom);
84577 pStep->pWhere = sqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE);
84578 pStep->pExprList = sqlite3ExprListDup(db, pList, EXPRDUP_REDUCE);
84579 pStep->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
84580 if( pWhen ){
84581 pWhen = sqlite3PExpr(pParse, TK_NOT, pWhen, 0, 0);
84582 pTrigger->pWhen = sqlite3ExprDup(db, pWhen, EXPRDUP_REDUCE);
84586 /* Re-enable the lookaside buffer, if it was disabled earlier. */
84587 db->lookaside.bEnabled = enableLookaside;
84589 sqlite3ExprDelete(db, pWhere);
84590 sqlite3ExprDelete(db, pWhen);
84591 sqlite3ExprListDelete(db, pList);
84592 sqlite3SelectDelete(db, pSelect);
84593 if( db->mallocFailed==1 ){
84594 fkTriggerDelete(db, pTrigger);
84595 return 0;
84598 switch( action ){
84599 case OE_Restrict:
84600 pStep->op = TK_SELECT;
84601 break;
84602 case OE_Cascade:
84603 if( !pChanges ){
84604 pStep->op = TK_DELETE;
84605 break;
84607 default:
84608 pStep->op = TK_UPDATE;
84610 pStep->pTrig = pTrigger;
84611 pTrigger->pSchema = pTab->pSchema;
84612 pTrigger->pTabSchema = pTab->pSchema;
84613 pFKey->apTrigger[iAction] = pTrigger;
84614 pTrigger->op = (pChanges ? TK_UPDATE : TK_DELETE);
84617 return pTrigger;
84621 ** This function is called when deleting or updating a row to implement
84622 ** any required CASCADE, SET NULL or SET DEFAULT actions.
84624 SQLITE_PRIVATE void sqlite3FkActions(
84625 Parse *pParse, /* Parse context */
84626 Table *pTab, /* Table being updated or deleted from */
84627 ExprList *pChanges, /* Change-list for UPDATE, NULL for DELETE */
84628 int regOld /* Address of array containing old row */
84630 /* If foreign-key support is enabled, iterate through all FKs that
84631 ** refer to table pTab. If there is an action associated with the FK
84632 ** for this operation (either update or delete), invoke the associated
84633 ** trigger sub-program. */
84634 if( pParse->db->flags&SQLITE_ForeignKeys ){
84635 FKey *pFKey; /* Iterator variable */
84636 for(pFKey = sqlite3FkReferences(pTab); pFKey; pFKey=pFKey->pNextTo){
84637 Trigger *pAction = fkActionTrigger(pParse, pTab, pFKey, pChanges);
84638 if( pAction ){
84639 sqlite3CodeRowTriggerDirect(pParse, pAction, pTab, regOld, OE_Abort, 0);
84645 #endif /* ifndef SQLITE_OMIT_TRIGGER */
84648 ** Free all memory associated with foreign key definitions attached to
84649 ** table pTab. Remove the deleted foreign keys from the Schema.fkeyHash
84650 ** hash table.
84652 SQLITE_PRIVATE void sqlite3FkDelete(sqlite3 *db, Table *pTab){
84653 FKey *pFKey; /* Iterator variable */
84654 FKey *pNext; /* Copy of pFKey->pNextFrom */
84656 assert( db==0 || sqlite3SchemaMutexHeld(db, 0, pTab->pSchema) );
84657 for(pFKey=pTab->pFKey; pFKey; pFKey=pNext){
84659 /* Remove the FK from the fkeyHash hash table. */
84660 if( !db || db->pnBytesFreed==0 ){
84661 if( pFKey->pPrevTo ){
84662 pFKey->pPrevTo->pNextTo = pFKey->pNextTo;
84663 }else{
84664 void *p = (void *)pFKey->pNextTo;
84665 const char *z = (p ? pFKey->pNextTo->zTo : pFKey->zTo);
84666 sqlite3HashInsert(&pTab->pSchema->fkeyHash, z, sqlite3Strlen30(z), p);
84668 if( pFKey->pNextTo ){
84669 pFKey->pNextTo->pPrevTo = pFKey->pPrevTo;
84673 /* EV: R-30323-21917 Each foreign key constraint in SQLite is
84674 ** classified as either immediate or deferred.
84676 assert( pFKey->isDeferred==0 || pFKey->isDeferred==1 );
84678 /* Delete any triggers created to implement actions for this FK. */
84679 #ifndef SQLITE_OMIT_TRIGGER
84680 fkTriggerDelete(db, pFKey->apTrigger[0]);
84681 fkTriggerDelete(db, pFKey->apTrigger[1]);
84682 #endif
84684 pNext = pFKey->pNextFrom;
84685 sqlite3DbFree(db, pFKey);
84688 #endif /* ifndef SQLITE_OMIT_FOREIGN_KEY */
84690 /************** End of fkey.c ************************************************/
84691 /************** Begin file insert.c ******************************************/
84693 ** 2001 September 15
84695 ** The author disclaims copyright to this source code. In place of
84696 ** a legal notice, here is a blessing:
84698 ** May you do good and not evil.
84699 ** May you find forgiveness for yourself and forgive others.
84700 ** May you share freely, never taking more than you give.
84702 *************************************************************************
84703 ** This file contains C code routines that are called by the parser
84704 ** to handle INSERT statements in SQLite.
84708 ** Generate code that will open a table for reading.
84710 SQLITE_PRIVATE void sqlite3OpenTable(
84711 Parse *p, /* Generate code into this VDBE */
84712 int iCur, /* The cursor number of the table */
84713 int iDb, /* The database index in sqlite3.aDb[] */
84714 Table *pTab, /* The table to be opened */
84715 int opcode /* OP_OpenRead or OP_OpenWrite */
84717 Vdbe *v;
84718 if( IsVirtual(pTab) ) return;
84719 v = sqlite3GetVdbe(p);
84720 assert( opcode==OP_OpenWrite || opcode==OP_OpenRead );
84721 sqlite3TableLock(p, iDb, pTab->tnum, (opcode==OP_OpenWrite)?1:0, pTab->zName);
84722 sqlite3VdbeAddOp3(v, opcode, iCur, pTab->tnum, iDb);
84723 sqlite3VdbeChangeP4(v, -1, SQLITE_INT_TO_PTR(pTab->nCol), P4_INT32);
84724 VdbeComment((v, "%s", pTab->zName));
84728 ** Return a pointer to the column affinity string associated with index
84729 ** pIdx. A column affinity string has one character for each column in
84730 ** the table, according to the affinity of the column:
84732 ** Character Column affinity
84733 ** ------------------------------
84734 ** 'a' TEXT
84735 ** 'b' NONE
84736 ** 'c' NUMERIC
84737 ** 'd' INTEGER
84738 ** 'e' REAL
84740 ** An extra 'b' is appended to the end of the string to cover the
84741 ** rowid that appears as the last column in every index.
84743 ** Memory for the buffer containing the column index affinity string
84744 ** is managed along with the rest of the Index structure. It will be
84745 ** released when sqlite3DeleteIndex() is called.
84747 SQLITE_PRIVATE const char *sqlite3IndexAffinityStr(Vdbe *v, Index *pIdx){
84748 if( !pIdx->zColAff ){
84749 /* The first time a column affinity string for a particular index is
84750 ** required, it is allocated and populated here. It is then stored as
84751 ** a member of the Index structure for subsequent use.
84753 ** The column affinity string will eventually be deleted by
84754 ** sqliteDeleteIndex() when the Index structure itself is cleaned
84755 ** up.
84757 int n;
84758 Table *pTab = pIdx->pTable;
84759 sqlite3 *db = sqlite3VdbeDb(v);
84760 pIdx->zColAff = (char *)sqlite3DbMallocRaw(0, pIdx->nColumn+2);
84761 if( !pIdx->zColAff ){
84762 db->mallocFailed = 1;
84763 return 0;
84765 for(n=0; n<pIdx->nColumn; n++){
84766 pIdx->zColAff[n] = pTab->aCol[pIdx->aiColumn[n]].affinity;
84768 pIdx->zColAff[n++] = SQLITE_AFF_NONE;
84769 pIdx->zColAff[n] = 0;
84772 return pIdx->zColAff;
84776 ** Set P4 of the most recently inserted opcode to a column affinity
84777 ** string for table pTab. A column affinity string has one character
84778 ** for each column indexed by the index, according to the affinity of the
84779 ** column:
84781 ** Character Column affinity
84782 ** ------------------------------
84783 ** 'a' TEXT
84784 ** 'b' NONE
84785 ** 'c' NUMERIC
84786 ** 'd' INTEGER
84787 ** 'e' REAL
84789 SQLITE_PRIVATE void sqlite3TableAffinityStr(Vdbe *v, Table *pTab){
84790 /* The first time a column affinity string for a particular table
84791 ** is required, it is allocated and populated here. It is then
84792 ** stored as a member of the Table structure for subsequent use.
84794 ** The column affinity string will eventually be deleted by
84795 ** sqlite3DeleteTable() when the Table structure itself is cleaned up.
84797 if( !pTab->zColAff ){
84798 char *zColAff;
84799 int i;
84800 sqlite3 *db = sqlite3VdbeDb(v);
84802 zColAff = (char *)sqlite3DbMallocRaw(0, pTab->nCol+1);
84803 if( !zColAff ){
84804 db->mallocFailed = 1;
84805 return;
84808 for(i=0; i<pTab->nCol; i++){
84809 zColAff[i] = pTab->aCol[i].affinity;
84811 zColAff[pTab->nCol] = '\0';
84813 pTab->zColAff = zColAff;
84816 sqlite3VdbeChangeP4(v, -1, pTab->zColAff, P4_TRANSIENT);
84820 ** Return non-zero if the table pTab in database iDb or any of its indices
84821 ** have been opened at any point in the VDBE program beginning at location
84822 ** iStartAddr throught the end of the program. This is used to see if
84823 ** a statement of the form "INSERT INTO <iDb, pTab> SELECT ..." can
84824 ** run without using temporary table for the results of the SELECT.
84826 static int readsTable(Parse *p, int iStartAddr, int iDb, Table *pTab){
84827 Vdbe *v = sqlite3GetVdbe(p);
84828 int i;
84829 int iEnd = sqlite3VdbeCurrentAddr(v);
84830 #ifndef SQLITE_OMIT_VIRTUALTABLE
84831 VTable *pVTab = IsVirtual(pTab) ? sqlite3GetVTable(p->db, pTab) : 0;
84832 #endif
84834 for(i=iStartAddr; i<iEnd; i++){
84835 VdbeOp *pOp = sqlite3VdbeGetOp(v, i);
84836 assert( pOp!=0 );
84837 if( pOp->opcode==OP_OpenRead && pOp->p3==iDb ){
84838 Index *pIndex;
84839 int tnum = pOp->p2;
84840 if( tnum==pTab->tnum ){
84841 return 1;
84843 for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){
84844 if( tnum==pIndex->tnum ){
84845 return 1;
84849 #ifndef SQLITE_OMIT_VIRTUALTABLE
84850 if( pOp->opcode==OP_VOpen && pOp->p4.pVtab==pVTab ){
84851 assert( pOp->p4.pVtab!=0 );
84852 assert( pOp->p4type==P4_VTAB );
84853 return 1;
84855 #endif
84857 return 0;
84860 #ifndef SQLITE_OMIT_AUTOINCREMENT
84862 ** Locate or create an AutoincInfo structure associated with table pTab
84863 ** which is in database iDb. Return the register number for the register
84864 ** that holds the maximum rowid.
84866 ** There is at most one AutoincInfo structure per table even if the
84867 ** same table is autoincremented multiple times due to inserts within
84868 ** triggers. A new AutoincInfo structure is created if this is the
84869 ** first use of table pTab. On 2nd and subsequent uses, the original
84870 ** AutoincInfo structure is used.
84872 ** Three memory locations are allocated:
84874 ** (1) Register to hold the name of the pTab table.
84875 ** (2) Register to hold the maximum ROWID of pTab.
84876 ** (3) Register to hold the rowid in sqlite_sequence of pTab
84878 ** The 2nd register is the one that is returned. That is all the
84879 ** insert routine needs to know about.
84881 static int autoIncBegin(
84882 Parse *pParse, /* Parsing context */
84883 int iDb, /* Index of the database holding pTab */
84884 Table *pTab /* The table we are writing to */
84886 int memId = 0; /* Register holding maximum rowid */
84887 if( pTab->tabFlags & TF_Autoincrement ){
84888 Parse *pToplevel = sqlite3ParseToplevel(pParse);
84889 AutoincInfo *pInfo;
84891 pInfo = pToplevel->pAinc;
84892 while( pInfo && pInfo->pTab!=pTab ){ pInfo = pInfo->pNext; }
84893 if( pInfo==0 ){
84894 pInfo = sqlite3DbMallocRaw(pParse->db, sizeof(*pInfo));
84895 if( pInfo==0 ) return 0;
84896 pInfo->pNext = pToplevel->pAinc;
84897 pToplevel->pAinc = pInfo;
84898 pInfo->pTab = pTab;
84899 pInfo->iDb = iDb;
84900 pToplevel->nMem++; /* Register to hold name of table */
84901 pInfo->regCtr = ++pToplevel->nMem; /* Max rowid register */
84902 pToplevel->nMem++; /* Rowid in sqlite_sequence */
84904 memId = pInfo->regCtr;
84906 return memId;
84910 ** This routine generates code that will initialize all of the
84911 ** register used by the autoincrement tracker.
84913 SQLITE_PRIVATE void sqlite3AutoincrementBegin(Parse *pParse){
84914 AutoincInfo *p; /* Information about an AUTOINCREMENT */
84915 sqlite3 *db = pParse->db; /* The database connection */
84916 Db *pDb; /* Database only autoinc table */
84917 int memId; /* Register holding max rowid */
84918 int addr; /* A VDBE address */
84919 Vdbe *v = pParse->pVdbe; /* VDBE under construction */
84921 /* This routine is never called during trigger-generation. It is
84922 ** only called from the top-level */
84923 assert( pParse->pTriggerTab==0 );
84924 assert( pParse==sqlite3ParseToplevel(pParse) );
84926 assert( v ); /* We failed long ago if this is not so */
84927 for(p = pParse->pAinc; p; p = p->pNext){
84928 pDb = &db->aDb[p->iDb];
84929 memId = p->regCtr;
84930 assert( sqlite3SchemaMutexHeld(db, 0, pDb->pSchema) );
84931 sqlite3OpenTable(pParse, 0, p->iDb, pDb->pSchema->pSeqTab, OP_OpenRead);
84932 addr = sqlite3VdbeCurrentAddr(v);
84933 sqlite3VdbeAddOp4(v, OP_String8, 0, memId-1, 0, p->pTab->zName, 0);
84934 sqlite3VdbeAddOp2(v, OP_Rewind, 0, addr+9);
84935 sqlite3VdbeAddOp3(v, OP_Column, 0, 0, memId);
84936 sqlite3VdbeAddOp3(v, OP_Ne, memId-1, addr+7, memId);
84937 sqlite3VdbeChangeP5(v, SQLITE_JUMPIFNULL);
84938 sqlite3VdbeAddOp2(v, OP_Rowid, 0, memId+1);
84939 sqlite3VdbeAddOp3(v, OP_Column, 0, 1, memId);
84940 sqlite3VdbeAddOp2(v, OP_Goto, 0, addr+9);
84941 sqlite3VdbeAddOp2(v, OP_Next, 0, addr+2);
84942 sqlite3VdbeAddOp2(v, OP_Integer, 0, memId);
84943 sqlite3VdbeAddOp0(v, OP_Close);
84948 ** Update the maximum rowid for an autoincrement calculation.
84950 ** This routine should be called when the top of the stack holds a
84951 ** new rowid that is about to be inserted. If that new rowid is
84952 ** larger than the maximum rowid in the memId memory cell, then the
84953 ** memory cell is updated. The stack is unchanged.
84955 static void autoIncStep(Parse *pParse, int memId, int regRowid){
84956 if( memId>0 ){
84957 sqlite3VdbeAddOp2(pParse->pVdbe, OP_MemMax, memId, regRowid);
84962 ** This routine generates the code needed to write autoincrement
84963 ** maximum rowid values back into the sqlite_sequence register.
84964 ** Every statement that might do an INSERT into an autoincrement
84965 ** table (either directly or through triggers) needs to call this
84966 ** routine just before the "exit" code.
84968 SQLITE_PRIVATE void sqlite3AutoincrementEnd(Parse *pParse){
84969 AutoincInfo *p;
84970 Vdbe *v = pParse->pVdbe;
84971 sqlite3 *db = pParse->db;
84973 assert( v );
84974 for(p = pParse->pAinc; p; p = p->pNext){
84975 Db *pDb = &db->aDb[p->iDb];
84976 int j1, j2, j3, j4, j5;
84977 int iRec;
84978 int memId = p->regCtr;
84980 iRec = sqlite3GetTempReg(pParse);
84981 assert( sqlite3SchemaMutexHeld(db, 0, pDb->pSchema) );
84982 sqlite3OpenTable(pParse, 0, p->iDb, pDb->pSchema->pSeqTab, OP_OpenWrite);
84983 j1 = sqlite3VdbeAddOp1(v, OP_NotNull, memId+1);
84984 j2 = sqlite3VdbeAddOp0(v, OP_Rewind);
84985 j3 = sqlite3VdbeAddOp3(v, OP_Column, 0, 0, iRec);
84986 j4 = sqlite3VdbeAddOp3(v, OP_Eq, memId-1, 0, iRec);
84987 sqlite3VdbeAddOp2(v, OP_Next, 0, j3);
84988 sqlite3VdbeJumpHere(v, j2);
84989 sqlite3VdbeAddOp2(v, OP_NewRowid, 0, memId+1);
84990 j5 = sqlite3VdbeAddOp0(v, OP_Goto);
84991 sqlite3VdbeJumpHere(v, j4);
84992 sqlite3VdbeAddOp2(v, OP_Rowid, 0, memId+1);
84993 sqlite3VdbeJumpHere(v, j1);
84994 sqlite3VdbeJumpHere(v, j5);
84995 sqlite3VdbeAddOp3(v, OP_MakeRecord, memId-1, 2, iRec);
84996 sqlite3VdbeAddOp3(v, OP_Insert, 0, iRec, memId+1);
84997 sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
84998 sqlite3VdbeAddOp0(v, OP_Close);
84999 sqlite3ReleaseTempReg(pParse, iRec);
85002 #else
85004 ** If SQLITE_OMIT_AUTOINCREMENT is defined, then the three routines
85005 ** above are all no-ops
85007 # define autoIncBegin(A,B,C) (0)
85008 # define autoIncStep(A,B,C)
85009 #endif /* SQLITE_OMIT_AUTOINCREMENT */
85012 /* Forward declaration */
85013 static int xferOptimization(
85014 Parse *pParse, /* Parser context */
85015 Table *pDest, /* The table we are inserting into */
85016 Select *pSelect, /* A SELECT statement to use as the data source */
85017 int onError, /* How to handle constraint errors */
85018 int iDbDest /* The database of pDest */
85022 ** This routine is call to handle SQL of the following forms:
85024 ** insert into TABLE (IDLIST) values(EXPRLIST)
85025 ** insert into TABLE (IDLIST) select
85027 ** The IDLIST following the table name is always optional. If omitted,
85028 ** then a list of all columns for the table is substituted. The IDLIST
85029 ** appears in the pColumn parameter. pColumn is NULL if IDLIST is omitted.
85031 ** The pList parameter holds EXPRLIST in the first form of the INSERT
85032 ** statement above, and pSelect is NULL. For the second form, pList is
85033 ** NULL and pSelect is a pointer to the select statement used to generate
85034 ** data for the insert.
85036 ** The code generated follows one of four templates. For a simple
85037 ** select with data coming from a VALUES clause, the code executes
85038 ** once straight down through. Pseudo-code follows (we call this
85039 ** the "1st template"):
85041 ** open write cursor to <table> and its indices
85042 ** puts VALUES clause expressions onto the stack
85043 ** write the resulting record into <table>
85044 ** cleanup
85046 ** The three remaining templates assume the statement is of the form
85048 ** INSERT INTO <table> SELECT ...
85050 ** If the SELECT clause is of the restricted form "SELECT * FROM <table2>" -
85051 ** in other words if the SELECT pulls all columns from a single table
85052 ** and there is no WHERE or LIMIT or GROUP BY or ORDER BY clauses, and
85053 ** if <table2> and <table1> are distinct tables but have identical
85054 ** schemas, including all the same indices, then a special optimization
85055 ** is invoked that copies raw records from <table2> over to <table1>.
85056 ** See the xferOptimization() function for the implementation of this
85057 ** template. This is the 2nd template.
85059 ** open a write cursor to <table>
85060 ** open read cursor on <table2>
85061 ** transfer all records in <table2> over to <table>
85062 ** close cursors
85063 ** foreach index on <table>
85064 ** open a write cursor on the <table> index
85065 ** open a read cursor on the corresponding <table2> index
85066 ** transfer all records from the read to the write cursors
85067 ** close cursors
85068 ** end foreach
85070 ** The 3rd template is for when the second template does not apply
85071 ** and the SELECT clause does not read from <table> at any time.
85072 ** The generated code follows this template:
85074 ** EOF <- 0
85075 ** X <- A
85076 ** goto B
85077 ** A: setup for the SELECT
85078 ** loop over the rows in the SELECT
85079 ** load values into registers R..R+n
85080 ** yield X
85081 ** end loop
85082 ** cleanup after the SELECT
85083 ** EOF <- 1
85084 ** yield X
85085 ** goto A
85086 ** B: open write cursor to <table> and its indices
85087 ** C: yield X
85088 ** if EOF goto D
85089 ** insert the select result into <table> from R..R+n
85090 ** goto C
85091 ** D: cleanup
85093 ** The 4th template is used if the insert statement takes its
85094 ** values from a SELECT but the data is being inserted into a table
85095 ** that is also read as part of the SELECT. In the third form,
85096 ** we have to use a intermediate table to store the results of
85097 ** the select. The template is like this:
85099 ** EOF <- 0
85100 ** X <- A
85101 ** goto B
85102 ** A: setup for the SELECT
85103 ** loop over the tables in the SELECT
85104 ** load value into register R..R+n
85105 ** yield X
85106 ** end loop
85107 ** cleanup after the SELECT
85108 ** EOF <- 1
85109 ** yield X
85110 ** halt-error
85111 ** B: open temp table
85112 ** L: yield X
85113 ** if EOF goto M
85114 ** insert row from R..R+n into temp table
85115 ** goto L
85116 ** M: open write cursor to <table> and its indices
85117 ** rewind temp table
85118 ** C: loop over rows of intermediate table
85119 ** transfer values form intermediate table into <table>
85120 ** end loop
85121 ** D: cleanup
85123 SQLITE_PRIVATE void sqlite3Insert(
85124 Parse *pParse, /* Parser context */
85125 SrcList *pTabList, /* Name of table into which we are inserting */
85126 ExprList *pList, /* List of values to be inserted */
85127 Select *pSelect, /* A SELECT statement to use as the data source */
85128 IdList *pColumn, /* Column names corresponding to IDLIST. */
85129 int onError /* How to handle constraint errors */
85131 sqlite3 *db; /* The main database structure */
85132 Table *pTab; /* The table to insert into. aka TABLE */
85133 char *zTab; /* Name of the table into which we are inserting */
85134 const char *zDb; /* Name of the database holding this table */
85135 int i, j, idx; /* Loop counters */
85136 Vdbe *v; /* Generate code into this virtual machine */
85137 Index *pIdx; /* For looping over indices of the table */
85138 int nColumn; /* Number of columns in the data */
85139 int nHidden = 0; /* Number of hidden columns if TABLE is virtual */
85140 int baseCur = 0; /* VDBE Cursor number for pTab */
85141 int keyColumn = -1; /* Column that is the INTEGER PRIMARY KEY */
85142 int endOfLoop; /* Label for the end of the insertion loop */
85143 int useTempTable = 0; /* Store SELECT results in intermediate table */
85144 int srcTab = 0; /* Data comes from this temporary cursor if >=0 */
85145 int addrInsTop = 0; /* Jump to label "D" */
85146 int addrCont = 0; /* Top of insert loop. Label "C" in templates 3 and 4 */
85147 int addrSelect = 0; /* Address of coroutine that implements the SELECT */
85148 SelectDest dest; /* Destination for SELECT on rhs of INSERT */
85149 int iDb; /* Index of database holding TABLE */
85150 Db *pDb; /* The database containing table being inserted into */
85151 int appendFlag = 0; /* True if the insert is likely to be an append */
85153 /* Register allocations */
85154 int regFromSelect = 0;/* Base register for data coming from SELECT */
85155 int regAutoinc = 0; /* Register holding the AUTOINCREMENT counter */
85156 int regRowCount = 0; /* Memory cell used for the row counter */
85157 int regIns; /* Block of regs holding rowid+data being inserted */
85158 int regRowid; /* registers holding insert rowid */
85159 int regData; /* register holding first column to insert */
85160 int regEof = 0; /* Register recording end of SELECT data */
85161 int *aRegIdx = 0; /* One register allocated to each index */
85163 #ifndef SQLITE_OMIT_TRIGGER
85164 int isView; /* True if attempting to insert into a view */
85165 Trigger *pTrigger; /* List of triggers on pTab, if required */
85166 int tmask; /* Mask of trigger times */
85167 #endif
85169 db = pParse->db;
85170 memset(&dest, 0, sizeof(dest));
85171 if( pParse->nErr || db->mallocFailed ){
85172 goto insert_cleanup;
85175 /* Locate the table into which we will be inserting new information.
85177 assert( pTabList->nSrc==1 );
85178 zTab = pTabList->a[0].zName;
85179 if( NEVER(zTab==0) ) goto insert_cleanup;
85180 pTab = sqlite3SrcListLookup(pParse, pTabList);
85181 if( pTab==0 ){
85182 goto insert_cleanup;
85184 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
85185 assert( iDb<db->nDb );
85186 pDb = &db->aDb[iDb];
85187 zDb = pDb->zName;
85188 if( sqlite3AuthCheck(pParse, SQLITE_INSERT, pTab->zName, 0, zDb) ){
85189 goto insert_cleanup;
85192 /* Figure out if we have any triggers and if the table being
85193 ** inserted into is a view
85195 #ifndef SQLITE_OMIT_TRIGGER
85196 pTrigger = sqlite3TriggersExist(pParse, pTab, TK_INSERT, 0, &tmask);
85197 isView = pTab->pSelect!=0;
85198 #else
85199 # define pTrigger 0
85200 # define tmask 0
85201 # define isView 0
85202 #endif
85203 #ifdef SQLITE_OMIT_VIEW
85204 # undef isView
85205 # define isView 0
85206 #endif
85207 assert( (pTrigger && tmask) || (pTrigger==0 && tmask==0) );
85209 /* If pTab is really a view, make sure it has been initialized.
85210 ** ViewGetColumnNames() is a no-op if pTab is not a view (or virtual
85211 ** module table).
85213 if( sqlite3ViewGetColumnNames(pParse, pTab) ){
85214 goto insert_cleanup;
85217 /* Ensure that:
85218 * (a) the table is not read-only,
85219 * (b) that if it is a view then ON INSERT triggers exist
85221 if( sqlite3IsReadOnly(pParse, pTab, tmask) ){
85222 goto insert_cleanup;
85225 /* Allocate a VDBE
85227 v = sqlite3GetVdbe(pParse);
85228 if( v==0 ) goto insert_cleanup;
85229 if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
85230 sqlite3BeginWriteOperation(pParse, pSelect || pTrigger, iDb);
85232 #ifndef SQLITE_OMIT_XFER_OPT
85233 /* If the statement is of the form
85235 ** INSERT INTO <table1> SELECT * FROM <table2>;
85237 ** Then special optimizations can be applied that make the transfer
85238 ** very fast and which reduce fragmentation of indices.
85240 ** This is the 2nd template.
85242 if( pColumn==0 && xferOptimization(pParse, pTab, pSelect, onError, iDb) ){
85243 assert( !pTrigger );
85244 assert( pList==0 );
85245 goto insert_end;
85247 #endif /* SQLITE_OMIT_XFER_OPT */
85249 /* If this is an AUTOINCREMENT table, look up the sequence number in the
85250 ** sqlite_sequence table and store it in memory cell regAutoinc.
85252 regAutoinc = autoIncBegin(pParse, iDb, pTab);
85254 /* Figure out how many columns of data are supplied. If the data
85255 ** is coming from a SELECT statement, then generate a co-routine that
85256 ** produces a single row of the SELECT on each invocation. The
85257 ** co-routine is the common header to the 3rd and 4th templates.
85259 if( pSelect ){
85260 /* Data is coming from a SELECT. Generate code to implement that SELECT
85261 ** as a co-routine. The code is common to both the 3rd and 4th
85262 ** templates:
85264 ** EOF <- 0
85265 ** X <- A
85266 ** goto B
85267 ** A: setup for the SELECT
85268 ** loop over the tables in the SELECT
85269 ** load value into register R..R+n
85270 ** yield X
85271 ** end loop
85272 ** cleanup after the SELECT
85273 ** EOF <- 1
85274 ** yield X
85275 ** halt-error
85277 ** On each invocation of the co-routine, it puts a single row of the
85278 ** SELECT result into registers dest.iMem...dest.iMem+dest.nMem-1.
85279 ** (These output registers are allocated by sqlite3Select().) When
85280 ** the SELECT completes, it sets the EOF flag stored in regEof.
85282 int rc, j1;
85284 regEof = ++pParse->nMem;
85285 sqlite3VdbeAddOp2(v, OP_Integer, 0, regEof); /* EOF <- 0 */
85286 VdbeComment((v, "SELECT eof flag"));
85287 sqlite3SelectDestInit(&dest, SRT_Coroutine, ++pParse->nMem);
85288 addrSelect = sqlite3VdbeCurrentAddr(v)+2;
85289 sqlite3VdbeAddOp2(v, OP_Integer, addrSelect-1, dest.iParm);
85290 j1 = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0);
85291 VdbeComment((v, "Jump over SELECT coroutine"));
85293 /* Resolve the expressions in the SELECT statement and execute it. */
85294 rc = sqlite3Select(pParse, pSelect, &dest);
85295 assert( pParse->nErr==0 || rc );
85296 if( rc || NEVER(pParse->nErr) || db->mallocFailed ){
85297 goto insert_cleanup;
85299 sqlite3VdbeAddOp2(v, OP_Integer, 1, regEof); /* EOF <- 1 */
85300 sqlite3VdbeAddOp1(v, OP_Yield, dest.iParm); /* yield X */
85301 sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_INTERNAL, OE_Abort);
85302 VdbeComment((v, "End of SELECT coroutine"));
85303 sqlite3VdbeJumpHere(v, j1); /* label B: */
85305 regFromSelect = dest.iMem;
85306 assert( pSelect->pEList );
85307 nColumn = pSelect->pEList->nExpr;
85308 assert( dest.nMem==nColumn );
85310 /* Set useTempTable to TRUE if the result of the SELECT statement
85311 ** should be written into a temporary table (template 4). Set to
85312 ** FALSE if each* row of the SELECT can be written directly into
85313 ** the destination table (template 3).
85315 ** A temp table must be used if the table being updated is also one
85316 ** of the tables being read by the SELECT statement. Also use a
85317 ** temp table in the case of row triggers.
85319 if( pTrigger || readsTable(pParse, addrSelect, iDb, pTab) ){
85320 useTempTable = 1;
85323 if( useTempTable ){
85324 /* Invoke the coroutine to extract information from the SELECT
85325 ** and add it to a transient table srcTab. The code generated
85326 ** here is from the 4th template:
85328 ** B: open temp table
85329 ** L: yield X
85330 ** if EOF goto M
85331 ** insert row from R..R+n into temp table
85332 ** goto L
85333 ** M: ...
85335 int regRec; /* Register to hold packed record */
85336 int regTempRowid; /* Register to hold temp table ROWID */
85337 int addrTop; /* Label "L" */
85338 int addrIf; /* Address of jump to M */
85340 srcTab = pParse->nTab++;
85341 regRec = sqlite3GetTempReg(pParse);
85342 regTempRowid = sqlite3GetTempReg(pParse);
85343 sqlite3VdbeAddOp2(v, OP_OpenEphemeral, srcTab, nColumn);
85344 addrTop = sqlite3VdbeAddOp1(v, OP_Yield, dest.iParm);
85345 addrIf = sqlite3VdbeAddOp1(v, OP_If, regEof);
85346 sqlite3VdbeAddOp3(v, OP_MakeRecord, regFromSelect, nColumn, regRec);
85347 sqlite3VdbeAddOp2(v, OP_NewRowid, srcTab, regTempRowid);
85348 sqlite3VdbeAddOp3(v, OP_Insert, srcTab, regRec, regTempRowid);
85349 sqlite3VdbeAddOp2(v, OP_Goto, 0, addrTop);
85350 sqlite3VdbeJumpHere(v, addrIf);
85351 sqlite3ReleaseTempReg(pParse, regRec);
85352 sqlite3ReleaseTempReg(pParse, regTempRowid);
85354 }else{
85355 /* This is the case if the data for the INSERT is coming from a VALUES
85356 ** clause
85358 NameContext sNC;
85359 memset(&sNC, 0, sizeof(sNC));
85360 sNC.pParse = pParse;
85361 srcTab = -1;
85362 assert( useTempTable==0 );
85363 nColumn = pList ? pList->nExpr : 0;
85364 for(i=0; i<nColumn; i++){
85365 if( sqlite3ResolveExprNames(&sNC, pList->a[i].pExpr) ){
85366 goto insert_cleanup;
85371 /* Make sure the number of columns in the source data matches the number
85372 ** of columns to be inserted into the table.
85374 if( IsVirtual(pTab) ){
85375 for(i=0; i<pTab->nCol; i++){
85376 nHidden += (IsHiddenColumn(&pTab->aCol[i]) ? 1 : 0);
85379 if( pColumn==0 && nColumn && nColumn!=(pTab->nCol-nHidden) ){
85380 sqlite3ErrorMsg(pParse,
85381 "table %S has %d columns but %d values were supplied",
85382 pTabList, 0, pTab->nCol-nHidden, nColumn);
85383 goto insert_cleanup;
85385 if( pColumn!=0 && nColumn!=pColumn->nId ){
85386 sqlite3ErrorMsg(pParse, "%d values for %d columns", nColumn, pColumn->nId);
85387 goto insert_cleanup;
85390 /* If the INSERT statement included an IDLIST term, then make sure
85391 ** all elements of the IDLIST really are columns of the table and
85392 ** remember the column indices.
85394 ** If the table has an INTEGER PRIMARY KEY column and that column
85395 ** is named in the IDLIST, then record in the keyColumn variable
85396 ** the index into IDLIST of the primary key column. keyColumn is
85397 ** the index of the primary key as it appears in IDLIST, not as
85398 ** is appears in the original table. (The index of the primary
85399 ** key in the original table is pTab->iPKey.)
85401 if( pColumn ){
85402 for(i=0; i<pColumn->nId; i++){
85403 pColumn->a[i].idx = -1;
85405 for(i=0; i<pColumn->nId; i++){
85406 for(j=0; j<pTab->nCol; j++){
85407 if( sqlite3StrICmp(pColumn->a[i].zName, pTab->aCol[j].zName)==0 ){
85408 pColumn->a[i].idx = j;
85409 if( j==pTab->iPKey ){
85410 keyColumn = i;
85412 break;
85415 if( j>=pTab->nCol ){
85416 if( sqlite3IsRowid(pColumn->a[i].zName) ){
85417 keyColumn = i;
85418 }else{
85419 sqlite3ErrorMsg(pParse, "table %S has no column named %s",
85420 pTabList, 0, pColumn->a[i].zName);
85421 pParse->checkSchema = 1;
85422 goto insert_cleanup;
85428 /* If there is no IDLIST term but the table has an integer primary
85429 ** key, the set the keyColumn variable to the primary key column index
85430 ** in the original table definition.
85432 if( pColumn==0 && nColumn>0 ){
85433 keyColumn = pTab->iPKey;
85436 /* Initialize the count of rows to be inserted
85438 if( db->flags & SQLITE_CountRows ){
85439 regRowCount = ++pParse->nMem;
85440 sqlite3VdbeAddOp2(v, OP_Integer, 0, regRowCount);
85443 /* If this is not a view, open the table and and all indices */
85444 if( !isView ){
85445 int nIdx;
85447 baseCur = pParse->nTab;
85448 nIdx = sqlite3OpenTableAndIndices(pParse, pTab, baseCur, OP_OpenWrite);
85449 aRegIdx = sqlite3DbMallocRaw(db, sizeof(int)*(nIdx+1));
85450 if( aRegIdx==0 ){
85451 goto insert_cleanup;
85453 for(i=0; i<nIdx; i++){
85454 aRegIdx[i] = ++pParse->nMem;
85458 /* This is the top of the main insertion loop */
85459 if( useTempTable ){
85460 /* This block codes the top of loop only. The complete loop is the
85461 ** following pseudocode (template 4):
85463 ** rewind temp table
85464 ** C: loop over rows of intermediate table
85465 ** transfer values form intermediate table into <table>
85466 ** end loop
85467 ** D: ...
85469 addrInsTop = sqlite3VdbeAddOp1(v, OP_Rewind, srcTab);
85470 addrCont = sqlite3VdbeCurrentAddr(v);
85471 }else if( pSelect ){
85472 /* This block codes the top of loop only. The complete loop is the
85473 ** following pseudocode (template 3):
85475 ** C: yield X
85476 ** if EOF goto D
85477 ** insert the select result into <table> from R..R+n
85478 ** goto C
85479 ** D: ...
85481 addrCont = sqlite3VdbeAddOp1(v, OP_Yield, dest.iParm);
85482 addrInsTop = sqlite3VdbeAddOp1(v, OP_If, regEof);
85485 /* Allocate registers for holding the rowid of the new row,
85486 ** the content of the new row, and the assemblied row record.
85488 regRowid = regIns = pParse->nMem+1;
85489 pParse->nMem += pTab->nCol + 1;
85490 if( IsVirtual(pTab) ){
85491 regRowid++;
85492 pParse->nMem++;
85494 regData = regRowid+1;
85496 /* Run the BEFORE and INSTEAD OF triggers, if there are any
85498 endOfLoop = sqlite3VdbeMakeLabel(v);
85499 if( tmask & TRIGGER_BEFORE ){
85500 int regCols = sqlite3GetTempRange(pParse, pTab->nCol+1);
85502 /* build the NEW.* reference row. Note that if there is an INTEGER
85503 ** PRIMARY KEY into which a NULL is being inserted, that NULL will be
85504 ** translated into a unique ID for the row. But on a BEFORE trigger,
85505 ** we do not know what the unique ID will be (because the insert has
85506 ** not happened yet) so we substitute a rowid of -1
85508 if( keyColumn<0 ){
85509 sqlite3VdbeAddOp2(v, OP_Integer, -1, regCols);
85510 }else{
85511 int j1;
85512 if( useTempTable ){
85513 sqlite3VdbeAddOp3(v, OP_Column, srcTab, keyColumn, regCols);
85514 }else{
85515 assert( pSelect==0 ); /* Otherwise useTempTable is true */
85516 sqlite3ExprCode(pParse, pList->a[keyColumn].pExpr, regCols);
85518 j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regCols);
85519 sqlite3VdbeAddOp2(v, OP_Integer, -1, regCols);
85520 sqlite3VdbeJumpHere(v, j1);
85521 sqlite3VdbeAddOp1(v, OP_MustBeInt, regCols);
85524 /* Cannot have triggers on a virtual table. If it were possible,
85525 ** this block would have to account for hidden column.
85527 assert( !IsVirtual(pTab) );
85529 /* Create the new column data
85531 for(i=0; i<pTab->nCol; i++){
85532 if( pColumn==0 ){
85533 j = i;
85534 }else{
85535 for(j=0; j<pColumn->nId; j++){
85536 if( pColumn->a[j].idx==i ) break;
85539 if( (!useTempTable && !pList) || (pColumn && j>=pColumn->nId) ){
85540 sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, regCols+i+1);
85541 }else if( useTempTable ){
85542 sqlite3VdbeAddOp3(v, OP_Column, srcTab, j, regCols+i+1);
85543 }else{
85544 assert( pSelect==0 ); /* Otherwise useTempTable is true */
85545 sqlite3ExprCodeAndCache(pParse, pList->a[j].pExpr, regCols+i+1);
85549 /* If this is an INSERT on a view with an INSTEAD OF INSERT trigger,
85550 ** do not attempt any conversions before assembling the record.
85551 ** If this is a real table, attempt conversions as required by the
85552 ** table column affinities.
85554 if( !isView ){
85555 sqlite3VdbeAddOp2(v, OP_Affinity, regCols+1, pTab->nCol);
85556 sqlite3TableAffinityStr(v, pTab);
85559 /* Fire BEFORE or INSTEAD OF triggers */
85560 sqlite3CodeRowTrigger(pParse, pTrigger, TK_INSERT, 0, TRIGGER_BEFORE,
85561 pTab, regCols-pTab->nCol-1, onError, endOfLoop);
85563 sqlite3ReleaseTempRange(pParse, regCols, pTab->nCol+1);
85566 /* Push the record number for the new entry onto the stack. The
85567 ** record number is a randomly generate integer created by NewRowid
85568 ** except when the table has an INTEGER PRIMARY KEY column, in which
85569 ** case the record number is the same as that column.
85571 if( !isView ){
85572 if( IsVirtual(pTab) ){
85573 /* The row that the VUpdate opcode will delete: none */
85574 sqlite3VdbeAddOp2(v, OP_Null, 0, regIns);
85576 if( keyColumn>=0 ){
85577 if( useTempTable ){
85578 sqlite3VdbeAddOp3(v, OP_Column, srcTab, keyColumn, regRowid);
85579 }else if( pSelect ){
85580 sqlite3VdbeAddOp2(v, OP_SCopy, regFromSelect+keyColumn, regRowid);
85581 }else{
85582 VdbeOp *pOp;
85583 sqlite3ExprCode(pParse, pList->a[keyColumn].pExpr, regRowid);
85584 pOp = sqlite3VdbeGetOp(v, -1);
85585 if( ALWAYS(pOp) && pOp->opcode==OP_Null && !IsVirtual(pTab) ){
85586 appendFlag = 1;
85587 pOp->opcode = OP_NewRowid;
85588 pOp->p1 = baseCur;
85589 pOp->p2 = regRowid;
85590 pOp->p3 = regAutoinc;
85593 /* If the PRIMARY KEY expression is NULL, then use OP_NewRowid
85594 ** to generate a unique primary key value.
85596 if( !appendFlag ){
85597 int j1;
85598 if( !IsVirtual(pTab) ){
85599 j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regRowid);
85600 sqlite3VdbeAddOp3(v, OP_NewRowid, baseCur, regRowid, regAutoinc);
85601 sqlite3VdbeJumpHere(v, j1);
85602 }else{
85603 j1 = sqlite3VdbeCurrentAddr(v);
85604 sqlite3VdbeAddOp2(v, OP_IsNull, regRowid, j1+2);
85606 sqlite3VdbeAddOp1(v, OP_MustBeInt, regRowid);
85608 }else if( IsVirtual(pTab) ){
85609 sqlite3VdbeAddOp2(v, OP_Null, 0, regRowid);
85610 }else{
85611 sqlite3VdbeAddOp3(v, OP_NewRowid, baseCur, regRowid, regAutoinc);
85612 appendFlag = 1;
85614 autoIncStep(pParse, regAutoinc, regRowid);
85616 /* Push onto the stack, data for all columns of the new entry, beginning
85617 ** with the first column.
85619 nHidden = 0;
85620 for(i=0; i<pTab->nCol; i++){
85621 int iRegStore = regRowid+1+i;
85622 if( i==pTab->iPKey ){
85623 /* The value of the INTEGER PRIMARY KEY column is always a NULL.
85624 ** Whenever this column is read, the record number will be substituted
85625 ** in its place. So will fill this column with a NULL to avoid
85626 ** taking up data space with information that will never be used. */
85627 sqlite3VdbeAddOp2(v, OP_Null, 0, iRegStore);
85628 continue;
85630 if( pColumn==0 ){
85631 if( IsHiddenColumn(&pTab->aCol[i]) ){
85632 assert( IsVirtual(pTab) );
85633 j = -1;
85634 nHidden++;
85635 }else{
85636 j = i - nHidden;
85638 }else{
85639 for(j=0; j<pColumn->nId; j++){
85640 if( pColumn->a[j].idx==i ) break;
85643 if( j<0 || nColumn==0 || (pColumn && j>=pColumn->nId) ){
85644 sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, iRegStore);
85645 }else if( useTempTable ){
85646 sqlite3VdbeAddOp3(v, OP_Column, srcTab, j, iRegStore);
85647 }else if( pSelect ){
85648 sqlite3VdbeAddOp2(v, OP_SCopy, regFromSelect+j, iRegStore);
85649 }else{
85650 sqlite3ExprCode(pParse, pList->a[j].pExpr, iRegStore);
85654 /* Generate code to check constraints and generate index keys and
85655 ** do the insertion.
85657 #ifndef SQLITE_OMIT_VIRTUALTABLE
85658 if( IsVirtual(pTab) ){
85659 const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
85660 sqlite3VtabMakeWritable(pParse, pTab);
85661 sqlite3VdbeAddOp4(v, OP_VUpdate, 1, pTab->nCol+2, regIns, pVTab, P4_VTAB);
85662 sqlite3MayAbort(pParse);
85663 }else
85664 #endif
85666 int isReplace; /* Set to true if constraints may cause a replace */
85667 sqlite3GenerateConstraintChecks(pParse, pTab, baseCur, regIns, aRegIdx,
85668 keyColumn>=0, 0, onError, endOfLoop, &isReplace
85670 sqlite3FkCheck(pParse, pTab, 0, regIns);
85671 sqlite3CompleteInsertion(
85672 pParse, pTab, baseCur, regIns, aRegIdx, 0, appendFlag, isReplace==0
85677 /* Update the count of rows that are inserted
85679 if( (db->flags & SQLITE_CountRows)!=0 ){
85680 sqlite3VdbeAddOp2(v, OP_AddImm, regRowCount, 1);
85683 if( pTrigger ){
85684 /* Code AFTER triggers */
85685 sqlite3CodeRowTrigger(pParse, pTrigger, TK_INSERT, 0, TRIGGER_AFTER,
85686 pTab, regData-2-pTab->nCol, onError, endOfLoop);
85689 /* The bottom of the main insertion loop, if the data source
85690 ** is a SELECT statement.
85692 sqlite3VdbeResolveLabel(v, endOfLoop);
85693 if( useTempTable ){
85694 sqlite3VdbeAddOp2(v, OP_Next, srcTab, addrCont);
85695 sqlite3VdbeJumpHere(v, addrInsTop);
85696 sqlite3VdbeAddOp1(v, OP_Close, srcTab);
85697 }else if( pSelect ){
85698 sqlite3VdbeAddOp2(v, OP_Goto, 0, addrCont);
85699 sqlite3VdbeJumpHere(v, addrInsTop);
85702 if( !IsVirtual(pTab) && !isView ){
85703 /* Close all tables opened */
85704 sqlite3VdbeAddOp1(v, OP_Close, baseCur);
85705 for(idx=1, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, idx++){
85706 sqlite3VdbeAddOp1(v, OP_Close, idx+baseCur);
85710 insert_end:
85711 /* Update the sqlite_sequence table by storing the content of the
85712 ** maximum rowid counter values recorded while inserting into
85713 ** autoincrement tables.
85715 if( pParse->nested==0 && pParse->pTriggerTab==0 ){
85716 sqlite3AutoincrementEnd(pParse);
85720 ** Return the number of rows inserted. If this routine is
85721 ** generating code because of a call to sqlite3NestedParse(), do not
85722 ** invoke the callback function.
85724 if( (db->flags&SQLITE_CountRows) && !pParse->nested && !pParse->pTriggerTab ){
85725 sqlite3VdbeAddOp2(v, OP_ResultRow, regRowCount, 1);
85726 sqlite3VdbeSetNumCols(v, 1);
85727 sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows inserted", SQLITE_STATIC);
85730 insert_cleanup:
85731 sqlite3SrcListDelete(db, pTabList);
85732 sqlite3ExprListDelete(db, pList);
85733 sqlite3SelectDelete(db, pSelect);
85734 sqlite3IdListDelete(db, pColumn);
85735 sqlite3DbFree(db, aRegIdx);
85738 /* Make sure "isView" and other macros defined above are undefined. Otherwise
85739 ** thely may interfere with compilation of other functions in this file
85740 ** (or in another file, if this file becomes part of the amalgamation). */
85741 #ifdef isView
85742 #undef isView
85743 #endif
85744 #ifdef pTrigger
85745 #undef pTrigger
85746 #endif
85747 #ifdef tmask
85748 #undef tmask
85749 #endif
85753 ** Generate code to do constraint checks prior to an INSERT or an UPDATE.
85755 ** The input is a range of consecutive registers as follows:
85757 ** 1. The rowid of the row after the update.
85759 ** 2. The data in the first column of the entry after the update.
85761 ** i. Data from middle columns...
85763 ** N. The data in the last column of the entry after the update.
85765 ** The regRowid parameter is the index of the register containing (1).
85767 ** If isUpdate is true and rowidChng is non-zero, then rowidChng contains
85768 ** the address of a register containing the rowid before the update takes
85769 ** place. isUpdate is true for UPDATEs and false for INSERTs. If isUpdate
85770 ** is false, indicating an INSERT statement, then a non-zero rowidChng
85771 ** indicates that the rowid was explicitly specified as part of the
85772 ** INSERT statement. If rowidChng is false, it means that the rowid is
85773 ** computed automatically in an insert or that the rowid value is not
85774 ** modified by an update.
85776 ** The code generated by this routine store new index entries into
85777 ** registers identified by aRegIdx[]. No index entry is created for
85778 ** indices where aRegIdx[i]==0. The order of indices in aRegIdx[] is
85779 ** the same as the order of indices on the linked list of indices
85780 ** attached to the table.
85782 ** This routine also generates code to check constraints. NOT NULL,
85783 ** CHECK, and UNIQUE constraints are all checked. If a constraint fails,
85784 ** then the appropriate action is performed. There are five possible
85785 ** actions: ROLLBACK, ABORT, FAIL, REPLACE, and IGNORE.
85787 ** Constraint type Action What Happens
85788 ** --------------- ---------- ----------------------------------------
85789 ** any ROLLBACK The current transaction is rolled back and
85790 ** sqlite3_exec() returns immediately with a
85791 ** return code of SQLITE_CONSTRAINT.
85793 ** any ABORT Back out changes from the current command
85794 ** only (do not do a complete rollback) then
85795 ** cause sqlite3_exec() to return immediately
85796 ** with SQLITE_CONSTRAINT.
85798 ** any FAIL Sqlite_exec() returns immediately with a
85799 ** return code of SQLITE_CONSTRAINT. The
85800 ** transaction is not rolled back and any
85801 ** prior changes are retained.
85803 ** any IGNORE The record number and data is popped from
85804 ** the stack and there is an immediate jump
85805 ** to label ignoreDest.
85807 ** NOT NULL REPLACE The NULL value is replace by the default
85808 ** value for that column. If the default value
85809 ** is NULL, the action is the same as ABORT.
85811 ** UNIQUE REPLACE The other row that conflicts with the row
85812 ** being inserted is removed.
85814 ** CHECK REPLACE Illegal. The results in an exception.
85816 ** Which action to take is determined by the overrideError parameter.
85817 ** Or if overrideError==OE_Default, then the pParse->onError parameter
85818 ** is used. Or if pParse->onError==OE_Default then the onError value
85819 ** for the constraint is used.
85821 ** The calling routine must open a read/write cursor for pTab with
85822 ** cursor number "baseCur". All indices of pTab must also have open
85823 ** read/write cursors with cursor number baseCur+i for the i-th cursor.
85824 ** Except, if there is no possibility of a REPLACE action then
85825 ** cursors do not need to be open for indices where aRegIdx[i]==0.
85827 SQLITE_PRIVATE void sqlite3GenerateConstraintChecks(
85828 Parse *pParse, /* The parser context */
85829 Table *pTab, /* the table into which we are inserting */
85830 int baseCur, /* Index of a read/write cursor pointing at pTab */
85831 int regRowid, /* Index of the range of input registers */
85832 int *aRegIdx, /* Register used by each index. 0 for unused indices */
85833 int rowidChng, /* True if the rowid might collide with existing entry */
85834 int isUpdate, /* True for UPDATE, False for INSERT */
85835 int overrideError, /* Override onError to this if not OE_Default */
85836 int ignoreDest, /* Jump to this label on an OE_Ignore resolution */
85837 int *pbMayReplace /* OUT: Set to true if constraint may cause a replace */
85839 int i; /* loop counter */
85840 Vdbe *v; /* VDBE under constrution */
85841 int nCol; /* Number of columns */
85842 int onError; /* Conflict resolution strategy */
85843 int j1; /* Addresss of jump instruction */
85844 int j2 = 0, j3; /* Addresses of jump instructions */
85845 int regData; /* Register containing first data column */
85846 int iCur; /* Table cursor number */
85847 Index *pIdx; /* Pointer to one of the indices */
85848 int seenReplace = 0; /* True if REPLACE is used to resolve INT PK conflict */
85849 int regOldRowid = (rowidChng && isUpdate) ? rowidChng : regRowid;
85851 v = sqlite3GetVdbe(pParse);
85852 assert( v!=0 );
85853 assert( pTab->pSelect==0 ); /* This table is not a VIEW */
85854 nCol = pTab->nCol;
85855 regData = regRowid + 1;
85857 /* Test all NOT NULL constraints.
85859 for(i=0; i<nCol; i++){
85860 if( i==pTab->iPKey ){
85861 continue;
85863 onError = pTab->aCol[i].notNull;
85864 if( onError==OE_None ) continue;
85865 if( overrideError!=OE_Default ){
85866 onError = overrideError;
85867 }else if( onError==OE_Default ){
85868 onError = OE_Abort;
85870 if( onError==OE_Replace && pTab->aCol[i].pDflt==0 ){
85871 onError = OE_Abort;
85873 assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
85874 || onError==OE_Ignore || onError==OE_Replace );
85875 switch( onError ){
85876 case OE_Abort:
85877 sqlite3MayAbort(pParse);
85878 case OE_Rollback:
85879 case OE_Fail: {
85880 char *zMsg;
85881 sqlite3VdbeAddOp3(v, OP_HaltIfNull,
85882 SQLITE_CONSTRAINT, onError, regData+i);
85883 zMsg = sqlite3MPrintf(pParse->db, "%s.%s may not be NULL",
85884 pTab->zName, pTab->aCol[i].zName);
85885 sqlite3VdbeChangeP4(v, -1, zMsg, P4_DYNAMIC);
85886 break;
85888 case OE_Ignore: {
85889 sqlite3VdbeAddOp2(v, OP_IsNull, regData+i, ignoreDest);
85890 break;
85892 default: {
85893 assert( onError==OE_Replace );
85894 j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regData+i);
85895 sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, regData+i);
85896 sqlite3VdbeJumpHere(v, j1);
85897 break;
85902 /* Test all CHECK constraints
85904 #ifndef SQLITE_OMIT_CHECK
85905 if( pTab->pCheck && (pParse->db->flags & SQLITE_IgnoreChecks)==0 ){
85906 int allOk = sqlite3VdbeMakeLabel(v);
85907 pParse->ckBase = regData;
85908 sqlite3ExprIfTrue(pParse, pTab->pCheck, allOk, SQLITE_JUMPIFNULL);
85909 onError = overrideError!=OE_Default ? overrideError : OE_Abort;
85910 if( onError==OE_Ignore ){
85911 sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest);
85912 }else{
85913 if( onError==OE_Replace ) onError = OE_Abort; /* IMP: R-15569-63625 */
85914 sqlite3HaltConstraint(pParse, onError, 0, 0);
85916 sqlite3VdbeResolveLabel(v, allOk);
85918 #endif /* !defined(SQLITE_OMIT_CHECK) */
85920 /* If we have an INTEGER PRIMARY KEY, make sure the primary key
85921 ** of the new record does not previously exist. Except, if this
85922 ** is an UPDATE and the primary key is not changing, that is OK.
85924 if( rowidChng ){
85925 onError = pTab->keyConf;
85926 if( overrideError!=OE_Default ){
85927 onError = overrideError;
85928 }else if( onError==OE_Default ){
85929 onError = OE_Abort;
85932 if( isUpdate ){
85933 j2 = sqlite3VdbeAddOp3(v, OP_Eq, regRowid, 0, rowidChng);
85935 j3 = sqlite3VdbeAddOp3(v, OP_NotExists, baseCur, 0, regRowid);
85936 switch( onError ){
85937 default: {
85938 onError = OE_Abort;
85939 /* Fall thru into the next case */
85941 case OE_Rollback:
85942 case OE_Abort:
85943 case OE_Fail: {
85944 sqlite3HaltConstraint(
85945 pParse, onError, "PRIMARY KEY must be unique", P4_STATIC);
85946 break;
85948 case OE_Replace: {
85949 /* If there are DELETE triggers on this table and the
85950 ** recursive-triggers flag is set, call GenerateRowDelete() to
85951 ** remove the conflicting row from the the table. This will fire
85952 ** the triggers and remove both the table and index b-tree entries.
85954 ** Otherwise, if there are no triggers or the recursive-triggers
85955 ** flag is not set, but the table has one or more indexes, call
85956 ** GenerateRowIndexDelete(). This removes the index b-tree entries
85957 ** only. The table b-tree entry will be replaced by the new entry
85958 ** when it is inserted.
85960 ** If either GenerateRowDelete() or GenerateRowIndexDelete() is called,
85961 ** also invoke MultiWrite() to indicate that this VDBE may require
85962 ** statement rollback (if the statement is aborted after the delete
85963 ** takes place). Earlier versions called sqlite3MultiWrite() regardless,
85964 ** but being more selective here allows statements like:
85966 ** REPLACE INTO t(rowid) VALUES($newrowid)
85968 ** to run without a statement journal if there are no indexes on the
85969 ** table.
85971 Trigger *pTrigger = 0;
85972 if( pParse->db->flags&SQLITE_RecTriggers ){
85973 pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
85975 if( pTrigger || sqlite3FkRequired(pParse, pTab, 0, 0) ){
85976 sqlite3MultiWrite(pParse);
85977 sqlite3GenerateRowDelete(
85978 pParse, pTab, baseCur, regRowid, 0, pTrigger, OE_Replace
85980 }else if( pTab->pIndex ){
85981 sqlite3MultiWrite(pParse);
85982 sqlite3GenerateRowIndexDelete(pParse, pTab, baseCur, 0);
85984 seenReplace = 1;
85985 break;
85987 case OE_Ignore: {
85988 assert( seenReplace==0 );
85989 sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest);
85990 break;
85993 sqlite3VdbeJumpHere(v, j3);
85994 if( isUpdate ){
85995 sqlite3VdbeJumpHere(v, j2);
85999 /* Test all UNIQUE constraints by creating entries for each UNIQUE
86000 ** index and making sure that duplicate entries do not already exist.
86001 ** Add the new records to the indices as we go.
86003 for(iCur=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, iCur++){
86004 int regIdx;
86005 int regR;
86007 if( aRegIdx[iCur]==0 ) continue; /* Skip unused indices */
86009 /* Create a key for accessing the index entry */
86010 regIdx = sqlite3GetTempRange(pParse, pIdx->nColumn+1);
86011 for(i=0; i<pIdx->nColumn; i++){
86012 int idx = pIdx->aiColumn[i];
86013 if( idx==pTab->iPKey ){
86014 sqlite3VdbeAddOp2(v, OP_SCopy, regRowid, regIdx+i);
86015 }else{
86016 sqlite3VdbeAddOp2(v, OP_SCopy, regData+idx, regIdx+i);
86019 sqlite3VdbeAddOp2(v, OP_SCopy, regRowid, regIdx+i);
86020 sqlite3VdbeAddOp3(v, OP_MakeRecord, regIdx, pIdx->nColumn+1, aRegIdx[iCur]);
86021 sqlite3VdbeChangeP4(v, -1, sqlite3IndexAffinityStr(v, pIdx), P4_TRANSIENT);
86022 sqlite3ExprCacheAffinityChange(pParse, regIdx, pIdx->nColumn+1);
86024 /* Find out what action to take in case there is an indexing conflict */
86025 onError = pIdx->onError;
86026 if( onError==OE_None ){
86027 sqlite3ReleaseTempRange(pParse, regIdx, pIdx->nColumn+1);
86028 continue; /* pIdx is not a UNIQUE index */
86030 if( overrideError!=OE_Default ){
86031 onError = overrideError;
86032 }else if( onError==OE_Default ){
86033 onError = OE_Abort;
86035 if( seenReplace ){
86036 if( onError==OE_Ignore ) onError = OE_Replace;
86037 else if( onError==OE_Fail ) onError = OE_Abort;
86040 /* Check to see if the new index entry will be unique */
86041 regR = sqlite3GetTempReg(pParse);
86042 sqlite3VdbeAddOp2(v, OP_SCopy, regOldRowid, regR);
86043 j3 = sqlite3VdbeAddOp4(v, OP_IsUnique, baseCur+iCur+1, 0,
86044 regR, SQLITE_INT_TO_PTR(regIdx),
86045 P4_INT32);
86046 sqlite3ReleaseTempRange(pParse, regIdx, pIdx->nColumn+1);
86048 /* Generate code that executes if the new index entry is not unique */
86049 assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
86050 || onError==OE_Ignore || onError==OE_Replace );
86051 switch( onError ){
86052 case OE_Rollback:
86053 case OE_Abort:
86054 case OE_Fail: {
86055 int j;
86056 StrAccum errMsg;
86057 const char *zSep;
86058 char *zErr;
86060 sqlite3StrAccumInit(&errMsg, 0, 0, 200);
86061 errMsg.db = pParse->db;
86062 zSep = pIdx->nColumn>1 ? "columns " : "column ";
86063 for(j=0; j<pIdx->nColumn; j++){
86064 char *zCol = pTab->aCol[pIdx->aiColumn[j]].zName;
86065 sqlite3StrAccumAppend(&errMsg, zSep, -1);
86066 zSep = ", ";
86067 sqlite3StrAccumAppend(&errMsg, zCol, -1);
86069 sqlite3StrAccumAppend(&errMsg,
86070 pIdx->nColumn>1 ? " are not unique" : " is not unique", -1);
86071 zErr = sqlite3StrAccumFinish(&errMsg);
86072 sqlite3HaltConstraint(pParse, onError, zErr, 0);
86073 sqlite3DbFree(errMsg.db, zErr);
86074 break;
86076 case OE_Ignore: {
86077 assert( seenReplace==0 );
86078 sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest);
86079 break;
86081 default: {
86082 Trigger *pTrigger = 0;
86083 assert( onError==OE_Replace );
86084 sqlite3MultiWrite(pParse);
86085 if( pParse->db->flags&SQLITE_RecTriggers ){
86086 pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
86088 sqlite3GenerateRowDelete(
86089 pParse, pTab, baseCur, regR, 0, pTrigger, OE_Replace
86091 seenReplace = 1;
86092 break;
86095 sqlite3VdbeJumpHere(v, j3);
86096 sqlite3ReleaseTempReg(pParse, regR);
86099 if( pbMayReplace ){
86100 *pbMayReplace = seenReplace;
86105 ** This routine generates code to finish the INSERT or UPDATE operation
86106 ** that was started by a prior call to sqlite3GenerateConstraintChecks.
86107 ** A consecutive range of registers starting at regRowid contains the
86108 ** rowid and the content to be inserted.
86110 ** The arguments to this routine should be the same as the first six
86111 ** arguments to sqlite3GenerateConstraintChecks.
86113 SQLITE_PRIVATE void sqlite3CompleteInsertion(
86114 Parse *pParse, /* The parser context */
86115 Table *pTab, /* the table into which we are inserting */
86116 int baseCur, /* Index of a read/write cursor pointing at pTab */
86117 int regRowid, /* Range of content */
86118 int *aRegIdx, /* Register used by each index. 0 for unused indices */
86119 int isUpdate, /* True for UPDATE, False for INSERT */
86120 int appendBias, /* True if this is likely to be an append */
86121 int useSeekResult /* True to set the USESEEKRESULT flag on OP_[Idx]Insert */
86123 int i;
86124 Vdbe *v;
86125 int nIdx;
86126 Index *pIdx;
86127 u8 pik_flags;
86128 int regData;
86129 int regRec;
86131 v = sqlite3GetVdbe(pParse);
86132 assert( v!=0 );
86133 assert( pTab->pSelect==0 ); /* This table is not a VIEW */
86134 for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){}
86135 for(i=nIdx-1; i>=0; i--){
86136 if( aRegIdx[i]==0 ) continue;
86137 sqlite3VdbeAddOp2(v, OP_IdxInsert, baseCur+i+1, aRegIdx[i]);
86138 if( useSeekResult ){
86139 sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
86142 regData = regRowid + 1;
86143 regRec = sqlite3GetTempReg(pParse);
86144 sqlite3VdbeAddOp3(v, OP_MakeRecord, regData, pTab->nCol, regRec);
86145 sqlite3TableAffinityStr(v, pTab);
86146 sqlite3ExprCacheAffinityChange(pParse, regData, pTab->nCol);
86147 if( pParse->nested ){
86148 pik_flags = 0;
86149 }else{
86150 pik_flags = OPFLAG_NCHANGE;
86151 pik_flags |= (isUpdate?OPFLAG_ISUPDATE:OPFLAG_LASTROWID);
86153 if( appendBias ){
86154 pik_flags |= OPFLAG_APPEND;
86156 if( useSeekResult ){
86157 pik_flags |= OPFLAG_USESEEKRESULT;
86159 sqlite3VdbeAddOp3(v, OP_Insert, baseCur, regRec, regRowid);
86160 if( !pParse->nested ){
86161 sqlite3VdbeChangeP4(v, -1, pTab->zName, P4_TRANSIENT);
86163 sqlite3VdbeChangeP5(v, pik_flags);
86167 ** Generate code that will open cursors for a table and for all
86168 ** indices of that table. The "baseCur" parameter is the cursor number used
86169 ** for the table. Indices are opened on subsequent cursors.
86171 ** Return the number of indices on the table.
86173 SQLITE_PRIVATE int sqlite3OpenTableAndIndices(
86174 Parse *pParse, /* Parsing context */
86175 Table *pTab, /* Table to be opened */
86176 int baseCur, /* Cursor number assigned to the table */
86177 int op /* OP_OpenRead or OP_OpenWrite */
86179 int i;
86180 int iDb;
86181 Index *pIdx;
86182 Vdbe *v;
86184 if( IsVirtual(pTab) ) return 0;
86185 iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
86186 v = sqlite3GetVdbe(pParse);
86187 assert( v!=0 );
86188 sqlite3OpenTable(pParse, baseCur, iDb, pTab, op);
86189 for(i=1, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
86190 KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIdx);
86191 assert( pIdx->pSchema==pTab->pSchema );
86192 sqlite3VdbeAddOp4(v, op, i+baseCur, pIdx->tnum, iDb,
86193 (char*)pKey, P4_KEYINFO_HANDOFF);
86194 VdbeComment((v, "%s", pIdx->zName));
86196 if( pParse->nTab<baseCur+i ){
86197 pParse->nTab = baseCur+i;
86199 return i-1;
86203 #ifdef SQLITE_TEST
86205 ** The following global variable is incremented whenever the
86206 ** transfer optimization is used. This is used for testing
86207 ** purposes only - to make sure the transfer optimization really
86208 ** is happening when it is suppose to.
86210 SQLITE_API int sqlite3_xferopt_count;
86211 #endif /* SQLITE_TEST */
86214 #ifndef SQLITE_OMIT_XFER_OPT
86216 ** Check to collation names to see if they are compatible.
86218 static int xferCompatibleCollation(const char *z1, const char *z2){
86219 if( z1==0 ){
86220 return z2==0;
86222 if( z2==0 ){
86223 return 0;
86225 return sqlite3StrICmp(z1, z2)==0;
86230 ** Check to see if index pSrc is compatible as a source of data
86231 ** for index pDest in an insert transfer optimization. The rules
86232 ** for a compatible index:
86234 ** * The index is over the same set of columns
86235 ** * The same DESC and ASC markings occurs on all columns
86236 ** * The same onError processing (OE_Abort, OE_Ignore, etc)
86237 ** * The same collating sequence on each column
86239 static int xferCompatibleIndex(Index *pDest, Index *pSrc){
86240 int i;
86241 assert( pDest && pSrc );
86242 assert( pDest->pTable!=pSrc->pTable );
86243 if( pDest->nColumn!=pSrc->nColumn ){
86244 return 0; /* Different number of columns */
86246 if( pDest->onError!=pSrc->onError ){
86247 return 0; /* Different conflict resolution strategies */
86249 for(i=0; i<pSrc->nColumn; i++){
86250 if( pSrc->aiColumn[i]!=pDest->aiColumn[i] ){
86251 return 0; /* Different columns indexed */
86253 if( pSrc->aSortOrder[i]!=pDest->aSortOrder[i] ){
86254 return 0; /* Different sort orders */
86256 if( !xferCompatibleCollation(pSrc->azColl[i],pDest->azColl[i]) ){
86257 return 0; /* Different collating sequences */
86261 /* If no test above fails then the indices must be compatible */
86262 return 1;
86266 ** Attempt the transfer optimization on INSERTs of the form
86268 ** INSERT INTO tab1 SELECT * FROM tab2;
86270 ** This optimization is only attempted if
86272 ** (1) tab1 and tab2 have identical schemas including all the
86273 ** same indices and constraints
86275 ** (2) tab1 and tab2 are different tables
86277 ** (3) There must be no triggers on tab1
86279 ** (4) The result set of the SELECT statement is "*"
86281 ** (5) The SELECT statement has no WHERE, HAVING, ORDER BY, GROUP BY,
86282 ** or LIMIT clause.
86284 ** (6) The SELECT statement is a simple (not a compound) select that
86285 ** contains only tab2 in its FROM clause
86287 ** This method for implementing the INSERT transfers raw records from
86288 ** tab2 over to tab1. The columns are not decoded. Raw records from
86289 ** the indices of tab2 are transfered to tab1 as well. In so doing,
86290 ** the resulting tab1 has much less fragmentation.
86292 ** This routine returns TRUE if the optimization is attempted. If any
86293 ** of the conditions above fail so that the optimization should not
86294 ** be attempted, then this routine returns FALSE.
86296 static int xferOptimization(
86297 Parse *pParse, /* Parser context */
86298 Table *pDest, /* The table we are inserting into */
86299 Select *pSelect, /* A SELECT statement to use as the data source */
86300 int onError, /* How to handle constraint errors */
86301 int iDbDest /* The database of pDest */
86303 ExprList *pEList; /* The result set of the SELECT */
86304 Table *pSrc; /* The table in the FROM clause of SELECT */
86305 Index *pSrcIdx, *pDestIdx; /* Source and destination indices */
86306 struct SrcList_item *pItem; /* An element of pSelect->pSrc */
86307 int i; /* Loop counter */
86308 int iDbSrc; /* The database of pSrc */
86309 int iSrc, iDest; /* Cursors from source and destination */
86310 int addr1, addr2; /* Loop addresses */
86311 int emptyDestTest; /* Address of test for empty pDest */
86312 int emptySrcTest; /* Address of test for empty pSrc */
86313 Vdbe *v; /* The VDBE we are building */
86314 KeyInfo *pKey; /* Key information for an index */
86315 int regAutoinc; /* Memory register used by AUTOINC */
86316 int destHasUniqueIdx = 0; /* True if pDest has a UNIQUE index */
86317 int regData, regRowid; /* Registers holding data and rowid */
86319 if( pSelect==0 ){
86320 return 0; /* Must be of the form INSERT INTO ... SELECT ... */
86322 if( sqlite3TriggerList(pParse, pDest) ){
86323 return 0; /* tab1 must not have triggers */
86325 #ifndef SQLITE_OMIT_VIRTUALTABLE
86326 if( pDest->tabFlags & TF_Virtual ){
86327 return 0; /* tab1 must not be a virtual table */
86329 #endif
86330 if( onError==OE_Default ){
86331 onError = OE_Abort;
86333 if( onError!=OE_Abort && onError!=OE_Rollback ){
86334 return 0; /* Cannot do OR REPLACE or OR IGNORE or OR FAIL */
86336 assert(pSelect->pSrc); /* allocated even if there is no FROM clause */
86337 if( pSelect->pSrc->nSrc!=1 ){
86338 return 0; /* FROM clause must have exactly one term */
86340 if( pSelect->pSrc->a[0].pSelect ){
86341 return 0; /* FROM clause cannot contain a subquery */
86343 if( pSelect->pWhere ){
86344 return 0; /* SELECT may not have a WHERE clause */
86346 if( pSelect->pOrderBy ){
86347 return 0; /* SELECT may not have an ORDER BY clause */
86349 /* Do not need to test for a HAVING clause. If HAVING is present but
86350 ** there is no ORDER BY, we will get an error. */
86351 if( pSelect->pGroupBy ){
86352 return 0; /* SELECT may not have a GROUP BY clause */
86354 if( pSelect->pLimit ){
86355 return 0; /* SELECT may not have a LIMIT clause */
86357 assert( pSelect->pOffset==0 ); /* Must be so if pLimit==0 */
86358 if( pSelect->pPrior ){
86359 return 0; /* SELECT may not be a compound query */
86361 if( pSelect->selFlags & SF_Distinct ){
86362 return 0; /* SELECT may not be DISTINCT */
86364 pEList = pSelect->pEList;
86365 assert( pEList!=0 );
86366 if( pEList->nExpr!=1 ){
86367 return 0; /* The result set must have exactly one column */
86369 assert( pEList->a[0].pExpr );
86370 if( pEList->a[0].pExpr->op!=TK_ALL ){
86371 return 0; /* The result set must be the special operator "*" */
86374 /* At this point we have established that the statement is of the
86375 ** correct syntactic form to participate in this optimization. Now
86376 ** we have to check the semantics.
86378 pItem = pSelect->pSrc->a;
86379 pSrc = sqlite3LocateTable(pParse, 0, pItem->zName, pItem->zDatabase);
86380 if( pSrc==0 ){
86381 return 0; /* FROM clause does not contain a real table */
86383 if( pSrc==pDest ){
86384 return 0; /* tab1 and tab2 may not be the same table */
86386 #ifndef SQLITE_OMIT_VIRTUALTABLE
86387 if( pSrc->tabFlags & TF_Virtual ){
86388 return 0; /* tab2 must not be a virtual table */
86390 #endif
86391 if( pSrc->pSelect ){
86392 return 0; /* tab2 may not be a view */
86394 if( pDest->nCol!=pSrc->nCol ){
86395 return 0; /* Number of columns must be the same in tab1 and tab2 */
86397 if( pDest->iPKey!=pSrc->iPKey ){
86398 return 0; /* Both tables must have the same INTEGER PRIMARY KEY */
86400 for(i=0; i<pDest->nCol; i++){
86401 if( pDest->aCol[i].affinity!=pSrc->aCol[i].affinity ){
86402 return 0; /* Affinity must be the same on all columns */
86404 if( !xferCompatibleCollation(pDest->aCol[i].zColl, pSrc->aCol[i].zColl) ){
86405 return 0; /* Collating sequence must be the same on all columns */
86407 if( pDest->aCol[i].notNull && !pSrc->aCol[i].notNull ){
86408 return 0; /* tab2 must be NOT NULL if tab1 is */
86411 for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
86412 if( pDestIdx->onError!=OE_None ){
86413 destHasUniqueIdx = 1;
86415 for(pSrcIdx=pSrc->pIndex; pSrcIdx; pSrcIdx=pSrcIdx->pNext){
86416 if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;
86418 if( pSrcIdx==0 ){
86419 return 0; /* pDestIdx has no corresponding index in pSrc */
86422 #ifndef SQLITE_OMIT_CHECK
86423 if( pDest->pCheck && sqlite3ExprCompare(pSrc->pCheck, pDest->pCheck) ){
86424 return 0; /* Tables have different CHECK constraints. Ticket #2252 */
86426 #endif
86428 /* If we get this far, it means either:
86430 ** * We can always do the transfer if the table contains an
86431 ** an integer primary key
86433 ** * We can conditionally do the transfer if the destination
86434 ** table is empty.
86436 #ifdef SQLITE_TEST
86437 sqlite3_xferopt_count++;
86438 #endif
86439 iDbSrc = sqlite3SchemaToIndex(pParse->db, pSrc->pSchema);
86440 v = sqlite3GetVdbe(pParse);
86441 sqlite3CodeVerifySchema(pParse, iDbSrc);
86442 iSrc = pParse->nTab++;
86443 iDest = pParse->nTab++;
86444 regAutoinc = autoIncBegin(pParse, iDbDest, pDest);
86445 sqlite3OpenTable(pParse, iDest, iDbDest, pDest, OP_OpenWrite);
86446 if( (pDest->iPKey<0 && pDest->pIndex!=0) || destHasUniqueIdx ){
86447 /* If tables do not have an INTEGER PRIMARY KEY and there
86448 ** are indices to be copied and the destination is not empty,
86449 ** we have to disallow the transfer optimization because the
86450 ** the rowids might change which will mess up indexing.
86452 ** Or if the destination has a UNIQUE index and is not empty,
86453 ** we also disallow the transfer optimization because we cannot
86454 ** insure that all entries in the union of DEST and SRC will be
86455 ** unique.
86457 addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iDest, 0);
86458 emptyDestTest = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0);
86459 sqlite3VdbeJumpHere(v, addr1);
86460 }else{
86461 emptyDestTest = 0;
86463 sqlite3OpenTable(pParse, iSrc, iDbSrc, pSrc, OP_OpenRead);
86464 emptySrcTest = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0);
86465 regData = sqlite3GetTempReg(pParse);
86466 regRowid = sqlite3GetTempReg(pParse);
86467 if( pDest->iPKey>=0 ){
86468 addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid);
86469 addr2 = sqlite3VdbeAddOp3(v, OP_NotExists, iDest, 0, regRowid);
86470 sqlite3HaltConstraint(
86471 pParse, onError, "PRIMARY KEY must be unique", P4_STATIC);
86472 sqlite3VdbeJumpHere(v, addr2);
86473 autoIncStep(pParse, regAutoinc, regRowid);
86474 }else if( pDest->pIndex==0 ){
86475 addr1 = sqlite3VdbeAddOp2(v, OP_NewRowid, iDest, regRowid);
86476 }else{
86477 addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid);
86478 assert( (pDest->tabFlags & TF_Autoincrement)==0 );
86480 sqlite3VdbeAddOp2(v, OP_RowData, iSrc, regData);
86481 sqlite3VdbeAddOp3(v, OP_Insert, iDest, regData, regRowid);
86482 sqlite3VdbeChangeP5(v, OPFLAG_NCHANGE|OPFLAG_LASTROWID|OPFLAG_APPEND);
86483 sqlite3VdbeChangeP4(v, -1, pDest->zName, 0);
86484 sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1);
86485 for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
86486 for(pSrcIdx=pSrc->pIndex; ALWAYS(pSrcIdx); pSrcIdx=pSrcIdx->pNext){
86487 if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;
86489 assert( pSrcIdx );
86490 sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0);
86491 sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
86492 pKey = sqlite3IndexKeyinfo(pParse, pSrcIdx);
86493 sqlite3VdbeAddOp4(v, OP_OpenRead, iSrc, pSrcIdx->tnum, iDbSrc,
86494 (char*)pKey, P4_KEYINFO_HANDOFF);
86495 VdbeComment((v, "%s", pSrcIdx->zName));
86496 pKey = sqlite3IndexKeyinfo(pParse, pDestIdx);
86497 sqlite3VdbeAddOp4(v, OP_OpenWrite, iDest, pDestIdx->tnum, iDbDest,
86498 (char*)pKey, P4_KEYINFO_HANDOFF);
86499 VdbeComment((v, "%s", pDestIdx->zName));
86500 addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0);
86501 sqlite3VdbeAddOp2(v, OP_RowKey, iSrc, regData);
86502 sqlite3VdbeAddOp3(v, OP_IdxInsert, iDest, regData, 1);
86503 sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1+1);
86504 sqlite3VdbeJumpHere(v, addr1);
86506 sqlite3VdbeJumpHere(v, emptySrcTest);
86507 sqlite3ReleaseTempReg(pParse, regRowid);
86508 sqlite3ReleaseTempReg(pParse, regData);
86509 sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0);
86510 sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
86511 if( emptyDestTest ){
86512 sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_OK, 0);
86513 sqlite3VdbeJumpHere(v, emptyDestTest);
86514 sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
86515 return 0;
86516 }else{
86517 return 1;
86520 #endif /* SQLITE_OMIT_XFER_OPT */
86522 /************** End of insert.c **********************************************/
86523 /************** Begin file legacy.c ******************************************/
86525 ** 2001 September 15
86527 ** The author disclaims copyright to this source code. In place of
86528 ** a legal notice, here is a blessing:
86530 ** May you do good and not evil.
86531 ** May you find forgiveness for yourself and forgive others.
86532 ** May you share freely, never taking more than you give.
86534 *************************************************************************
86535 ** Main file for the SQLite library. The routines in this file
86536 ** implement the programmer interface to the library. Routines in
86537 ** other files are for internal use by SQLite and should not be
86538 ** accessed by users of the library.
86543 ** Execute SQL code. Return one of the SQLITE_ success/failure
86544 ** codes. Also write an error message into memory obtained from
86545 ** malloc() and make *pzErrMsg point to that message.
86547 ** If the SQL is a query, then for each row in the query result
86548 ** the xCallback() function is called. pArg becomes the first
86549 ** argument to xCallback(). If xCallback=NULL then no callback
86550 ** is invoked, even for queries.
86552 SQLITE_API int sqlite3_exec(
86553 sqlite3 *db, /* The database on which the SQL executes */
86554 const char *zSql, /* The SQL to be executed */
86555 sqlite3_callback xCallback, /* Invoke this callback routine */
86556 void *pArg, /* First argument to xCallback() */
86557 char **pzErrMsg /* Write error messages here */
86559 int rc = SQLITE_OK; /* Return code */
86560 const char *zLeftover; /* Tail of unprocessed SQL */
86561 sqlite3_stmt *pStmt = 0; /* The current SQL statement */
86562 char **azCols = 0; /* Names of result columns */
86563 int nRetry = 0; /* Number of retry attempts */
86564 int callbackIsInit; /* True if callback data is initialized */
86566 if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
86567 if( zSql==0 ) zSql = "";
86569 sqlite3_mutex_enter(db->mutex);
86570 sqlite3Error(db, SQLITE_OK, 0);
86571 while( (rc==SQLITE_OK || (rc==SQLITE_SCHEMA && (++nRetry)<2)) && zSql[0] ){
86572 int nCol;
86573 char **azVals = 0;
86575 pStmt = 0;
86576 rc = sqlite3_prepare(db, zSql, -1, &pStmt, &zLeftover);
86577 assert( rc==SQLITE_OK || pStmt==0 );
86578 if( rc!=SQLITE_OK ){
86579 continue;
86581 if( !pStmt ){
86582 /* this happens for a comment or white-space */
86583 zSql = zLeftover;
86584 continue;
86587 callbackIsInit = 0;
86588 nCol = sqlite3_column_count(pStmt);
86590 while( 1 ){
86591 int i;
86592 rc = sqlite3_step(pStmt);
86594 /* Invoke the callback function if required */
86595 if( xCallback && (SQLITE_ROW==rc ||
86596 (SQLITE_DONE==rc && !callbackIsInit
86597 && db->flags&SQLITE_NullCallback)) ){
86598 if( !callbackIsInit ){
86599 azCols = sqlite3DbMallocZero(db, 2*nCol*sizeof(const char*) + 1);
86600 if( azCols==0 ){
86601 goto exec_out;
86603 for(i=0; i<nCol; i++){
86604 azCols[i] = (char *)sqlite3_column_name(pStmt, i);
86605 /* sqlite3VdbeSetColName() installs column names as UTF8
86606 ** strings so there is no way for sqlite3_column_name() to fail. */
86607 assert( azCols[i]!=0 );
86609 callbackIsInit = 1;
86611 if( rc==SQLITE_ROW ){
86612 azVals = &azCols[nCol];
86613 for(i=0; i<nCol; i++){
86614 azVals[i] = (char *)sqlite3_column_text(pStmt, i);
86615 if( !azVals[i] && sqlite3_column_type(pStmt, i)!=SQLITE_NULL ){
86616 db->mallocFailed = 1;
86617 goto exec_out;
86621 if( xCallback(pArg, nCol, azVals, azCols) ){
86622 rc = SQLITE_ABORT;
86623 sqlite3VdbeFinalize((Vdbe *)pStmt);
86624 pStmt = 0;
86625 sqlite3Error(db, SQLITE_ABORT, 0);
86626 goto exec_out;
86630 if( rc!=SQLITE_ROW ){
86631 rc = sqlite3VdbeFinalize((Vdbe *)pStmt);
86632 pStmt = 0;
86633 if( rc!=SQLITE_SCHEMA ){
86634 nRetry = 0;
86635 zSql = zLeftover;
86636 while( sqlite3Isspace(zSql[0]) ) zSql++;
86638 break;
86642 sqlite3DbFree(db, azCols);
86643 azCols = 0;
86646 exec_out:
86647 if( pStmt ) sqlite3VdbeFinalize((Vdbe *)pStmt);
86648 sqlite3DbFree(db, azCols);
86650 rc = sqlite3ApiExit(db, rc);
86651 if( rc!=SQLITE_OK && ALWAYS(rc==sqlite3_errcode(db)) && pzErrMsg ){
86652 int nErrMsg = 1 + sqlite3Strlen30(sqlite3_errmsg(db));
86653 *pzErrMsg = sqlite3Malloc(nErrMsg);
86654 if( *pzErrMsg ){
86655 memcpy(*pzErrMsg, sqlite3_errmsg(db), nErrMsg);
86656 }else{
86657 rc = SQLITE_NOMEM;
86658 sqlite3Error(db, SQLITE_NOMEM, 0);
86660 }else if( pzErrMsg ){
86661 *pzErrMsg = 0;
86664 assert( (rc&db->errMask)==rc );
86665 sqlite3_mutex_leave(db->mutex);
86666 return rc;
86669 /************** End of legacy.c **********************************************/
86670 /************** Begin file loadext.c *****************************************/
86672 ** 2006 June 7
86674 ** The author disclaims copyright to this source code. In place of
86675 ** a legal notice, here is a blessing:
86677 ** May you do good and not evil.
86678 ** May you find forgiveness for yourself and forgive others.
86679 ** May you share freely, never taking more than you give.
86681 *************************************************************************
86682 ** This file contains code used to dynamically load extensions into
86683 ** the SQLite library.
86686 #ifndef SQLITE_CORE
86687 #define SQLITE_CORE 1 /* Disable the API redefinition in sqlite3ext.h */
86688 #endif
86689 /************** Include sqlite3ext.h in the middle of loadext.c **************/
86690 /************** Begin file sqlite3ext.h **************************************/
86692 ** 2006 June 7
86694 ** The author disclaims copyright to this source code. In place of
86695 ** a legal notice, here is a blessing:
86697 ** May you do good and not evil.
86698 ** May you find forgiveness for yourself and forgive others.
86699 ** May you share freely, never taking more than you give.
86701 *************************************************************************
86702 ** This header file defines the SQLite interface for use by
86703 ** shared libraries that want to be imported as extensions into
86704 ** an SQLite instance. Shared libraries that intend to be loaded
86705 ** as extensions by SQLite should #include this file instead of
86706 ** sqlite3.h.
86708 #ifndef _SQLITE3EXT_H_
86709 #define _SQLITE3EXT_H_
86711 typedef struct sqlite3_api_routines sqlite3_api_routines;
86714 ** The following structure holds pointers to all of the SQLite API
86715 ** routines.
86717 ** WARNING: In order to maintain backwards compatibility, add new
86718 ** interfaces to the end of this structure only. If you insert new
86719 ** interfaces in the middle of this structure, then older different
86720 ** versions of SQLite will not be able to load each others' shared
86721 ** libraries!
86723 struct sqlite3_api_routines {
86724 void * (*aggregate_context)(sqlite3_context*,int nBytes);
86725 int (*aggregate_count)(sqlite3_context*);
86726 int (*bind_blob)(sqlite3_stmt*,int,const void*,int n,void(*)(void*));
86727 int (*bind_double)(sqlite3_stmt*,int,double);
86728 int (*bind_int)(sqlite3_stmt*,int,int);
86729 int (*bind_int64)(sqlite3_stmt*,int,sqlite_int64);
86730 int (*bind_null)(sqlite3_stmt*,int);
86731 int (*bind_parameter_count)(sqlite3_stmt*);
86732 int (*bind_parameter_index)(sqlite3_stmt*,const char*zName);
86733 const char * (*bind_parameter_name)(sqlite3_stmt*,int);
86734 int (*bind_text)(sqlite3_stmt*,int,const char*,int n,void(*)(void*));
86735 int (*bind_text16)(sqlite3_stmt*,int,const void*,int,void(*)(void*));
86736 int (*bind_value)(sqlite3_stmt*,int,const sqlite3_value*);
86737 int (*busy_handler)(sqlite3*,int(*)(void*,int),void*);
86738 int (*busy_timeout)(sqlite3*,int ms);
86739 int (*changes)(sqlite3*);
86740 int (*close)(sqlite3*);
86741 int (*collation_needed)(sqlite3*,void*,void(*)(void*,sqlite3*,int eTextRep,const char*));
86742 int (*collation_needed16)(sqlite3*,void*,void(*)(void*,sqlite3*,int eTextRep,const void*));
86743 const void * (*column_blob)(sqlite3_stmt*,int iCol);
86744 int (*column_bytes)(sqlite3_stmt*,int iCol);
86745 int (*column_bytes16)(sqlite3_stmt*,int iCol);
86746 int (*column_count)(sqlite3_stmt*pStmt);
86747 const char * (*column_database_name)(sqlite3_stmt*,int);
86748 const void * (*column_database_name16)(sqlite3_stmt*,int);
86749 const char * (*column_decltype)(sqlite3_stmt*,int i);
86750 const void * (*column_decltype16)(sqlite3_stmt*,int);
86751 double (*column_double)(sqlite3_stmt*,int iCol);
86752 int (*column_int)(sqlite3_stmt*,int iCol);
86753 sqlite_int64 (*column_int64)(sqlite3_stmt*,int iCol);
86754 const char * (*column_name)(sqlite3_stmt*,int);
86755 const void * (*column_name16)(sqlite3_stmt*,int);
86756 const char * (*column_origin_name)(sqlite3_stmt*,int);
86757 const void * (*column_origin_name16)(sqlite3_stmt*,int);
86758 const char * (*column_table_name)(sqlite3_stmt*,int);
86759 const void * (*column_table_name16)(sqlite3_stmt*,int);
86760 const unsigned char * (*column_text)(sqlite3_stmt*,int iCol);
86761 const void * (*column_text16)(sqlite3_stmt*,int iCol);
86762 int (*column_type)(sqlite3_stmt*,int iCol);
86763 sqlite3_value* (*column_value)(sqlite3_stmt*,int iCol);
86764 void * (*commit_hook)(sqlite3*,int(*)(void*),void*);
86765 int (*complete)(const char*sql);
86766 int (*complete16)(const void*sql);
86767 int (*create_collation)(sqlite3*,const char*,int,void*,int(*)(void*,int,const void*,int,const void*));
86768 int (*create_collation16)(sqlite3*,const void*,int,void*,int(*)(void*,int,const void*,int,const void*));
86769 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*));
86770 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*));
86771 int (*create_module)(sqlite3*,const char*,const sqlite3_module*,void*);
86772 int (*data_count)(sqlite3_stmt*pStmt);
86773 sqlite3 * (*db_handle)(sqlite3_stmt*);
86774 int (*declare_vtab)(sqlite3*,const char*);
86775 int (*enable_shared_cache)(int);
86776 int (*errcode)(sqlite3*db);
86777 const char * (*errmsg)(sqlite3*);
86778 const void * (*errmsg16)(sqlite3*);
86779 int (*exec)(sqlite3*,const char*,sqlite3_callback,void*,char**);
86780 int (*expired)(sqlite3_stmt*);
86781 int (*finalize)(sqlite3_stmt*pStmt);
86782 void (*free)(void*);
86783 void (*free_table)(char**result);
86784 int (*get_autocommit)(sqlite3*);
86785 void * (*get_auxdata)(sqlite3_context*,int);
86786 int (*get_table)(sqlite3*,const char*,char***,int*,int*,char**);
86787 int (*global_recover)(void);
86788 void (*interruptx)(sqlite3*);
86789 sqlite_int64 (*last_insert_rowid)(sqlite3*);
86790 const char * (*libversion)(void);
86791 int (*libversion_number)(void);
86792 void *(*malloc)(int);
86793 char * (*mprintf)(const char*,...);
86794 int (*open)(const char*,sqlite3**);
86795 int (*open16)(const void*,sqlite3**);
86796 int (*prepare)(sqlite3*,const char*,int,sqlite3_stmt**,const char**);
86797 int (*prepare16)(sqlite3*,const void*,int,sqlite3_stmt**,const void**);
86798 void * (*profile)(sqlite3*,void(*)(void*,const char*,sqlite_uint64),void*);
86799 void (*progress_handler)(sqlite3*,int,int(*)(void*),void*);
86800 void *(*realloc)(void*,int);
86801 int (*reset)(sqlite3_stmt*pStmt);
86802 void (*result_blob)(sqlite3_context*,const void*,int,void(*)(void*));
86803 void (*result_double)(sqlite3_context*,double);
86804 void (*result_error)(sqlite3_context*,const char*,int);
86805 void (*result_error16)(sqlite3_context*,const void*,int);
86806 void (*result_int)(sqlite3_context*,int);
86807 void (*result_int64)(sqlite3_context*,sqlite_int64);
86808 void (*result_null)(sqlite3_context*);
86809 void (*result_text)(sqlite3_context*,const char*,int,void(*)(void*));
86810 void (*result_text16)(sqlite3_context*,const void*,int,void(*)(void*));
86811 void (*result_text16be)(sqlite3_context*,const void*,int,void(*)(void*));
86812 void (*result_text16le)(sqlite3_context*,const void*,int,void(*)(void*));
86813 void (*result_value)(sqlite3_context*,sqlite3_value*);
86814 void * (*rollback_hook)(sqlite3*,void(*)(void*),void*);
86815 int (*set_authorizer)(sqlite3*,int(*)(void*,int,const char*,const char*,const char*,const char*),void*);
86816 void (*set_auxdata)(sqlite3_context*,int,void*,void (*)(void*));
86817 char * (*snprintf)(int,char*,const char*,...);
86818 int (*step)(sqlite3_stmt*);
86819 int (*table_column_metadata)(sqlite3*,const char*,const char*,const char*,char const**,char const**,int*,int*,int*);
86820 void (*thread_cleanup)(void);
86821 int (*total_changes)(sqlite3*);
86822 void * (*trace)(sqlite3*,void(*xTrace)(void*,const char*),void*);
86823 int (*transfer_bindings)(sqlite3_stmt*,sqlite3_stmt*);
86824 void * (*update_hook)(sqlite3*,void(*)(void*,int ,char const*,char const*,sqlite_int64),void*);
86825 void * (*user_data)(sqlite3_context*);
86826 const void * (*value_blob)(sqlite3_value*);
86827 int (*value_bytes)(sqlite3_value*);
86828 int (*value_bytes16)(sqlite3_value*);
86829 double (*value_double)(sqlite3_value*);
86830 int (*value_int)(sqlite3_value*);
86831 sqlite_int64 (*value_int64)(sqlite3_value*);
86832 int (*value_numeric_type)(sqlite3_value*);
86833 const unsigned char * (*value_text)(sqlite3_value*);
86834 const void * (*value_text16)(sqlite3_value*);
86835 const void * (*value_text16be)(sqlite3_value*);
86836 const void * (*value_text16le)(sqlite3_value*);
86837 int (*value_type)(sqlite3_value*);
86838 char *(*vmprintf)(const char*,va_list);
86839 /* Added ??? */
86840 int (*overload_function)(sqlite3*, const char *zFuncName, int nArg);
86841 /* Added by 3.3.13 */
86842 int (*prepare_v2)(sqlite3*,const char*,int,sqlite3_stmt**,const char**);
86843 int (*prepare16_v2)(sqlite3*,const void*,int,sqlite3_stmt**,const void**);
86844 int (*clear_bindings)(sqlite3_stmt*);
86845 /* Added by 3.4.1 */
86846 int (*create_module_v2)(sqlite3*,const char*,const sqlite3_module*,void*,void (*xDestroy)(void *));
86847 /* Added by 3.5.0 */
86848 int (*bind_zeroblob)(sqlite3_stmt*,int,int);
86849 int (*blob_bytes)(sqlite3_blob*);
86850 int (*blob_close)(sqlite3_blob*);
86851 int (*blob_open)(sqlite3*,const char*,const char*,const char*,sqlite3_int64,int,sqlite3_blob**);
86852 int (*blob_read)(sqlite3_blob*,void*,int,int);
86853 int (*blob_write)(sqlite3_blob*,const void*,int,int);
86854 int (*create_collation_v2)(sqlite3*,const char*,int,void*,int(*)(void*,int,const void*,int,const void*),void(*)(void*));
86855 int (*file_control)(sqlite3*,const char*,int,void*);
86856 sqlite3_int64 (*memory_highwater)(int);
86857 sqlite3_int64 (*memory_used)(void);
86858 sqlite3_mutex *(*mutex_alloc)(int);
86859 void (*mutex_enter)(sqlite3_mutex*);
86860 void (*mutex_free)(sqlite3_mutex*);
86861 void (*mutex_leave)(sqlite3_mutex*);
86862 int (*mutex_try)(sqlite3_mutex*);
86863 int (*open_v2)(const char*,sqlite3**,int,const char*);
86864 int (*release_memory)(int);
86865 void (*result_error_nomem)(sqlite3_context*);
86866 void (*result_error_toobig)(sqlite3_context*);
86867 int (*sleep)(int);
86868 void (*soft_heap_limit)(int);
86869 sqlite3_vfs *(*vfs_find)(const char*);
86870 int (*vfs_register)(sqlite3_vfs*,int);
86871 int (*vfs_unregister)(sqlite3_vfs*);
86872 int (*xthreadsafe)(void);
86873 void (*result_zeroblob)(sqlite3_context*,int);
86874 void (*result_error_code)(sqlite3_context*,int);
86875 int (*test_control)(int, ...);
86876 void (*randomness)(int,void*);
86877 sqlite3 *(*context_db_handle)(sqlite3_context*);
86878 int (*extended_result_codes)(sqlite3*,int);
86879 int (*limit)(sqlite3*,int,int);
86880 sqlite3_stmt *(*next_stmt)(sqlite3*,sqlite3_stmt*);
86881 const char *(*sql)(sqlite3_stmt*);
86882 int (*status)(int,int*,int*,int);
86883 int (*backup_finish)(sqlite3_backup*);
86884 sqlite3_backup *(*backup_init)(sqlite3*,const char*,sqlite3*,const char*);
86885 int (*backup_pagecount)(sqlite3_backup*);
86886 int (*backup_remaining)(sqlite3_backup*);
86887 int (*backup_step)(sqlite3_backup*,int);
86888 const char *(*compileoption_get)(int);
86889 int (*compileoption_used)(const char*);
86890 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*));
86891 int (*db_config)(sqlite3*,int,...);
86892 sqlite3_mutex *(*db_mutex)(sqlite3*);
86893 int (*db_status)(sqlite3*,int,int*,int*,int);
86894 int (*extended_errcode)(sqlite3*);
86895 void (*log)(int,const char*,...);
86896 sqlite3_int64 (*soft_heap_limit64)(sqlite3_int64);
86897 const char *(*sourceid)(void);
86898 int (*stmt_status)(sqlite3_stmt*,int,int);
86899 int (*strnicmp)(const char*,const char*,int);
86900 int (*unlock_notify)(sqlite3*,void(*)(void**,int),void*);
86901 int (*wal_autocheckpoint)(sqlite3*,int);
86902 int (*wal_checkpoint)(sqlite3*,const char*);
86903 void *(*wal_hook)(sqlite3*,int(*)(void*,sqlite3*,const char*,int),void*);
86907 ** The following macros redefine the API routines so that they are
86908 ** redirected throught the global sqlite3_api structure.
86910 ** This header file is also used by the loadext.c source file
86911 ** (part of the main SQLite library - not an extension) so that
86912 ** it can get access to the sqlite3_api_routines structure
86913 ** definition. But the main library does not want to redefine
86914 ** the API. So the redefinition macros are only valid if the
86915 ** SQLITE_CORE macros is undefined.
86917 #ifndef SQLITE_CORE
86918 #define sqlite3_aggregate_context sqlite3_api->aggregate_context
86919 #ifndef SQLITE_OMIT_DEPRECATED
86920 #define sqlite3_aggregate_count sqlite3_api->aggregate_count
86921 #endif
86922 #define sqlite3_bind_blob sqlite3_api->bind_blob
86923 #define sqlite3_bind_double sqlite3_api->bind_double
86924 #define sqlite3_bind_int sqlite3_api->bind_int
86925 #define sqlite3_bind_int64 sqlite3_api->bind_int64
86926 #define sqlite3_bind_null sqlite3_api->bind_null
86927 #define sqlite3_bind_parameter_count sqlite3_api->bind_parameter_count
86928 #define sqlite3_bind_parameter_index sqlite3_api->bind_parameter_index
86929 #define sqlite3_bind_parameter_name sqlite3_api->bind_parameter_name
86930 #define sqlite3_bind_text sqlite3_api->bind_text
86931 #define sqlite3_bind_text16 sqlite3_api->bind_text16
86932 #define sqlite3_bind_value sqlite3_api->bind_value
86933 #define sqlite3_busy_handler sqlite3_api->busy_handler
86934 #define sqlite3_busy_timeout sqlite3_api->busy_timeout
86935 #define sqlite3_changes sqlite3_api->changes
86936 #define sqlite3_close sqlite3_api->close
86937 #define sqlite3_collation_needed sqlite3_api->collation_needed
86938 #define sqlite3_collation_needed16 sqlite3_api->collation_needed16
86939 #define sqlite3_column_blob sqlite3_api->column_blob
86940 #define sqlite3_column_bytes sqlite3_api->column_bytes
86941 #define sqlite3_column_bytes16 sqlite3_api->column_bytes16
86942 #define sqlite3_column_count sqlite3_api->column_count
86943 #define sqlite3_column_database_name sqlite3_api->column_database_name
86944 #define sqlite3_column_database_name16 sqlite3_api->column_database_name16
86945 #define sqlite3_column_decltype sqlite3_api->column_decltype
86946 #define sqlite3_column_decltype16 sqlite3_api->column_decltype16
86947 #define sqlite3_column_double sqlite3_api->column_double
86948 #define sqlite3_column_int sqlite3_api->column_int
86949 #define sqlite3_column_int64 sqlite3_api->column_int64
86950 #define sqlite3_column_name sqlite3_api->column_name
86951 #define sqlite3_column_name16 sqlite3_api->column_name16
86952 #define sqlite3_column_origin_name sqlite3_api->column_origin_name
86953 #define sqlite3_column_origin_name16 sqlite3_api->column_origin_name16
86954 #define sqlite3_column_table_name sqlite3_api->column_table_name
86955 #define sqlite3_column_table_name16 sqlite3_api->column_table_name16
86956 #define sqlite3_column_text sqlite3_api->column_text
86957 #define sqlite3_column_text16 sqlite3_api->column_text16
86958 #define sqlite3_column_type sqlite3_api->column_type
86959 #define sqlite3_column_value sqlite3_api->column_value
86960 #define sqlite3_commit_hook sqlite3_api->commit_hook
86961 #define sqlite3_complete sqlite3_api->complete
86962 #define sqlite3_complete16 sqlite3_api->complete16
86963 #define sqlite3_create_collation sqlite3_api->create_collation
86964 #define sqlite3_create_collation16 sqlite3_api->create_collation16
86965 #define sqlite3_create_function sqlite3_api->create_function
86966 #define sqlite3_create_function16 sqlite3_api->create_function16
86967 #define sqlite3_create_module sqlite3_api->create_module
86968 #define sqlite3_create_module_v2 sqlite3_api->create_module_v2
86969 #define sqlite3_data_count sqlite3_api->data_count
86970 #define sqlite3_db_handle sqlite3_api->db_handle
86971 #define sqlite3_declare_vtab sqlite3_api->declare_vtab
86972 #define sqlite3_enable_shared_cache sqlite3_api->enable_shared_cache
86973 #define sqlite3_errcode sqlite3_api->errcode
86974 #define sqlite3_errmsg sqlite3_api->errmsg
86975 #define sqlite3_errmsg16 sqlite3_api->errmsg16
86976 #define sqlite3_exec sqlite3_api->exec
86977 #ifndef SQLITE_OMIT_DEPRECATED
86978 #define sqlite3_expired sqlite3_api->expired
86979 #endif
86980 #define sqlite3_finalize sqlite3_api->finalize
86981 #define sqlite3_free sqlite3_api->free
86982 #define sqlite3_free_table sqlite3_api->free_table
86983 #define sqlite3_get_autocommit sqlite3_api->get_autocommit
86984 #define sqlite3_get_auxdata sqlite3_api->get_auxdata
86985 #define sqlite3_get_table sqlite3_api->get_table
86986 #ifndef SQLITE_OMIT_DEPRECATED
86987 #define sqlite3_global_recover sqlite3_api->global_recover
86988 #endif
86989 #define sqlite3_interrupt sqlite3_api->interruptx
86990 #define sqlite3_last_insert_rowid sqlite3_api->last_insert_rowid
86991 #define sqlite3_libversion sqlite3_api->libversion
86992 #define sqlite3_libversion_number sqlite3_api->libversion_number
86993 #define sqlite3_malloc sqlite3_api->malloc
86994 #define sqlite3_mprintf sqlite3_api->mprintf
86995 #define sqlite3_open sqlite3_api->open
86996 #define sqlite3_open16 sqlite3_api->open16
86997 #define sqlite3_prepare sqlite3_api->prepare
86998 #define sqlite3_prepare16 sqlite3_api->prepare16
86999 #define sqlite3_prepare_v2 sqlite3_api->prepare_v2
87000 #define sqlite3_prepare16_v2 sqlite3_api->prepare16_v2
87001 #define sqlite3_profile sqlite3_api->profile
87002 #define sqlite3_progress_handler sqlite3_api->progress_handler
87003 #define sqlite3_realloc sqlite3_api->realloc
87004 #define sqlite3_reset sqlite3_api->reset
87005 #define sqlite3_result_blob sqlite3_api->result_blob
87006 #define sqlite3_result_double sqlite3_api->result_double
87007 #define sqlite3_result_error sqlite3_api->result_error
87008 #define sqlite3_result_error16 sqlite3_api->result_error16
87009 #define sqlite3_result_int sqlite3_api->result_int
87010 #define sqlite3_result_int64 sqlite3_api->result_int64
87011 #define sqlite3_result_null sqlite3_api->result_null
87012 #define sqlite3_result_text sqlite3_api->result_text
87013 #define sqlite3_result_text16 sqlite3_api->result_text16
87014 #define sqlite3_result_text16be sqlite3_api->result_text16be
87015 #define sqlite3_result_text16le sqlite3_api->result_text16le
87016 #define sqlite3_result_value sqlite3_api->result_value
87017 #define sqlite3_rollback_hook sqlite3_api->rollback_hook
87018 #define sqlite3_set_authorizer sqlite3_api->set_authorizer
87019 #define sqlite3_set_auxdata sqlite3_api->set_auxdata
87020 #define sqlite3_snprintf sqlite3_api->snprintf
87021 #define sqlite3_step sqlite3_api->step
87022 #define sqlite3_table_column_metadata sqlite3_api->table_column_metadata
87023 #define sqlite3_thread_cleanup sqlite3_api->thread_cleanup
87024 #define sqlite3_total_changes sqlite3_api->total_changes
87025 #define sqlite3_trace sqlite3_api->trace
87026 #ifndef SQLITE_OMIT_DEPRECATED
87027 #define sqlite3_transfer_bindings sqlite3_api->transfer_bindings
87028 #endif
87029 #define sqlite3_update_hook sqlite3_api->update_hook
87030 #define sqlite3_user_data sqlite3_api->user_data
87031 #define sqlite3_value_blob sqlite3_api->value_blob
87032 #define sqlite3_value_bytes sqlite3_api->value_bytes
87033 #define sqlite3_value_bytes16 sqlite3_api->value_bytes16
87034 #define sqlite3_value_double sqlite3_api->value_double
87035 #define sqlite3_value_int sqlite3_api->value_int
87036 #define sqlite3_value_int64 sqlite3_api->value_int64
87037 #define sqlite3_value_numeric_type sqlite3_api->value_numeric_type
87038 #define sqlite3_value_text sqlite3_api->value_text
87039 #define sqlite3_value_text16 sqlite3_api->value_text16
87040 #define sqlite3_value_text16be sqlite3_api->value_text16be
87041 #define sqlite3_value_text16le sqlite3_api->value_text16le
87042 #define sqlite3_value_type sqlite3_api->value_type
87043 #define sqlite3_vmprintf sqlite3_api->vmprintf
87044 #define sqlite3_overload_function sqlite3_api->overload_function
87045 #define sqlite3_prepare_v2 sqlite3_api->prepare_v2
87046 #define sqlite3_prepare16_v2 sqlite3_api->prepare16_v2
87047 #define sqlite3_clear_bindings sqlite3_api->clear_bindings
87048 #define sqlite3_bind_zeroblob sqlite3_api->bind_zeroblob
87049 #define sqlite3_blob_bytes sqlite3_api->blob_bytes
87050 #define sqlite3_blob_close sqlite3_api->blob_close
87051 #define sqlite3_blob_open sqlite3_api->blob_open
87052 #define sqlite3_blob_read sqlite3_api->blob_read
87053 #define sqlite3_blob_write sqlite3_api->blob_write
87054 #define sqlite3_create_collation_v2 sqlite3_api->create_collation_v2
87055 #define sqlite3_file_control sqlite3_api->file_control
87056 #define sqlite3_memory_highwater sqlite3_api->memory_highwater
87057 #define sqlite3_memory_used sqlite3_api->memory_used
87058 #define sqlite3_mutex_alloc sqlite3_api->mutex_alloc
87059 #define sqlite3_mutex_enter sqlite3_api->mutex_enter
87060 #define sqlite3_mutex_free sqlite3_api->mutex_free
87061 #define sqlite3_mutex_leave sqlite3_api->mutex_leave
87062 #define sqlite3_mutex_try sqlite3_api->mutex_try
87063 #define sqlite3_open_v2 sqlite3_api->open_v2
87064 #define sqlite3_release_memory sqlite3_api->release_memory
87065 #define sqlite3_result_error_nomem sqlite3_api->result_error_nomem
87066 #define sqlite3_result_error_toobig sqlite3_api->result_error_toobig
87067 #define sqlite3_sleep sqlite3_api->sleep
87068 #define sqlite3_soft_heap_limit sqlite3_api->soft_heap_limit
87069 #define sqlite3_vfs_find sqlite3_api->vfs_find
87070 #define sqlite3_vfs_register sqlite3_api->vfs_register
87071 #define sqlite3_vfs_unregister sqlite3_api->vfs_unregister
87072 #define sqlite3_threadsafe sqlite3_api->xthreadsafe
87073 #define sqlite3_result_zeroblob sqlite3_api->result_zeroblob
87074 #define sqlite3_result_error_code sqlite3_api->result_error_code
87075 #define sqlite3_test_control sqlite3_api->test_control
87076 #define sqlite3_randomness sqlite3_api->randomness
87077 #define sqlite3_context_db_handle sqlite3_api->context_db_handle
87078 #define sqlite3_extended_result_codes sqlite3_api->extended_result_codes
87079 #define sqlite3_limit sqlite3_api->limit
87080 #define sqlite3_next_stmt sqlite3_api->next_stmt
87081 #define sqlite3_sql sqlite3_api->sql
87082 #define sqlite3_status sqlite3_api->status
87083 #define sqlite3_backup_finish sqlite3_api->backup_finish
87084 #define sqlite3_backup_init sqlite3_api->backup_init
87085 #define sqlite3_backup_pagecount sqlite3_api->backup_pagecount
87086 #define sqlite3_backup_remaining sqlite3_api->backup_remaining
87087 #define sqlite3_backup_step sqlite3_api->backup_step
87088 #define sqlite3_compileoption_get sqlite3_api->compileoption_get
87089 #define sqlite3_compileoption_used sqlite3_api->compileoption_used
87090 #define sqlite3_create_function_v2 sqlite3_api->create_function_v2
87091 #define sqlite3_db_config sqlite3_api->db_config
87092 #define sqlite3_db_mutex sqlite3_api->db_mutex
87093 #define sqlite3_db_status sqlite3_api->db_status
87094 #define sqlite3_extended_errcode sqlite3_api->extended_errcode
87095 #define sqlite3_log sqlite3_api->log
87096 #define sqlite3_soft_heap_limit64 sqlite3_api->soft_heap_limit64
87097 #define sqlite3_sourceid sqlite3_api->sourceid
87098 #define sqlite3_stmt_status sqlite3_api->stmt_status
87099 #define sqlite3_strnicmp sqlite3_api->strnicmp
87100 #define sqlite3_unlock_notify sqlite3_api->unlock_notify
87101 #define sqlite3_wal_autocheckpoint sqlite3_api->wal_autocheckpoint
87102 #define sqlite3_wal_checkpoint sqlite3_api->wal_checkpoint
87103 #define sqlite3_wal_hook sqlite3_api->wal_hook
87104 #endif /* SQLITE_CORE */
87106 #define SQLITE_EXTENSION_INIT1 const sqlite3_api_routines *sqlite3_api = 0;
87107 #define SQLITE_EXTENSION_INIT2(v) sqlite3_api = v;
87109 #endif /* _SQLITE3EXT_H_ */
87111 /************** End of sqlite3ext.h ******************************************/
87112 /************** Continuing where we left off in loadext.c ********************/
87114 #ifndef SQLITE_OMIT_LOAD_EXTENSION
87117 ** Some API routines are omitted when various features are
87118 ** excluded from a build of SQLite. Substitute a NULL pointer
87119 ** for any missing APIs.
87121 #ifndef SQLITE_ENABLE_COLUMN_METADATA
87122 # define sqlite3_column_database_name 0
87123 # define sqlite3_column_database_name16 0
87124 # define sqlite3_column_table_name 0
87125 # define sqlite3_column_table_name16 0
87126 # define sqlite3_column_origin_name 0
87127 # define sqlite3_column_origin_name16 0
87128 # define sqlite3_table_column_metadata 0
87129 #endif
87131 #ifdef SQLITE_OMIT_AUTHORIZATION
87132 # define sqlite3_set_authorizer 0
87133 #endif
87135 #ifdef SQLITE_OMIT_UTF16
87136 # define sqlite3_bind_text16 0
87137 # define sqlite3_collation_needed16 0
87138 # define sqlite3_column_decltype16 0
87139 # define sqlite3_column_name16 0
87140 # define sqlite3_column_text16 0
87141 # define sqlite3_complete16 0
87142 # define sqlite3_create_collation16 0
87143 # define sqlite3_create_function16 0
87144 # define sqlite3_errmsg16 0
87145 # define sqlite3_open16 0
87146 # define sqlite3_prepare16 0
87147 # define sqlite3_prepare16_v2 0
87148 # define sqlite3_result_error16 0
87149 # define sqlite3_result_text16 0
87150 # define sqlite3_result_text16be 0
87151 # define sqlite3_result_text16le 0
87152 # define sqlite3_value_text16 0
87153 # define sqlite3_value_text16be 0
87154 # define sqlite3_value_text16le 0
87155 # define sqlite3_column_database_name16 0
87156 # define sqlite3_column_table_name16 0
87157 # define sqlite3_column_origin_name16 0
87158 #endif
87160 #ifdef SQLITE_OMIT_COMPLETE
87161 # define sqlite3_complete 0
87162 # define sqlite3_complete16 0
87163 #endif
87165 #ifdef SQLITE_OMIT_DECLTYPE
87166 # define sqlite3_column_decltype16 0
87167 # define sqlite3_column_decltype 0
87168 #endif
87170 #ifdef SQLITE_OMIT_PROGRESS_CALLBACK
87171 # define sqlite3_progress_handler 0
87172 #endif
87174 #ifdef SQLITE_OMIT_VIRTUALTABLE
87175 # define sqlite3_create_module 0
87176 # define sqlite3_create_module_v2 0
87177 # define sqlite3_declare_vtab 0
87178 #endif
87180 #ifdef SQLITE_OMIT_SHARED_CACHE
87181 # define sqlite3_enable_shared_cache 0
87182 #endif
87184 #ifdef SQLITE_OMIT_TRACE
87185 # define sqlite3_profile 0
87186 # define sqlite3_trace 0
87187 #endif
87189 #ifdef SQLITE_OMIT_GET_TABLE
87190 # define sqlite3_free_table 0
87191 # define sqlite3_get_table 0
87192 #endif
87194 #ifdef SQLITE_OMIT_INCRBLOB
87195 #define sqlite3_bind_zeroblob 0
87196 #define sqlite3_blob_bytes 0
87197 #define sqlite3_blob_close 0
87198 #define sqlite3_blob_open 0
87199 #define sqlite3_blob_read 0
87200 #define sqlite3_blob_write 0
87201 #endif
87204 ** The following structure contains pointers to all SQLite API routines.
87205 ** A pointer to this structure is passed into extensions when they are
87206 ** loaded so that the extension can make calls back into the SQLite
87207 ** library.
87209 ** When adding new APIs, add them to the bottom of this structure
87210 ** in order to preserve backwards compatibility.
87212 ** Extensions that use newer APIs should first call the
87213 ** sqlite3_libversion_number() to make sure that the API they
87214 ** intend to use is supported by the library. Extensions should
87215 ** also check to make sure that the pointer to the function is
87216 ** not NULL before calling it.
87218 static const sqlite3_api_routines sqlite3Apis = {
87219 sqlite3_aggregate_context,
87220 #ifndef SQLITE_OMIT_DEPRECATED
87221 sqlite3_aggregate_count,
87222 #else
87224 #endif
87225 sqlite3_bind_blob,
87226 sqlite3_bind_double,
87227 sqlite3_bind_int,
87228 sqlite3_bind_int64,
87229 sqlite3_bind_null,
87230 sqlite3_bind_parameter_count,
87231 sqlite3_bind_parameter_index,
87232 sqlite3_bind_parameter_name,
87233 sqlite3_bind_text,
87234 sqlite3_bind_text16,
87235 sqlite3_bind_value,
87236 sqlite3_busy_handler,
87237 sqlite3_busy_timeout,
87238 sqlite3_changes,
87239 sqlite3_close,
87240 sqlite3_collation_needed,
87241 sqlite3_collation_needed16,
87242 sqlite3_column_blob,
87243 sqlite3_column_bytes,
87244 sqlite3_column_bytes16,
87245 sqlite3_column_count,
87246 sqlite3_column_database_name,
87247 sqlite3_column_database_name16,
87248 sqlite3_column_decltype,
87249 sqlite3_column_decltype16,
87250 sqlite3_column_double,
87251 sqlite3_column_int,
87252 sqlite3_column_int64,
87253 sqlite3_column_name,
87254 sqlite3_column_name16,
87255 sqlite3_column_origin_name,
87256 sqlite3_column_origin_name16,
87257 sqlite3_column_table_name,
87258 sqlite3_column_table_name16,
87259 sqlite3_column_text,
87260 sqlite3_column_text16,
87261 sqlite3_column_type,
87262 sqlite3_column_value,
87263 sqlite3_commit_hook,
87264 sqlite3_complete,
87265 sqlite3_complete16,
87266 sqlite3_create_collation,
87267 sqlite3_create_collation16,
87268 sqlite3_create_function,
87269 sqlite3_create_function16,
87270 sqlite3_create_module,
87271 sqlite3_data_count,
87272 sqlite3_db_handle,
87273 sqlite3_declare_vtab,
87274 sqlite3_enable_shared_cache,
87275 sqlite3_errcode,
87276 sqlite3_errmsg,
87277 sqlite3_errmsg16,
87278 sqlite3_exec,
87279 #ifndef SQLITE_OMIT_DEPRECATED
87280 sqlite3_expired,
87281 #else
87283 #endif
87284 sqlite3_finalize,
87285 sqlite3_free,
87286 sqlite3_free_table,
87287 sqlite3_get_autocommit,
87288 sqlite3_get_auxdata,
87289 sqlite3_get_table,
87290 0, /* Was sqlite3_global_recover(), but that function is deprecated */
87291 sqlite3_interrupt,
87292 sqlite3_last_insert_rowid,
87293 sqlite3_libversion,
87294 sqlite3_libversion_number,
87295 sqlite3_malloc,
87296 sqlite3_mprintf,
87297 sqlite3_open,
87298 sqlite3_open16,
87299 sqlite3_prepare,
87300 sqlite3_prepare16,
87301 sqlite3_profile,
87302 sqlite3_progress_handler,
87303 sqlite3_realloc,
87304 sqlite3_reset,
87305 sqlite3_result_blob,
87306 sqlite3_result_double,
87307 sqlite3_result_error,
87308 sqlite3_result_error16,
87309 sqlite3_result_int,
87310 sqlite3_result_int64,
87311 sqlite3_result_null,
87312 sqlite3_result_text,
87313 sqlite3_result_text16,
87314 sqlite3_result_text16be,
87315 sqlite3_result_text16le,
87316 sqlite3_result_value,
87317 sqlite3_rollback_hook,
87318 sqlite3_set_authorizer,
87319 sqlite3_set_auxdata,
87320 sqlite3_snprintf,
87321 sqlite3_step,
87322 sqlite3_table_column_metadata,
87323 #ifndef SQLITE_OMIT_DEPRECATED
87324 sqlite3_thread_cleanup,
87325 #else
87327 #endif
87328 sqlite3_total_changes,
87329 sqlite3_trace,
87330 #ifndef SQLITE_OMIT_DEPRECATED
87331 sqlite3_transfer_bindings,
87332 #else
87334 #endif
87335 sqlite3_update_hook,
87336 sqlite3_user_data,
87337 sqlite3_value_blob,
87338 sqlite3_value_bytes,
87339 sqlite3_value_bytes16,
87340 sqlite3_value_double,
87341 sqlite3_value_int,
87342 sqlite3_value_int64,
87343 sqlite3_value_numeric_type,
87344 sqlite3_value_text,
87345 sqlite3_value_text16,
87346 sqlite3_value_text16be,
87347 sqlite3_value_text16le,
87348 sqlite3_value_type,
87349 sqlite3_vmprintf,
87351 ** The original API set ends here. All extensions can call any
87352 ** of the APIs above provided that the pointer is not NULL. But
87353 ** before calling APIs that follow, extension should check the
87354 ** sqlite3_libversion_number() to make sure they are dealing with
87355 ** a library that is new enough to support that API.
87356 *************************************************************************
87358 sqlite3_overload_function,
87361 ** Added after 3.3.13
87363 sqlite3_prepare_v2,
87364 sqlite3_prepare16_v2,
87365 sqlite3_clear_bindings,
87368 ** Added for 3.4.1
87370 sqlite3_create_module_v2,
87373 ** Added for 3.5.0
87375 sqlite3_bind_zeroblob,
87376 sqlite3_blob_bytes,
87377 sqlite3_blob_close,
87378 sqlite3_blob_open,
87379 sqlite3_blob_read,
87380 sqlite3_blob_write,
87381 sqlite3_create_collation_v2,
87382 sqlite3_file_control,
87383 sqlite3_memory_highwater,
87384 sqlite3_memory_used,
87385 #ifdef SQLITE_MUTEX_OMIT
87391 #else
87392 sqlite3_mutex_alloc,
87393 sqlite3_mutex_enter,
87394 sqlite3_mutex_free,
87395 sqlite3_mutex_leave,
87396 sqlite3_mutex_try,
87397 #endif
87398 sqlite3_open_v2,
87399 sqlite3_release_memory,
87400 sqlite3_result_error_nomem,
87401 sqlite3_result_error_toobig,
87402 sqlite3_sleep,
87403 sqlite3_soft_heap_limit,
87404 sqlite3_vfs_find,
87405 sqlite3_vfs_register,
87406 sqlite3_vfs_unregister,
87409 ** Added for 3.5.8
87411 sqlite3_threadsafe,
87412 sqlite3_result_zeroblob,
87413 sqlite3_result_error_code,
87414 sqlite3_test_control,
87415 sqlite3_randomness,
87416 sqlite3_context_db_handle,
87419 ** Added for 3.6.0
87421 sqlite3_extended_result_codes,
87422 sqlite3_limit,
87423 sqlite3_next_stmt,
87424 sqlite3_sql,
87425 sqlite3_status,
87428 ** Added for 3.7.4
87430 sqlite3_backup_finish,
87431 sqlite3_backup_init,
87432 sqlite3_backup_pagecount,
87433 sqlite3_backup_remaining,
87434 sqlite3_backup_step,
87435 #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
87436 sqlite3_compileoption_get,
87437 sqlite3_compileoption_used,
87438 #else
87441 #endif
87442 sqlite3_create_function_v2,
87443 sqlite3_db_config,
87444 sqlite3_db_mutex,
87445 sqlite3_db_status,
87446 sqlite3_extended_errcode,
87447 sqlite3_log,
87448 sqlite3_soft_heap_limit64,
87449 sqlite3_sourceid,
87450 sqlite3_stmt_status,
87451 sqlite3_strnicmp,
87452 #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
87453 sqlite3_unlock_notify,
87454 #else
87456 #endif
87457 #ifndef SQLITE_OMIT_WAL
87458 sqlite3_wal_autocheckpoint,
87459 sqlite3_wal_checkpoint,
87460 sqlite3_wal_hook,
87461 #else
87465 #endif
87469 ** Attempt to load an SQLite extension library contained in the file
87470 ** zFile. The entry point is zProc. zProc may be 0 in which case a
87471 ** default entry point name (sqlite3_extension_init) is used. Use
87472 ** of the default name is recommended.
87474 ** Return SQLITE_OK on success and SQLITE_ERROR if something goes wrong.
87476 ** If an error occurs and pzErrMsg is not 0, then fill *pzErrMsg with
87477 ** error message text. The calling function should free this memory
87478 ** by calling sqlite3DbFree(db, ).
87480 static int sqlite3LoadExtension(
87481 sqlite3 *db, /* Load the extension into this database connection */
87482 const char *zFile, /* Name of the shared library containing extension */
87483 const char *zProc, /* Entry point. Use "sqlite3_extension_init" if 0 */
87484 char **pzErrMsg /* Put error message here if not 0 */
87486 sqlite3_vfs *pVfs = db->pVfs;
87487 void *handle;
87488 int (*xInit)(sqlite3*,char**,const sqlite3_api_routines*);
87489 char *zErrmsg = 0;
87490 void **aHandle;
87491 const int nMsg = 300;
87493 if( pzErrMsg ) *pzErrMsg = 0;
87495 /* Ticket #1863. To avoid a creating security problems for older
87496 ** applications that relink against newer versions of SQLite, the
87497 ** ability to run load_extension is turned off by default. One
87498 ** must call sqlite3_enable_load_extension() to turn on extension
87499 ** loading. Otherwise you get the following error.
87501 if( (db->flags & SQLITE_LoadExtension)==0 ){
87502 if( pzErrMsg ){
87503 *pzErrMsg = sqlite3_mprintf("not authorized");
87505 return SQLITE_ERROR;
87508 if( zProc==0 ){
87509 zProc = "sqlite3_extension_init";
87512 handle = sqlite3OsDlOpen(pVfs, zFile);
87513 if( handle==0 ){
87514 if( pzErrMsg ){
87515 *pzErrMsg = zErrmsg = sqlite3_malloc(nMsg);
87516 if( zErrmsg ){
87517 sqlite3_snprintf(nMsg, zErrmsg,
87518 "unable to open shared library [%s]", zFile);
87519 sqlite3OsDlError(pVfs, nMsg-1, zErrmsg);
87522 return SQLITE_ERROR;
87524 xInit = (int(*)(sqlite3*,char**,const sqlite3_api_routines*))
87525 sqlite3OsDlSym(pVfs, handle, zProc);
87526 if( xInit==0 ){
87527 if( pzErrMsg ){
87528 *pzErrMsg = zErrmsg = sqlite3_malloc(nMsg);
87529 if( zErrmsg ){
87530 sqlite3_snprintf(nMsg, zErrmsg,
87531 "no entry point [%s] in shared library [%s]", zProc,zFile);
87532 sqlite3OsDlError(pVfs, nMsg-1, zErrmsg);
87534 sqlite3OsDlClose(pVfs, handle);
87536 return SQLITE_ERROR;
87537 }else if( xInit(db, &zErrmsg, &sqlite3Apis) ){
87538 if( pzErrMsg ){
87539 *pzErrMsg = sqlite3_mprintf("error during initialization: %s", zErrmsg);
87541 sqlite3_free(zErrmsg);
87542 sqlite3OsDlClose(pVfs, handle);
87543 return SQLITE_ERROR;
87546 /* Append the new shared library handle to the db->aExtension array. */
87547 aHandle = sqlite3DbMallocZero(db, sizeof(handle)*(db->nExtension+1));
87548 if( aHandle==0 ){
87549 return SQLITE_NOMEM;
87551 if( db->nExtension>0 ){
87552 memcpy(aHandle, db->aExtension, sizeof(handle)*db->nExtension);
87554 sqlite3DbFree(db, db->aExtension);
87555 db->aExtension = aHandle;
87557 db->aExtension[db->nExtension++] = handle;
87558 return SQLITE_OK;
87560 SQLITE_API int sqlite3_load_extension(
87561 sqlite3 *db, /* Load the extension into this database connection */
87562 const char *zFile, /* Name of the shared library containing extension */
87563 const char *zProc, /* Entry point. Use "sqlite3_extension_init" if 0 */
87564 char **pzErrMsg /* Put error message here if not 0 */
87566 int rc;
87567 sqlite3_mutex_enter(db->mutex);
87568 rc = sqlite3LoadExtension(db, zFile, zProc, pzErrMsg);
87569 rc = sqlite3ApiExit(db, rc);
87570 sqlite3_mutex_leave(db->mutex);
87571 return rc;
87575 ** Call this routine when the database connection is closing in order
87576 ** to clean up loaded extensions
87578 SQLITE_PRIVATE void sqlite3CloseExtensions(sqlite3 *db){
87579 int i;
87580 assert( sqlite3_mutex_held(db->mutex) );
87581 for(i=0; i<db->nExtension; i++){
87582 sqlite3OsDlClose(db->pVfs, db->aExtension[i]);
87584 sqlite3DbFree(db, db->aExtension);
87588 ** Enable or disable extension loading. Extension loading is disabled by
87589 ** default so as not to open security holes in older applications.
87591 SQLITE_API int sqlite3_enable_load_extension(sqlite3 *db, int onoff){
87592 sqlite3_mutex_enter(db->mutex);
87593 if( onoff ){
87594 db->flags |= SQLITE_LoadExtension;
87595 }else{
87596 db->flags &= ~SQLITE_LoadExtension;
87598 sqlite3_mutex_leave(db->mutex);
87599 return SQLITE_OK;
87602 #endif /* SQLITE_OMIT_LOAD_EXTENSION */
87605 ** The auto-extension code added regardless of whether or not extension
87606 ** loading is supported. We need a dummy sqlite3Apis pointer for that
87607 ** code if regular extension loading is not available. This is that
87608 ** dummy pointer.
87610 #ifdef SQLITE_OMIT_LOAD_EXTENSION
87611 static const sqlite3_api_routines sqlite3Apis = { 0 };
87612 #endif
87616 ** The following object holds the list of automatically loaded
87617 ** extensions.
87619 ** This list is shared across threads. The SQLITE_MUTEX_STATIC_MASTER
87620 ** mutex must be held while accessing this list.
87622 typedef struct sqlite3AutoExtList sqlite3AutoExtList;
87623 static SQLITE_WSD struct sqlite3AutoExtList {
87624 int nExt; /* Number of entries in aExt[] */
87625 void (**aExt)(void); /* Pointers to the extension init functions */
87626 } sqlite3Autoext = { 0, 0 };
87628 /* The "wsdAutoext" macro will resolve to the autoextension
87629 ** state vector. If writable static data is unsupported on the target,
87630 ** we have to locate the state vector at run-time. In the more common
87631 ** case where writable static data is supported, wsdStat can refer directly
87632 ** to the "sqlite3Autoext" state vector declared above.
87634 #ifdef SQLITE_OMIT_WSD
87635 # define wsdAutoextInit \
87636 sqlite3AutoExtList *x = &GLOBAL(sqlite3AutoExtList,sqlite3Autoext)
87637 # define wsdAutoext x[0]
87638 #else
87639 # define wsdAutoextInit
87640 # define wsdAutoext sqlite3Autoext
87641 #endif
87645 ** Register a statically linked extension that is automatically
87646 ** loaded by every new database connection.
87648 SQLITE_API int sqlite3_auto_extension(void (*xInit)(void)){
87649 int rc = SQLITE_OK;
87650 #ifndef SQLITE_OMIT_AUTOINIT
87651 rc = sqlite3_initialize();
87652 if( rc ){
87653 return rc;
87654 }else
87655 #endif
87657 int i;
87658 #if SQLITE_THREADSAFE
87659 sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
87660 #endif
87661 wsdAutoextInit;
87662 sqlite3_mutex_enter(mutex);
87663 for(i=0; i<wsdAutoext.nExt; i++){
87664 if( wsdAutoext.aExt[i]==xInit ) break;
87666 if( i==wsdAutoext.nExt ){
87667 int nByte = (wsdAutoext.nExt+1)*sizeof(wsdAutoext.aExt[0]);
87668 void (**aNew)(void);
87669 aNew = sqlite3_realloc(wsdAutoext.aExt, nByte);
87670 if( aNew==0 ){
87671 rc = SQLITE_NOMEM;
87672 }else{
87673 wsdAutoext.aExt = aNew;
87674 wsdAutoext.aExt[wsdAutoext.nExt] = xInit;
87675 wsdAutoext.nExt++;
87678 sqlite3_mutex_leave(mutex);
87679 assert( (rc&0xff)==rc );
87680 return rc;
87685 ** Reset the automatic extension loading mechanism.
87687 SQLITE_API void sqlite3_reset_auto_extension(void){
87688 #ifndef SQLITE_OMIT_AUTOINIT
87689 if( sqlite3_initialize()==SQLITE_OK )
87690 #endif
87692 #if SQLITE_THREADSAFE
87693 sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
87694 #endif
87695 wsdAutoextInit;
87696 sqlite3_mutex_enter(mutex);
87697 sqlite3_free(wsdAutoext.aExt);
87698 wsdAutoext.aExt = 0;
87699 wsdAutoext.nExt = 0;
87700 sqlite3_mutex_leave(mutex);
87705 ** Load all automatic extensions.
87707 ** If anything goes wrong, set an error in the database connection.
87709 SQLITE_PRIVATE void sqlite3AutoLoadExtensions(sqlite3 *db){
87710 int i;
87711 int go = 1;
87712 int (*xInit)(sqlite3*,char**,const sqlite3_api_routines*);
87714 wsdAutoextInit;
87715 if( wsdAutoext.nExt==0 ){
87716 /* Common case: early out without every having to acquire a mutex */
87717 return;
87719 for(i=0; go; i++){
87720 char *zErrmsg;
87721 #if SQLITE_THREADSAFE
87722 sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
87723 #endif
87724 sqlite3_mutex_enter(mutex);
87725 if( i>=wsdAutoext.nExt ){
87726 xInit = 0;
87727 go = 0;
87728 }else{
87729 xInit = (int(*)(sqlite3*,char**,const sqlite3_api_routines*))
87730 wsdAutoext.aExt[i];
87732 sqlite3_mutex_leave(mutex);
87733 zErrmsg = 0;
87734 if( xInit && xInit(db, &zErrmsg, &sqlite3Apis) ){
87735 sqlite3Error(db, SQLITE_ERROR,
87736 "automatic extension loading failed: %s", zErrmsg);
87737 go = 0;
87739 sqlite3_free(zErrmsg);
87743 /************** End of loadext.c *********************************************/
87744 /************** Begin file pragma.c ******************************************/
87746 ** 2003 April 6
87748 ** The author disclaims copyright to this source code. In place of
87749 ** a legal notice, here is a blessing:
87751 ** May you do good and not evil.
87752 ** May you find forgiveness for yourself and forgive others.
87753 ** May you share freely, never taking more than you give.
87755 *************************************************************************
87756 ** This file contains code used to implement the PRAGMA command.
87759 /* Ignore this whole file if pragmas are disabled
87761 #if !defined(SQLITE_OMIT_PRAGMA)
87764 ** Interpret the given string as a safety level. Return 0 for OFF,
87765 ** 1 for ON or NORMAL and 2 for FULL. Return 1 for an empty or
87766 ** unrecognized string argument.
87768 ** Note that the values returned are one less that the values that
87769 ** should be passed into sqlite3BtreeSetSafetyLevel(). The is done
87770 ** to support legacy SQL code. The safety level used to be boolean
87771 ** and older scripts may have used numbers 0 for OFF and 1 for ON.
87773 static u8 getSafetyLevel(const char *z){
87774 /* 123456789 123456789 */
87775 static const char zText[] = "onoffalseyestruefull";
87776 static const u8 iOffset[] = {0, 1, 2, 4, 9, 12, 16};
87777 static const u8 iLength[] = {2, 2, 3, 5, 3, 4, 4};
87778 static const u8 iValue[] = {1, 0, 0, 0, 1, 1, 2};
87779 int i, n;
87780 if( sqlite3Isdigit(*z) ){
87781 return (u8)sqlite3Atoi(z);
87783 n = sqlite3Strlen30(z);
87784 for(i=0; i<ArraySize(iLength); i++){
87785 if( iLength[i]==n && sqlite3StrNICmp(&zText[iOffset[i]],z,n)==0 ){
87786 return iValue[i];
87789 return 1;
87793 ** Interpret the given string as a boolean value.
87795 static u8 getBoolean(const char *z){
87796 return getSafetyLevel(z)&1;
87800 ** Interpret the given string as a locking mode value.
87802 static int getLockingMode(const char *z){
87803 if( z ){
87804 if( 0==sqlite3StrICmp(z, "exclusive") ) return PAGER_LOCKINGMODE_EXCLUSIVE;
87805 if( 0==sqlite3StrICmp(z, "normal") ) return PAGER_LOCKINGMODE_NORMAL;
87807 return PAGER_LOCKINGMODE_QUERY;
87810 #ifndef SQLITE_OMIT_AUTOVACUUM
87812 ** Interpret the given string as an auto-vacuum mode value.
87814 ** The following strings, "none", "full" and "incremental" are
87815 ** acceptable, as are their numeric equivalents: 0, 1 and 2 respectively.
87817 static int getAutoVacuum(const char *z){
87818 int i;
87819 if( 0==sqlite3StrICmp(z, "none") ) return BTREE_AUTOVACUUM_NONE;
87820 if( 0==sqlite3StrICmp(z, "full") ) return BTREE_AUTOVACUUM_FULL;
87821 if( 0==sqlite3StrICmp(z, "incremental") ) return BTREE_AUTOVACUUM_INCR;
87822 i = sqlite3Atoi(z);
87823 return (u8)((i>=0&&i<=2)?i:0);
87825 #endif /* ifndef SQLITE_OMIT_AUTOVACUUM */
87827 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
87829 ** Interpret the given string as a temp db location. Return 1 for file
87830 ** backed temporary databases, 2 for the Red-Black tree in memory database
87831 ** and 0 to use the compile-time default.
87833 static int getTempStore(const char *z){
87834 if( z[0]>='0' && z[0]<='2' ){
87835 return z[0] - '0';
87836 }else if( sqlite3StrICmp(z, "file")==0 ){
87837 return 1;
87838 }else if( sqlite3StrICmp(z, "memory")==0 ){
87839 return 2;
87840 }else{
87841 return 0;
87844 #endif /* SQLITE_PAGER_PRAGMAS */
87846 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
87848 ** Invalidate temp storage, either when the temp storage is changed
87849 ** from default, or when 'file' and the temp_store_directory has changed
87851 static int invalidateTempStorage(Parse *pParse){
87852 sqlite3 *db = pParse->db;
87853 if( db->aDb[1].pBt!=0 ){
87854 if( !db->autoCommit || sqlite3BtreeIsInReadTrans(db->aDb[1].pBt) ){
87855 sqlite3ErrorMsg(pParse, "temporary storage cannot be changed "
87856 "from within a transaction");
87857 return SQLITE_ERROR;
87859 sqlite3BtreeClose(db->aDb[1].pBt);
87860 db->aDb[1].pBt = 0;
87861 sqlite3ResetInternalSchema(db, -1);
87863 return SQLITE_OK;
87865 #endif /* SQLITE_PAGER_PRAGMAS */
87867 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
87869 ** If the TEMP database is open, close it and mark the database schema
87870 ** as needing reloading. This must be done when using the SQLITE_TEMP_STORE
87871 ** or DEFAULT_TEMP_STORE pragmas.
87873 static int changeTempStorage(Parse *pParse, const char *zStorageType){
87874 int ts = getTempStore(zStorageType);
87875 sqlite3 *db = pParse->db;
87876 if( db->temp_store==ts ) return SQLITE_OK;
87877 if( invalidateTempStorage( pParse ) != SQLITE_OK ){
87878 return SQLITE_ERROR;
87880 db->temp_store = (u8)ts;
87881 return SQLITE_OK;
87883 #endif /* SQLITE_PAGER_PRAGMAS */
87886 ** Generate code to return a single integer value.
87888 static void returnSingleInt(Parse *pParse, const char *zLabel, i64 value){
87889 Vdbe *v = sqlite3GetVdbe(pParse);
87890 int mem = ++pParse->nMem;
87891 i64 *pI64 = sqlite3DbMallocRaw(pParse->db, sizeof(value));
87892 if( pI64 ){
87893 memcpy(pI64, &value, sizeof(value));
87895 sqlite3VdbeAddOp4(v, OP_Int64, 0, mem, 0, (char*)pI64, P4_INT64);
87896 sqlite3VdbeSetNumCols(v, 1);
87897 sqlite3VdbeSetColName(v, 0, COLNAME_NAME, zLabel, SQLITE_STATIC);
87898 sqlite3VdbeAddOp2(v, OP_ResultRow, mem, 1);
87901 #ifndef SQLITE_OMIT_FLAG_PRAGMAS
87903 ** Check to see if zRight and zLeft refer to a pragma that queries
87904 ** or changes one of the flags in db->flags. Return 1 if so and 0 if not.
87905 ** Also, implement the pragma.
87907 static int flagPragma(Parse *pParse, const char *zLeft, const char *zRight){
87908 static const struct sPragmaType {
87909 const char *zName; /* Name of the pragma */
87910 int mask; /* Mask for the db->flags value */
87911 } aPragma[] = {
87912 { "full_column_names", SQLITE_FullColNames },
87913 { "short_column_names", SQLITE_ShortColNames },
87914 { "count_changes", SQLITE_CountRows },
87915 { "empty_result_callbacks", SQLITE_NullCallback },
87916 { "legacy_file_format", SQLITE_LegacyFileFmt },
87917 { "fullfsync", SQLITE_FullFSync },
87918 { "checkpoint_fullfsync", SQLITE_CkptFullFSync },
87919 { "reverse_unordered_selects", SQLITE_ReverseOrder },
87920 #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
87921 { "automatic_index", SQLITE_AutoIndex },
87922 #endif
87923 #ifdef SQLITE_DEBUG
87924 { "sql_trace", SQLITE_SqlTrace },
87925 { "vdbe_listing", SQLITE_VdbeListing },
87926 { "vdbe_trace", SQLITE_VdbeTrace },
87927 #endif
87928 #ifndef SQLITE_OMIT_CHECK
87929 { "ignore_check_constraints", SQLITE_IgnoreChecks },
87930 #endif
87931 /* The following is VERY experimental */
87932 { "writable_schema", SQLITE_WriteSchema|SQLITE_RecoveryMode },
87933 { "omit_readlock", SQLITE_NoReadlock },
87935 /* TODO: Maybe it shouldn't be possible to change the ReadUncommitted
87936 ** flag if there are any active statements. */
87937 { "read_uncommitted", SQLITE_ReadUncommitted },
87938 { "recursive_triggers", SQLITE_RecTriggers },
87940 /* This flag may only be set if both foreign-key and trigger support
87941 ** are present in the build. */
87942 #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
87943 { "foreign_keys", SQLITE_ForeignKeys },
87944 #endif
87946 int i;
87947 const struct sPragmaType *p;
87948 for(i=0, p=aPragma; i<ArraySize(aPragma); i++, p++){
87949 if( sqlite3StrICmp(zLeft, p->zName)==0 ){
87950 sqlite3 *db = pParse->db;
87951 Vdbe *v;
87952 v = sqlite3GetVdbe(pParse);
87953 assert( v!=0 ); /* Already allocated by sqlite3Pragma() */
87954 if( ALWAYS(v) ){
87955 if( zRight==0 ){
87956 returnSingleInt(pParse, p->zName, (db->flags & p->mask)!=0 );
87957 }else{
87958 int mask = p->mask; /* Mask of bits to set or clear. */
87959 if( db->autoCommit==0 ){
87960 /* Foreign key support may not be enabled or disabled while not
87961 ** in auto-commit mode. */
87962 mask &= ~(SQLITE_ForeignKeys);
87965 if( getBoolean(zRight) ){
87966 db->flags |= mask;
87967 }else{
87968 db->flags &= ~mask;
87971 /* Many of the flag-pragmas modify the code generated by the SQL
87972 ** compiler (eg. count_changes). So add an opcode to expire all
87973 ** compiled SQL statements after modifying a pragma value.
87975 sqlite3VdbeAddOp2(v, OP_Expire, 0, 0);
87979 return 1;
87982 return 0;
87984 #endif /* SQLITE_OMIT_FLAG_PRAGMAS */
87987 ** Return a human-readable name for a constraint resolution action.
87989 #ifndef SQLITE_OMIT_FOREIGN_KEY
87990 static const char *actionName(u8 action){
87991 const char *zName;
87992 switch( action ){
87993 case OE_SetNull: zName = "SET NULL"; break;
87994 case OE_SetDflt: zName = "SET DEFAULT"; break;
87995 case OE_Cascade: zName = "CASCADE"; break;
87996 case OE_Restrict: zName = "RESTRICT"; break;
87997 default: zName = "NO ACTION";
87998 assert( action==OE_None ); break;
88000 return zName;
88002 #endif
88006 ** Parameter eMode must be one of the PAGER_JOURNALMODE_XXX constants
88007 ** defined in pager.h. This function returns the associated lowercase
88008 ** journal-mode name.
88010 SQLITE_PRIVATE const char *sqlite3JournalModename(int eMode){
88011 static char * const azModeName[] = {
88012 "delete", "persist", "off", "truncate", "memory"
88013 #ifndef SQLITE_OMIT_WAL
88014 , "wal"
88015 #endif
88017 assert( PAGER_JOURNALMODE_DELETE==0 );
88018 assert( PAGER_JOURNALMODE_PERSIST==1 );
88019 assert( PAGER_JOURNALMODE_OFF==2 );
88020 assert( PAGER_JOURNALMODE_TRUNCATE==3 );
88021 assert( PAGER_JOURNALMODE_MEMORY==4 );
88022 assert( PAGER_JOURNALMODE_WAL==5 );
88023 assert( eMode>=0 && eMode<=ArraySize(azModeName) );
88025 if( eMode==ArraySize(azModeName) ) return 0;
88026 return azModeName[eMode];
88030 ** Process a pragma statement.
88032 ** Pragmas are of this form:
88034 ** PRAGMA [database.]id [= value]
88036 ** The identifier might also be a string. The value is a string, and
88037 ** identifier, or a number. If minusFlag is true, then the value is
88038 ** a number that was preceded by a minus sign.
88040 ** If the left side is "database.id" then pId1 is the database name
88041 ** and pId2 is the id. If the left side is just "id" then pId1 is the
88042 ** id and pId2 is any empty string.
88044 SQLITE_PRIVATE void sqlite3Pragma(
88045 Parse *pParse,
88046 Token *pId1, /* First part of [database.]id field */
88047 Token *pId2, /* Second part of [database.]id field, or NULL */
88048 Token *pValue, /* Token for <value>, or NULL */
88049 int minusFlag /* True if a '-' sign preceded <value> */
88051 char *zLeft = 0; /* Nul-terminated UTF-8 string <id> */
88052 char *zRight = 0; /* Nul-terminated UTF-8 string <value>, or NULL */
88053 const char *zDb = 0; /* The database name */
88054 Token *pId; /* Pointer to <id> token */
88055 int iDb; /* Database index for <database> */
88056 sqlite3 *db = pParse->db;
88057 Db *pDb;
88058 Vdbe *v = pParse->pVdbe = sqlite3VdbeCreate(db);
88059 if( v==0 ) return;
88060 sqlite3VdbeRunOnlyOnce(v);
88061 pParse->nMem = 2;
88063 /* Interpret the [database.] part of the pragma statement. iDb is the
88064 ** index of the database this pragma is being applied to in db.aDb[]. */
88065 iDb = sqlite3TwoPartName(pParse, pId1, pId2, &pId);
88066 if( iDb<0 ) return;
88067 pDb = &db->aDb[iDb];
88069 /* If the temp database has been explicitly named as part of the
88070 ** pragma, make sure it is open.
88072 if( iDb==1 && sqlite3OpenTempDatabase(pParse) ){
88073 return;
88076 zLeft = sqlite3NameFromToken(db, pId);
88077 if( !zLeft ) return;
88078 if( minusFlag ){
88079 zRight = sqlite3MPrintf(db, "-%T", pValue);
88080 }else{
88081 zRight = sqlite3NameFromToken(db, pValue);
88084 assert( pId2 );
88085 zDb = pId2->n>0 ? pDb->zName : 0;
88086 if( sqlite3AuthCheck(pParse, SQLITE_PRAGMA, zLeft, zRight, zDb) ){
88087 goto pragma_out;
88090 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
88092 ** PRAGMA [database.]default_cache_size
88093 ** PRAGMA [database.]default_cache_size=N
88095 ** The first form reports the current persistent setting for the
88096 ** page cache size. The value returned is the maximum number of
88097 ** pages in the page cache. The second form sets both the current
88098 ** page cache size value and the persistent page cache size value
88099 ** stored in the database file.
88101 ** Older versions of SQLite would set the default cache size to a
88102 ** negative number to indicate synchronous=OFF. These days, synchronous
88103 ** is always on by default regardless of the sign of the default cache
88104 ** size. But continue to take the absolute value of the default cache
88105 ** size of historical compatibility.
88107 if( sqlite3StrICmp(zLeft,"default_cache_size")==0 ){
88108 static const VdbeOpList getCacheSize[] = {
88109 { OP_Transaction, 0, 0, 0}, /* 0 */
88110 { OP_ReadCookie, 0, 1, BTREE_DEFAULT_CACHE_SIZE}, /* 1 */
88111 { OP_IfPos, 1, 7, 0},
88112 { OP_Integer, 0, 2, 0},
88113 { OP_Subtract, 1, 2, 1},
88114 { OP_IfPos, 1, 7, 0},
88115 { OP_Integer, 0, 1, 0}, /* 6 */
88116 { OP_ResultRow, 1, 1, 0},
88118 int addr;
88119 if( sqlite3ReadSchema(pParse) ) goto pragma_out;
88120 sqlite3VdbeUsesBtree(v, iDb);
88121 if( !zRight ){
88122 sqlite3VdbeSetNumCols(v, 1);
88123 sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "cache_size", SQLITE_STATIC);
88124 pParse->nMem += 2;
88125 addr = sqlite3VdbeAddOpList(v, ArraySize(getCacheSize), getCacheSize);
88126 sqlite3VdbeChangeP1(v, addr, iDb);
88127 sqlite3VdbeChangeP1(v, addr+1, iDb);
88128 sqlite3VdbeChangeP1(v, addr+6, SQLITE_DEFAULT_CACHE_SIZE);
88129 }else{
88130 int size = sqlite3AbsInt32(sqlite3Atoi(zRight));
88131 sqlite3BeginWriteOperation(pParse, 0, iDb);
88132 sqlite3VdbeAddOp2(v, OP_Integer, size, 1);
88133 sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_DEFAULT_CACHE_SIZE, 1);
88134 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
88135 pDb->pSchema->cache_size = size;
88136 sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
88138 }else
88141 ** PRAGMA [database.]page_size
88142 ** PRAGMA [database.]page_size=N
88144 ** The first form reports the current setting for the
88145 ** database page size in bytes. The second form sets the
88146 ** database page size value. The value can only be set if
88147 ** the database has not yet been created.
88149 if( sqlite3StrICmp(zLeft,"page_size")==0 ){
88150 Btree *pBt = pDb->pBt;
88151 assert( pBt!=0 );
88152 if( !zRight ){
88153 int size = ALWAYS(pBt) ? sqlite3BtreeGetPageSize(pBt) : 0;
88154 returnSingleInt(pParse, "page_size", size);
88155 }else{
88156 /* Malloc may fail when setting the page-size, as there is an internal
88157 ** buffer that the pager module resizes using sqlite3_realloc().
88159 db->nextPagesize = sqlite3Atoi(zRight);
88160 if( SQLITE_NOMEM==sqlite3BtreeSetPageSize(pBt, db->nextPagesize, -1, 0) ){
88161 db->mallocFailed = 1;
88164 }else
88167 ** PRAGMA [database.]secure_delete
88168 ** PRAGMA [database.]secure_delete=ON/OFF
88170 ** The first form reports the current setting for the
88171 ** secure_delete flag. The second form changes the secure_delete
88172 ** flag setting and reports thenew value.
88174 if( sqlite3StrICmp(zLeft,"secure_delete")==0 ){
88175 Btree *pBt = pDb->pBt;
88176 int b = -1;
88177 assert( pBt!=0 );
88178 if( zRight ){
88179 b = getBoolean(zRight);
88181 if( pId2->n==0 && b>=0 ){
88182 int ii;
88183 for(ii=0; ii<db->nDb; ii++){
88184 sqlite3BtreeSecureDelete(db->aDb[ii].pBt, b);
88187 b = sqlite3BtreeSecureDelete(pBt, b);
88188 returnSingleInt(pParse, "secure_delete", b);
88189 }else
88192 ** PRAGMA [database.]max_page_count
88193 ** PRAGMA [database.]max_page_count=N
88195 ** The first form reports the current setting for the
88196 ** maximum number of pages in the database file. The
88197 ** second form attempts to change this setting. Both
88198 ** forms return the current setting.
88200 ** PRAGMA [database.]page_count
88202 ** Return the number of pages in the specified database.
88204 if( sqlite3StrICmp(zLeft,"page_count")==0
88205 || sqlite3StrICmp(zLeft,"max_page_count")==0
88207 int iReg;
88208 if( sqlite3ReadSchema(pParse) ) goto pragma_out;
88209 sqlite3CodeVerifySchema(pParse, iDb);
88210 iReg = ++pParse->nMem;
88211 if( zLeft[0]=='p' ){
88212 sqlite3VdbeAddOp2(v, OP_Pagecount, iDb, iReg);
88213 }else{
88214 sqlite3VdbeAddOp3(v, OP_MaxPgcnt, iDb, iReg, sqlite3Atoi(zRight));
88216 sqlite3VdbeAddOp2(v, OP_ResultRow, iReg, 1);
88217 sqlite3VdbeSetNumCols(v, 1);
88218 sqlite3VdbeSetColName(v, 0, COLNAME_NAME, zLeft, SQLITE_TRANSIENT);
88219 }else
88222 ** PRAGMA [database.]locking_mode
88223 ** PRAGMA [database.]locking_mode = (normal|exclusive)
88225 if( sqlite3StrICmp(zLeft,"locking_mode")==0 ){
88226 const char *zRet = "normal";
88227 int eMode = getLockingMode(zRight);
88229 if( pId2->n==0 && eMode==PAGER_LOCKINGMODE_QUERY ){
88230 /* Simple "PRAGMA locking_mode;" statement. This is a query for
88231 ** the current default locking mode (which may be different to
88232 ** the locking-mode of the main database).
88234 eMode = db->dfltLockMode;
88235 }else{
88236 Pager *pPager;
88237 if( pId2->n==0 ){
88238 /* This indicates that no database name was specified as part
88239 ** of the PRAGMA command. In this case the locking-mode must be
88240 ** set on all attached databases, as well as the main db file.
88242 ** Also, the sqlite3.dfltLockMode variable is set so that
88243 ** any subsequently attached databases also use the specified
88244 ** locking mode.
88246 int ii;
88247 assert(pDb==&db->aDb[0]);
88248 for(ii=2; ii<db->nDb; ii++){
88249 pPager = sqlite3BtreePager(db->aDb[ii].pBt);
88250 sqlite3PagerLockingMode(pPager, eMode);
88252 db->dfltLockMode = (u8)eMode;
88254 pPager = sqlite3BtreePager(pDb->pBt);
88255 eMode = sqlite3PagerLockingMode(pPager, eMode);
88258 assert(eMode==PAGER_LOCKINGMODE_NORMAL||eMode==PAGER_LOCKINGMODE_EXCLUSIVE);
88259 if( eMode==PAGER_LOCKINGMODE_EXCLUSIVE ){
88260 zRet = "exclusive";
88262 sqlite3VdbeSetNumCols(v, 1);
88263 sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "locking_mode", SQLITE_STATIC);
88264 sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, zRet, 0);
88265 sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
88266 }else
88269 ** PRAGMA [database.]journal_mode
88270 ** PRAGMA [database.]journal_mode =
88271 ** (delete|persist|off|truncate|memory|wal|off)
88273 if( sqlite3StrICmp(zLeft,"journal_mode")==0 ){
88274 int eMode; /* One of the PAGER_JOURNALMODE_XXX symbols */
88275 int ii; /* Loop counter */
88277 /* Force the schema to be loaded on all databases. This cases all
88278 ** database files to be opened and the journal_modes set. */
88279 if( sqlite3ReadSchema(pParse) ){
88280 goto pragma_out;
88283 sqlite3VdbeSetNumCols(v, 1);
88284 sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "journal_mode", SQLITE_STATIC);
88286 if( zRight==0 ){
88287 /* If there is no "=MODE" part of the pragma, do a query for the
88288 ** current mode */
88289 eMode = PAGER_JOURNALMODE_QUERY;
88290 }else{
88291 const char *zMode;
88292 int n = sqlite3Strlen30(zRight);
88293 for(eMode=0; (zMode = sqlite3JournalModename(eMode))!=0; eMode++){
88294 if( sqlite3StrNICmp(zRight, zMode, n)==0 ) break;
88296 if( !zMode ){
88297 /* If the "=MODE" part does not match any known journal mode,
88298 ** then do a query */
88299 eMode = PAGER_JOURNALMODE_QUERY;
88302 if( eMode==PAGER_JOURNALMODE_QUERY && pId2->n==0 ){
88303 /* Convert "PRAGMA journal_mode" into "PRAGMA main.journal_mode" */
88304 iDb = 0;
88305 pId2->n = 1;
88307 for(ii=db->nDb-1; ii>=0; ii--){
88308 if( db->aDb[ii].pBt && (ii==iDb || pId2->n==0) ){
88309 sqlite3VdbeUsesBtree(v, ii);
88310 sqlite3VdbeAddOp3(v, OP_JournalMode, ii, 1, eMode);
88313 sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
88314 }else
88317 ** PRAGMA [database.]journal_size_limit
88318 ** PRAGMA [database.]journal_size_limit=N
88320 ** Get or set the size limit on rollback journal files.
88322 if( sqlite3StrICmp(zLeft,"journal_size_limit")==0 ){
88323 Pager *pPager = sqlite3BtreePager(pDb->pBt);
88324 i64 iLimit = -2;
88325 if( zRight ){
88326 sqlite3Atoi64(zRight, &iLimit, 1000000, SQLITE_UTF8);
88327 if( iLimit<-1 ) iLimit = -1;
88329 iLimit = sqlite3PagerJournalSizeLimit(pPager, iLimit);
88330 returnSingleInt(pParse, "journal_size_limit", iLimit);
88331 }else
88333 #endif /* SQLITE_OMIT_PAGER_PRAGMAS */
88336 ** PRAGMA [database.]auto_vacuum
88337 ** PRAGMA [database.]auto_vacuum=N
88339 ** Get or set the value of the database 'auto-vacuum' parameter.
88340 ** The value is one of: 0 NONE 1 FULL 2 INCREMENTAL
88342 #ifndef SQLITE_OMIT_AUTOVACUUM
88343 if( sqlite3StrICmp(zLeft,"auto_vacuum")==0 ){
88344 Btree *pBt = pDb->pBt;
88345 assert( pBt!=0 );
88346 if( sqlite3ReadSchema(pParse) ){
88347 goto pragma_out;
88349 if( !zRight ){
88350 int auto_vacuum;
88351 if( ALWAYS(pBt) ){
88352 auto_vacuum = sqlite3BtreeGetAutoVacuum(pBt);
88353 }else{
88354 auto_vacuum = SQLITE_DEFAULT_AUTOVACUUM;
88356 returnSingleInt(pParse, "auto_vacuum", auto_vacuum);
88357 }else{
88358 int eAuto = getAutoVacuum(zRight);
88359 assert( eAuto>=0 && eAuto<=2 );
88360 db->nextAutovac = (u8)eAuto;
88361 if( ALWAYS(eAuto>=0) ){
88362 /* Call SetAutoVacuum() to set initialize the internal auto and
88363 ** incr-vacuum flags. This is required in case this connection
88364 ** creates the database file. It is important that it is created
88365 ** as an auto-vacuum capable db.
88367 int rc = sqlite3BtreeSetAutoVacuum(pBt, eAuto);
88368 if( rc==SQLITE_OK && (eAuto==1 || eAuto==2) ){
88369 /* When setting the auto_vacuum mode to either "full" or
88370 ** "incremental", write the value of meta[6] in the database
88371 ** file. Before writing to meta[6], check that meta[3] indicates
88372 ** that this really is an auto-vacuum capable database.
88374 static const VdbeOpList setMeta6[] = {
88375 { OP_Transaction, 0, 1, 0}, /* 0 */
88376 { OP_ReadCookie, 0, 1, BTREE_LARGEST_ROOT_PAGE},
88377 { OP_If, 1, 0, 0}, /* 2 */
88378 { OP_Halt, SQLITE_OK, OE_Abort, 0}, /* 3 */
88379 { OP_Integer, 0, 1, 0}, /* 4 */
88380 { OP_SetCookie, 0, BTREE_INCR_VACUUM, 1}, /* 5 */
88382 int iAddr;
88383 iAddr = sqlite3VdbeAddOpList(v, ArraySize(setMeta6), setMeta6);
88384 sqlite3VdbeChangeP1(v, iAddr, iDb);
88385 sqlite3VdbeChangeP1(v, iAddr+1, iDb);
88386 sqlite3VdbeChangeP2(v, iAddr+2, iAddr+4);
88387 sqlite3VdbeChangeP1(v, iAddr+4, eAuto-1);
88388 sqlite3VdbeChangeP1(v, iAddr+5, iDb);
88389 sqlite3VdbeUsesBtree(v, iDb);
88393 }else
88394 #endif
88397 ** PRAGMA [database.]incremental_vacuum(N)
88399 ** Do N steps of incremental vacuuming on a database.
88401 #ifndef SQLITE_OMIT_AUTOVACUUM
88402 if( sqlite3StrICmp(zLeft,"incremental_vacuum")==0 ){
88403 int iLimit, addr;
88404 if( sqlite3ReadSchema(pParse) ){
88405 goto pragma_out;
88407 if( zRight==0 || !sqlite3GetInt32(zRight, &iLimit) || iLimit<=0 ){
88408 iLimit = 0x7fffffff;
88410 sqlite3BeginWriteOperation(pParse, 0, iDb);
88411 sqlite3VdbeAddOp2(v, OP_Integer, iLimit, 1);
88412 addr = sqlite3VdbeAddOp1(v, OP_IncrVacuum, iDb);
88413 sqlite3VdbeAddOp1(v, OP_ResultRow, 1);
88414 sqlite3VdbeAddOp2(v, OP_AddImm, 1, -1);
88415 sqlite3VdbeAddOp2(v, OP_IfPos, 1, addr);
88416 sqlite3VdbeJumpHere(v, addr);
88417 }else
88418 #endif
88420 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
88422 ** PRAGMA [database.]cache_size
88423 ** PRAGMA [database.]cache_size=N
88425 ** The first form reports the current local setting for the
88426 ** page cache size. The local setting can be different from
88427 ** the persistent cache size value that is stored in the database
88428 ** file itself. The value returned is the maximum number of
88429 ** pages in the page cache. The second form sets the local
88430 ** page cache size value. It does not change the persistent
88431 ** cache size stored on the disk so the cache size will revert
88432 ** to its default value when the database is closed and reopened.
88433 ** N should be a positive integer.
88435 if( sqlite3StrICmp(zLeft,"cache_size")==0 ){
88436 if( sqlite3ReadSchema(pParse) ) goto pragma_out;
88437 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
88438 if( !zRight ){
88439 returnSingleInt(pParse, "cache_size", pDb->pSchema->cache_size);
88440 }else{
88441 int size = sqlite3AbsInt32(sqlite3Atoi(zRight));
88442 pDb->pSchema->cache_size = size;
88443 sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
88445 }else
88448 ** PRAGMA temp_store
88449 ** PRAGMA temp_store = "default"|"memory"|"file"
88451 ** Return or set the local value of the temp_store flag. Changing
88452 ** the local value does not make changes to the disk file and the default
88453 ** value will be restored the next time the database is opened.
88455 ** Note that it is possible for the library compile-time options to
88456 ** override this setting
88458 if( sqlite3StrICmp(zLeft, "temp_store")==0 ){
88459 if( !zRight ){
88460 returnSingleInt(pParse, "temp_store", db->temp_store);
88461 }else{
88462 changeTempStorage(pParse, zRight);
88464 }else
88467 ** PRAGMA temp_store_directory
88468 ** PRAGMA temp_store_directory = ""|"directory_name"
88470 ** Return or set the local value of the temp_store_directory flag. Changing
88471 ** the value sets a specific directory to be used for temporary files.
88472 ** Setting to a null string reverts to the default temporary directory search.
88473 ** If temporary directory is changed, then invalidateTempStorage.
88476 if( sqlite3StrICmp(zLeft, "temp_store_directory")==0 ){
88477 if( !zRight ){
88478 if( sqlite3_temp_directory ){
88479 sqlite3VdbeSetNumCols(v, 1);
88480 sqlite3VdbeSetColName(v, 0, COLNAME_NAME,
88481 "temp_store_directory", SQLITE_STATIC);
88482 sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, sqlite3_temp_directory, 0);
88483 sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
88485 }else{
88486 #ifndef SQLITE_OMIT_WSD
88487 if( zRight[0] ){
88488 int rc;
88489 int res;
88490 rc = sqlite3OsAccess(db->pVfs, zRight, SQLITE_ACCESS_READWRITE, &res);
88491 if( rc!=SQLITE_OK || res==0 ){
88492 sqlite3ErrorMsg(pParse, "not a writable directory");
88493 goto pragma_out;
88496 if( SQLITE_TEMP_STORE==0
88497 || (SQLITE_TEMP_STORE==1 && db->temp_store<=1)
88498 || (SQLITE_TEMP_STORE==2 && db->temp_store==1)
88500 invalidateTempStorage(pParse);
88502 sqlite3_free(sqlite3_temp_directory);
88503 if( zRight[0] ){
88504 sqlite3_temp_directory = sqlite3_mprintf("%s", zRight);
88505 }else{
88506 sqlite3_temp_directory = 0;
88508 #endif /* SQLITE_OMIT_WSD */
88510 }else
88512 #if !defined(SQLITE_ENABLE_LOCKING_STYLE)
88513 # if defined(__APPLE__)
88514 # define SQLITE_ENABLE_LOCKING_STYLE 1
88515 # else
88516 # define SQLITE_ENABLE_LOCKING_STYLE 0
88517 # endif
88518 #endif
88519 #if SQLITE_ENABLE_LOCKING_STYLE
88521 ** PRAGMA [database.]lock_proxy_file
88522 ** PRAGMA [database.]lock_proxy_file = ":auto:"|"lock_file_path"
88524 ** Return or set the value of the lock_proxy_file flag. Changing
88525 ** the value sets a specific file to be used for database access locks.
88528 if( sqlite3StrICmp(zLeft, "lock_proxy_file")==0 ){
88529 if( !zRight ){
88530 Pager *pPager = sqlite3BtreePager(pDb->pBt);
88531 char *proxy_file_path = NULL;
88532 sqlite3_file *pFile = sqlite3PagerFile(pPager);
88533 sqlite3OsFileControl(pFile, SQLITE_GET_LOCKPROXYFILE,
88534 &proxy_file_path);
88536 if( proxy_file_path ){
88537 sqlite3VdbeSetNumCols(v, 1);
88538 sqlite3VdbeSetColName(v, 0, COLNAME_NAME,
88539 "lock_proxy_file", SQLITE_STATIC);
88540 sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, proxy_file_path, 0);
88541 sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
88543 }else{
88544 Pager *pPager = sqlite3BtreePager(pDb->pBt);
88545 sqlite3_file *pFile = sqlite3PagerFile(pPager);
88546 int res;
88547 if( zRight[0] ){
88548 res=sqlite3OsFileControl(pFile, SQLITE_SET_LOCKPROXYFILE,
88549 zRight);
88550 } else {
88551 res=sqlite3OsFileControl(pFile, SQLITE_SET_LOCKPROXYFILE,
88552 NULL);
88554 if( res!=SQLITE_OK ){
88555 sqlite3ErrorMsg(pParse, "failed to set lock proxy file");
88556 goto pragma_out;
88559 }else
88560 #endif /* SQLITE_ENABLE_LOCKING_STYLE */
88563 ** PRAGMA [database.]synchronous
88564 ** PRAGMA [database.]synchronous=OFF|ON|NORMAL|FULL
88566 ** Return or set the local value of the synchronous flag. Changing
88567 ** the local value does not make changes to the disk file and the
88568 ** default value will be restored the next time the database is
88569 ** opened.
88571 if( sqlite3StrICmp(zLeft,"synchronous")==0 ){
88572 if( sqlite3ReadSchema(pParse) ) goto pragma_out;
88573 if( !zRight ){
88574 returnSingleInt(pParse, "synchronous", pDb->safety_level-1);
88575 }else{
88576 if( !db->autoCommit ){
88577 sqlite3ErrorMsg(pParse,
88578 "Safety level may not be changed inside a transaction");
88579 }else{
88580 pDb->safety_level = getSafetyLevel(zRight)+1;
88583 }else
88584 #endif /* SQLITE_OMIT_PAGER_PRAGMAS */
88586 #ifndef SQLITE_OMIT_FLAG_PRAGMAS
88587 if( flagPragma(pParse, zLeft, zRight) ){
88588 /* The flagPragma() subroutine also generates any necessary code
88589 ** there is nothing more to do here */
88590 }else
88591 #endif /* SQLITE_OMIT_FLAG_PRAGMAS */
88593 #ifndef SQLITE_OMIT_SCHEMA_PRAGMAS
88595 ** PRAGMA table_info(<table>)
88597 ** Return a single row for each column of the named table. The columns of
88598 ** the returned data set are:
88600 ** cid: Column id (numbered from left to right, starting at 0)
88601 ** name: Column name
88602 ** type: Column declaration type.
88603 ** notnull: True if 'NOT NULL' is part of column declaration
88604 ** dflt_value: The default value for the column, if any.
88606 if( sqlite3StrICmp(zLeft, "table_info")==0 && zRight ){
88607 Table *pTab;
88608 if( sqlite3ReadSchema(pParse) ) goto pragma_out;
88609 pTab = sqlite3FindTable(db, zRight, zDb);
88610 if( pTab ){
88611 int i;
88612 int nHidden = 0;
88613 Column *pCol;
88614 sqlite3VdbeSetNumCols(v, 6);
88615 pParse->nMem = 6;
88616 sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "cid", SQLITE_STATIC);
88617 sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "name", SQLITE_STATIC);
88618 sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "type", SQLITE_STATIC);
88619 sqlite3VdbeSetColName(v, 3, COLNAME_NAME, "notnull", SQLITE_STATIC);
88620 sqlite3VdbeSetColName(v, 4, COLNAME_NAME, "dflt_value", SQLITE_STATIC);
88621 sqlite3VdbeSetColName(v, 5, COLNAME_NAME, "pk", SQLITE_STATIC);
88622 sqlite3ViewGetColumnNames(pParse, pTab);
88623 for(i=0, pCol=pTab->aCol; i<pTab->nCol; i++, pCol++){
88624 if( IsHiddenColumn(pCol) ){
88625 nHidden++;
88626 continue;
88628 sqlite3VdbeAddOp2(v, OP_Integer, i-nHidden, 1);
88629 sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, pCol->zName, 0);
88630 sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0,
88631 pCol->zType ? pCol->zType : "", 0);
88632 sqlite3VdbeAddOp2(v, OP_Integer, (pCol->notNull ? 1 : 0), 4);
88633 if( pCol->zDflt ){
88634 sqlite3VdbeAddOp4(v, OP_String8, 0, 5, 0, (char*)pCol->zDflt, 0);
88635 }else{
88636 sqlite3VdbeAddOp2(v, OP_Null, 0, 5);
88638 sqlite3VdbeAddOp2(v, OP_Integer, pCol->isPrimKey, 6);
88639 sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 6);
88642 }else
88644 if( sqlite3StrICmp(zLeft, "index_info")==0 && zRight ){
88645 Index *pIdx;
88646 Table *pTab;
88647 if( sqlite3ReadSchema(pParse) ) goto pragma_out;
88648 pIdx = sqlite3FindIndex(db, zRight, zDb);
88649 if( pIdx ){
88650 int i;
88651 pTab = pIdx->pTable;
88652 sqlite3VdbeSetNumCols(v, 3);
88653 pParse->nMem = 3;
88654 sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "seqno", SQLITE_STATIC);
88655 sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "cid", SQLITE_STATIC);
88656 sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "name", SQLITE_STATIC);
88657 for(i=0; i<pIdx->nColumn; i++){
88658 int cnum = pIdx->aiColumn[i];
88659 sqlite3VdbeAddOp2(v, OP_Integer, i, 1);
88660 sqlite3VdbeAddOp2(v, OP_Integer, cnum, 2);
88661 assert( pTab->nCol>cnum );
88662 sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, pTab->aCol[cnum].zName, 0);
88663 sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3);
88666 }else
88668 if( sqlite3StrICmp(zLeft, "index_list")==0 && zRight ){
88669 Index *pIdx;
88670 Table *pTab;
88671 if( sqlite3ReadSchema(pParse) ) goto pragma_out;
88672 pTab = sqlite3FindTable(db, zRight, zDb);
88673 if( pTab ){
88674 v = sqlite3GetVdbe(pParse);
88675 pIdx = pTab->pIndex;
88676 if( pIdx ){
88677 int i = 0;
88678 sqlite3VdbeSetNumCols(v, 3);
88679 pParse->nMem = 3;
88680 sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "seq", SQLITE_STATIC);
88681 sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "name", SQLITE_STATIC);
88682 sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "unique", SQLITE_STATIC);
88683 while(pIdx){
88684 sqlite3VdbeAddOp2(v, OP_Integer, i, 1);
88685 sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, pIdx->zName, 0);
88686 sqlite3VdbeAddOp2(v, OP_Integer, pIdx->onError!=OE_None, 3);
88687 sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3);
88688 ++i;
88689 pIdx = pIdx->pNext;
88693 }else
88695 if( sqlite3StrICmp(zLeft, "database_list")==0 ){
88696 int i;
88697 if( sqlite3ReadSchema(pParse) ) goto pragma_out;
88698 sqlite3VdbeSetNumCols(v, 3);
88699 pParse->nMem = 3;
88700 sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "seq", SQLITE_STATIC);
88701 sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "name", SQLITE_STATIC);
88702 sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "file", SQLITE_STATIC);
88703 for(i=0; i<db->nDb; i++){
88704 if( db->aDb[i].pBt==0 ) continue;
88705 assert( db->aDb[i].zName!=0 );
88706 sqlite3VdbeAddOp2(v, OP_Integer, i, 1);
88707 sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, db->aDb[i].zName, 0);
88708 sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0,
88709 sqlite3BtreeGetFilename(db->aDb[i].pBt), 0);
88710 sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3);
88712 }else
88714 if( sqlite3StrICmp(zLeft, "collation_list")==0 ){
88715 int i = 0;
88716 HashElem *p;
88717 sqlite3VdbeSetNumCols(v, 2);
88718 pParse->nMem = 2;
88719 sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "seq", SQLITE_STATIC);
88720 sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "name", SQLITE_STATIC);
88721 for(p=sqliteHashFirst(&db->aCollSeq); p; p=sqliteHashNext(p)){
88722 CollSeq *pColl = (CollSeq *)sqliteHashData(p);
88723 sqlite3VdbeAddOp2(v, OP_Integer, i++, 1);
88724 sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, pColl->zName, 0);
88725 sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 2);
88727 }else
88728 #endif /* SQLITE_OMIT_SCHEMA_PRAGMAS */
88730 #ifndef SQLITE_OMIT_FOREIGN_KEY
88731 if( sqlite3StrICmp(zLeft, "foreign_key_list")==0 && zRight ){
88732 FKey *pFK;
88733 Table *pTab;
88734 if( sqlite3ReadSchema(pParse) ) goto pragma_out;
88735 pTab = sqlite3FindTable(db, zRight, zDb);
88736 if( pTab ){
88737 v = sqlite3GetVdbe(pParse);
88738 pFK = pTab->pFKey;
88739 if( pFK ){
88740 int i = 0;
88741 sqlite3VdbeSetNumCols(v, 8);
88742 pParse->nMem = 8;
88743 sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "id", SQLITE_STATIC);
88744 sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "seq", SQLITE_STATIC);
88745 sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "table", SQLITE_STATIC);
88746 sqlite3VdbeSetColName(v, 3, COLNAME_NAME, "from", SQLITE_STATIC);
88747 sqlite3VdbeSetColName(v, 4, COLNAME_NAME, "to", SQLITE_STATIC);
88748 sqlite3VdbeSetColName(v, 5, COLNAME_NAME, "on_update", SQLITE_STATIC);
88749 sqlite3VdbeSetColName(v, 6, COLNAME_NAME, "on_delete", SQLITE_STATIC);
88750 sqlite3VdbeSetColName(v, 7, COLNAME_NAME, "match", SQLITE_STATIC);
88751 while(pFK){
88752 int j;
88753 for(j=0; j<pFK->nCol; j++){
88754 char *zCol = pFK->aCol[j].zCol;
88755 char *zOnDelete = (char *)actionName(pFK->aAction[0]);
88756 char *zOnUpdate = (char *)actionName(pFK->aAction[1]);
88757 sqlite3VdbeAddOp2(v, OP_Integer, i, 1);
88758 sqlite3VdbeAddOp2(v, OP_Integer, j, 2);
88759 sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, pFK->zTo, 0);
88760 sqlite3VdbeAddOp4(v, OP_String8, 0, 4, 0,
88761 pTab->aCol[pFK->aCol[j].iFrom].zName, 0);
88762 sqlite3VdbeAddOp4(v, zCol ? OP_String8 : OP_Null, 0, 5, 0, zCol, 0);
88763 sqlite3VdbeAddOp4(v, OP_String8, 0, 6, 0, zOnUpdate, 0);
88764 sqlite3VdbeAddOp4(v, OP_String8, 0, 7, 0, zOnDelete, 0);
88765 sqlite3VdbeAddOp4(v, OP_String8, 0, 8, 0, "NONE", 0);
88766 sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 8);
88768 ++i;
88769 pFK = pFK->pNextFrom;
88773 }else
88774 #endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
88776 #ifndef NDEBUG
88777 if( sqlite3StrICmp(zLeft, "parser_trace")==0 ){
88778 if( zRight ){
88779 if( getBoolean(zRight) ){
88780 sqlite3ParserTrace(stderr, "parser: ");
88781 }else{
88782 sqlite3ParserTrace(0, 0);
88785 }else
88786 #endif
88788 /* Reinstall the LIKE and GLOB functions. The variant of LIKE
88789 ** used will be case sensitive or not depending on the RHS.
88791 if( sqlite3StrICmp(zLeft, "case_sensitive_like")==0 ){
88792 if( zRight ){
88793 sqlite3RegisterLikeFunctions(db, getBoolean(zRight));
88795 }else
88797 #ifndef SQLITE_INTEGRITY_CHECK_ERROR_MAX
88798 # define SQLITE_INTEGRITY_CHECK_ERROR_MAX 100
88799 #endif
88801 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
88802 /* Pragma "quick_check" is an experimental reduced version of
88803 ** integrity_check designed to detect most database corruption
88804 ** without most of the overhead of a full integrity-check.
88806 if( sqlite3StrICmp(zLeft, "integrity_check")==0
88807 || sqlite3StrICmp(zLeft, "quick_check")==0
88809 int i, j, addr, mxErr;
88811 /* Code that appears at the end of the integrity check. If no error
88812 ** messages have been generated, output OK. Otherwise output the
88813 ** error message
88815 static const VdbeOpList endCode[] = {
88816 { OP_AddImm, 1, 0, 0}, /* 0 */
88817 { OP_IfNeg, 1, 0, 0}, /* 1 */
88818 { OP_String8, 0, 3, 0}, /* 2 */
88819 { OP_ResultRow, 3, 1, 0},
88822 int isQuick = (zLeft[0]=='q');
88824 /* Initialize the VDBE program */
88825 if( sqlite3ReadSchema(pParse) ) goto pragma_out;
88826 pParse->nMem = 6;
88827 sqlite3VdbeSetNumCols(v, 1);
88828 sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "integrity_check", SQLITE_STATIC);
88830 /* Set the maximum error count */
88831 mxErr = SQLITE_INTEGRITY_CHECK_ERROR_MAX;
88832 if( zRight ){
88833 sqlite3GetInt32(zRight, &mxErr);
88834 if( mxErr<=0 ){
88835 mxErr = SQLITE_INTEGRITY_CHECK_ERROR_MAX;
88838 sqlite3VdbeAddOp2(v, OP_Integer, mxErr, 1); /* reg[1] holds errors left */
88840 /* Do an integrity check on each database file */
88841 for(i=0; i<db->nDb; i++){
88842 HashElem *x;
88843 Hash *pTbls;
88844 int cnt = 0;
88846 if( OMIT_TEMPDB && i==1 ) continue;
88848 sqlite3CodeVerifySchema(pParse, i);
88849 addr = sqlite3VdbeAddOp1(v, OP_IfPos, 1); /* Halt if out of errors */
88850 sqlite3VdbeAddOp2(v, OP_Halt, 0, 0);
88851 sqlite3VdbeJumpHere(v, addr);
88853 /* Do an integrity check of the B-Tree
88855 ** Begin by filling registers 2, 3, ... with the root pages numbers
88856 ** for all tables and indices in the database.
88858 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
88859 pTbls = &db->aDb[i].pSchema->tblHash;
88860 for(x=sqliteHashFirst(pTbls); x; x=sqliteHashNext(x)){
88861 Table *pTab = sqliteHashData(x);
88862 Index *pIdx;
88863 sqlite3VdbeAddOp2(v, OP_Integer, pTab->tnum, 2+cnt);
88864 cnt++;
88865 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
88866 sqlite3VdbeAddOp2(v, OP_Integer, pIdx->tnum, 2+cnt);
88867 cnt++;
88871 /* Make sure sufficient number of registers have been allocated */
88872 if( pParse->nMem < cnt+4 ){
88873 pParse->nMem = cnt+4;
88876 /* Do the b-tree integrity checks */
88877 sqlite3VdbeAddOp3(v, OP_IntegrityCk, 2, cnt, 1);
88878 sqlite3VdbeChangeP5(v, (u8)i);
88879 addr = sqlite3VdbeAddOp1(v, OP_IsNull, 2);
88880 sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0,
88881 sqlite3MPrintf(db, "*** in database %s ***\n", db->aDb[i].zName),
88882 P4_DYNAMIC);
88883 sqlite3VdbeAddOp3(v, OP_Move, 2, 4, 1);
88884 sqlite3VdbeAddOp3(v, OP_Concat, 4, 3, 2);
88885 sqlite3VdbeAddOp2(v, OP_ResultRow, 2, 1);
88886 sqlite3VdbeJumpHere(v, addr);
88888 /* Make sure all the indices are constructed correctly.
88890 for(x=sqliteHashFirst(pTbls); x && !isQuick; x=sqliteHashNext(x)){
88891 Table *pTab = sqliteHashData(x);
88892 Index *pIdx;
88893 int loopTop;
88895 if( pTab->pIndex==0 ) continue;
88896 addr = sqlite3VdbeAddOp1(v, OP_IfPos, 1); /* Stop if out of errors */
88897 sqlite3VdbeAddOp2(v, OP_Halt, 0, 0);
88898 sqlite3VdbeJumpHere(v, addr);
88899 sqlite3OpenTableAndIndices(pParse, pTab, 1, OP_OpenRead);
88900 sqlite3VdbeAddOp2(v, OP_Integer, 0, 2); /* reg(2) will count entries */
88901 loopTop = sqlite3VdbeAddOp2(v, OP_Rewind, 1, 0);
88902 sqlite3VdbeAddOp2(v, OP_AddImm, 2, 1); /* increment entry count */
88903 for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
88904 int jmp2;
88905 int r1;
88906 static const VdbeOpList idxErr[] = {
88907 { OP_AddImm, 1, -1, 0},
88908 { OP_String8, 0, 3, 0}, /* 1 */
88909 { OP_Rowid, 1, 4, 0},
88910 { OP_String8, 0, 5, 0}, /* 3 */
88911 { OP_String8, 0, 6, 0}, /* 4 */
88912 { OP_Concat, 4, 3, 3},
88913 { OP_Concat, 5, 3, 3},
88914 { OP_Concat, 6, 3, 3},
88915 { OP_ResultRow, 3, 1, 0},
88916 { OP_IfPos, 1, 0, 0}, /* 9 */
88917 { OP_Halt, 0, 0, 0},
88919 r1 = sqlite3GenerateIndexKey(pParse, pIdx, 1, 3, 0);
88920 jmp2 = sqlite3VdbeAddOp4Int(v, OP_Found, j+2, 0, r1, pIdx->nColumn+1);
88921 addr = sqlite3VdbeAddOpList(v, ArraySize(idxErr), idxErr);
88922 sqlite3VdbeChangeP4(v, addr+1, "rowid ", P4_STATIC);
88923 sqlite3VdbeChangeP4(v, addr+3, " missing from index ", P4_STATIC);
88924 sqlite3VdbeChangeP4(v, addr+4, pIdx->zName, P4_TRANSIENT);
88925 sqlite3VdbeJumpHere(v, addr+9);
88926 sqlite3VdbeJumpHere(v, jmp2);
88928 sqlite3VdbeAddOp2(v, OP_Next, 1, loopTop+1);
88929 sqlite3VdbeJumpHere(v, loopTop);
88930 for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
88931 static const VdbeOpList cntIdx[] = {
88932 { OP_Integer, 0, 3, 0},
88933 { OP_Rewind, 0, 0, 0}, /* 1 */
88934 { OP_AddImm, 3, 1, 0},
88935 { OP_Next, 0, 0, 0}, /* 3 */
88936 { OP_Eq, 2, 0, 3}, /* 4 */
88937 { OP_AddImm, 1, -1, 0},
88938 { OP_String8, 0, 2, 0}, /* 6 */
88939 { OP_String8, 0, 3, 0}, /* 7 */
88940 { OP_Concat, 3, 2, 2},
88941 { OP_ResultRow, 2, 1, 0},
88943 addr = sqlite3VdbeAddOp1(v, OP_IfPos, 1);
88944 sqlite3VdbeAddOp2(v, OP_Halt, 0, 0);
88945 sqlite3VdbeJumpHere(v, addr);
88946 addr = sqlite3VdbeAddOpList(v, ArraySize(cntIdx), cntIdx);
88947 sqlite3VdbeChangeP1(v, addr+1, j+2);
88948 sqlite3VdbeChangeP2(v, addr+1, addr+4);
88949 sqlite3VdbeChangeP1(v, addr+3, j+2);
88950 sqlite3VdbeChangeP2(v, addr+3, addr+2);
88951 sqlite3VdbeJumpHere(v, addr+4);
88952 sqlite3VdbeChangeP4(v, addr+6,
88953 "wrong # of entries in index ", P4_STATIC);
88954 sqlite3VdbeChangeP4(v, addr+7, pIdx->zName, P4_TRANSIENT);
88958 addr = sqlite3VdbeAddOpList(v, ArraySize(endCode), endCode);
88959 sqlite3VdbeChangeP2(v, addr, -mxErr);
88960 sqlite3VdbeJumpHere(v, addr+1);
88961 sqlite3VdbeChangeP4(v, addr+2, "ok", P4_STATIC);
88962 }else
88963 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
88965 #ifndef SQLITE_OMIT_UTF16
88967 ** PRAGMA encoding
88968 ** PRAGMA encoding = "utf-8"|"utf-16"|"utf-16le"|"utf-16be"
88970 ** In its first form, this pragma returns the encoding of the main
88971 ** database. If the database is not initialized, it is initialized now.
88973 ** The second form of this pragma is a no-op if the main database file
88974 ** has not already been initialized. In this case it sets the default
88975 ** encoding that will be used for the main database file if a new file
88976 ** is created. If an existing main database file is opened, then the
88977 ** default text encoding for the existing database is used.
88979 ** In all cases new databases created using the ATTACH command are
88980 ** created to use the same default text encoding as the main database. If
88981 ** the main database has not been initialized and/or created when ATTACH
88982 ** is executed, this is done before the ATTACH operation.
88984 ** In the second form this pragma sets the text encoding to be used in
88985 ** new database files created using this database handle. It is only
88986 ** useful if invoked immediately after the main database i
88988 if( sqlite3StrICmp(zLeft, "encoding")==0 ){
88989 static const struct EncName {
88990 char *zName;
88991 u8 enc;
88992 } encnames[] = {
88993 { "UTF8", SQLITE_UTF8 },
88994 { "UTF-8", SQLITE_UTF8 }, /* Must be element [1] */
88995 { "UTF-16le", SQLITE_UTF16LE }, /* Must be element [2] */
88996 { "UTF-16be", SQLITE_UTF16BE }, /* Must be element [3] */
88997 { "UTF16le", SQLITE_UTF16LE },
88998 { "UTF16be", SQLITE_UTF16BE },
88999 { "UTF-16", 0 }, /* SQLITE_UTF16NATIVE */
89000 { "UTF16", 0 }, /* SQLITE_UTF16NATIVE */
89001 { 0, 0 }
89003 const struct EncName *pEnc;
89004 if( !zRight ){ /* "PRAGMA encoding" */
89005 if( sqlite3ReadSchema(pParse) ) goto pragma_out;
89006 sqlite3VdbeSetNumCols(v, 1);
89007 sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "encoding", SQLITE_STATIC);
89008 sqlite3VdbeAddOp2(v, OP_String8, 0, 1);
89009 assert( encnames[SQLITE_UTF8].enc==SQLITE_UTF8 );
89010 assert( encnames[SQLITE_UTF16LE].enc==SQLITE_UTF16LE );
89011 assert( encnames[SQLITE_UTF16BE].enc==SQLITE_UTF16BE );
89012 sqlite3VdbeChangeP4(v, -1, encnames[ENC(pParse->db)].zName, P4_STATIC);
89013 sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
89014 }else{ /* "PRAGMA encoding = XXX" */
89015 /* Only change the value of sqlite.enc if the database handle is not
89016 ** initialized. If the main database exists, the new sqlite.enc value
89017 ** will be overwritten when the schema is next loaded. If it does not
89018 ** already exists, it will be created to use the new encoding value.
89020 if(
89021 !(DbHasProperty(db, 0, DB_SchemaLoaded)) ||
89022 DbHasProperty(db, 0, DB_Empty)
89024 for(pEnc=&encnames[0]; pEnc->zName; pEnc++){
89025 if( 0==sqlite3StrICmp(zRight, pEnc->zName) ){
89026 ENC(pParse->db) = pEnc->enc ? pEnc->enc : SQLITE_UTF16NATIVE;
89027 break;
89030 if( !pEnc->zName ){
89031 sqlite3ErrorMsg(pParse, "unsupported encoding: %s", zRight);
89035 }else
89036 #endif /* SQLITE_OMIT_UTF16 */
89038 #ifndef SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS
89040 ** PRAGMA [database.]schema_version
89041 ** PRAGMA [database.]schema_version = <integer>
89043 ** PRAGMA [database.]user_version
89044 ** PRAGMA [database.]user_version = <integer>
89046 ** The pragma's schema_version and user_version are used to set or get
89047 ** the value of the schema-version and user-version, respectively. Both
89048 ** the schema-version and the user-version are 32-bit signed integers
89049 ** stored in the database header.
89051 ** The schema-cookie is usually only manipulated internally by SQLite. It
89052 ** is incremented by SQLite whenever the database schema is modified (by
89053 ** creating or dropping a table or index). The schema version is used by
89054 ** SQLite each time a query is executed to ensure that the internal cache
89055 ** of the schema used when compiling the SQL query matches the schema of
89056 ** the database against which the compiled query is actually executed.
89057 ** Subverting this mechanism by using "PRAGMA schema_version" to modify
89058 ** the schema-version is potentially dangerous and may lead to program
89059 ** crashes or database corruption. Use with caution!
89061 ** The user-version is not used internally by SQLite. It may be used by
89062 ** applications for any purpose.
89064 if( sqlite3StrICmp(zLeft, "schema_version")==0
89065 || sqlite3StrICmp(zLeft, "user_version")==0
89066 || sqlite3StrICmp(zLeft, "freelist_count")==0
89068 int iCookie; /* Cookie index. 1 for schema-cookie, 6 for user-cookie. */
89069 sqlite3VdbeUsesBtree(v, iDb);
89070 switch( zLeft[0] ){
89071 case 'f': case 'F':
89072 iCookie = BTREE_FREE_PAGE_COUNT;
89073 break;
89074 case 's': case 'S':
89075 iCookie = BTREE_SCHEMA_VERSION;
89076 break;
89077 default:
89078 iCookie = BTREE_USER_VERSION;
89079 break;
89082 if( zRight && iCookie!=BTREE_FREE_PAGE_COUNT ){
89083 /* Write the specified cookie value */
89084 static const VdbeOpList setCookie[] = {
89085 { OP_Transaction, 0, 1, 0}, /* 0 */
89086 { OP_Integer, 0, 1, 0}, /* 1 */
89087 { OP_SetCookie, 0, 0, 1}, /* 2 */
89089 int addr = sqlite3VdbeAddOpList(v, ArraySize(setCookie), setCookie);
89090 sqlite3VdbeChangeP1(v, addr, iDb);
89091 sqlite3VdbeChangeP1(v, addr+1, sqlite3Atoi(zRight));
89092 sqlite3VdbeChangeP1(v, addr+2, iDb);
89093 sqlite3VdbeChangeP2(v, addr+2, iCookie);
89094 }else{
89095 /* Read the specified cookie value */
89096 static const VdbeOpList readCookie[] = {
89097 { OP_Transaction, 0, 0, 0}, /* 0 */
89098 { OP_ReadCookie, 0, 1, 0}, /* 1 */
89099 { OP_ResultRow, 1, 1, 0}
89101 int addr = sqlite3VdbeAddOpList(v, ArraySize(readCookie), readCookie);
89102 sqlite3VdbeChangeP1(v, addr, iDb);
89103 sqlite3VdbeChangeP1(v, addr+1, iDb);
89104 sqlite3VdbeChangeP3(v, addr+1, iCookie);
89105 sqlite3VdbeSetNumCols(v, 1);
89106 sqlite3VdbeSetColName(v, 0, COLNAME_NAME, zLeft, SQLITE_TRANSIENT);
89108 }else
89109 #endif /* SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS */
89111 #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
89113 ** PRAGMA compile_options
89115 ** Return the names of all compile-time options used in this build,
89116 ** one option per row.
89118 if( sqlite3StrICmp(zLeft, "compile_options")==0 ){
89119 int i = 0;
89120 const char *zOpt;
89121 sqlite3VdbeSetNumCols(v, 1);
89122 pParse->nMem = 1;
89123 sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "compile_option", SQLITE_STATIC);
89124 while( (zOpt = sqlite3_compileoption_get(i++))!=0 ){
89125 sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, zOpt, 0);
89126 sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
89128 }else
89129 #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
89131 #ifndef SQLITE_OMIT_WAL
89133 ** PRAGMA [database.]wal_checkpoint = passive|full|restart
89135 ** Checkpoint the database.
89137 if( sqlite3StrICmp(zLeft, "wal_checkpoint")==0 ){
89138 int iBt = (pId2->z?iDb:SQLITE_MAX_ATTACHED);
89139 int eMode = SQLITE_CHECKPOINT_PASSIVE;
89140 if( zRight ){
89141 if( sqlite3StrICmp(zRight, "full")==0 ){
89142 eMode = SQLITE_CHECKPOINT_FULL;
89143 }else if( sqlite3StrICmp(zRight, "restart")==0 ){
89144 eMode = SQLITE_CHECKPOINT_RESTART;
89147 if( sqlite3ReadSchema(pParse) ) goto pragma_out;
89148 sqlite3VdbeSetNumCols(v, 3);
89149 pParse->nMem = 3;
89150 sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "busy", SQLITE_STATIC);
89151 sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "log", SQLITE_STATIC);
89152 sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "checkpointed", SQLITE_STATIC);
89154 sqlite3VdbeAddOp3(v, OP_Checkpoint, iBt, eMode, 1);
89155 sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3);
89156 }else
89159 ** PRAGMA wal_autocheckpoint
89160 ** PRAGMA wal_autocheckpoint = N
89162 ** Configure a database connection to automatically checkpoint a database
89163 ** after accumulating N frames in the log. Or query for the current value
89164 ** of N.
89166 if( sqlite3StrICmp(zLeft, "wal_autocheckpoint")==0 ){
89167 if( zRight ){
89168 sqlite3_wal_autocheckpoint(db, sqlite3Atoi(zRight));
89170 returnSingleInt(pParse, "wal_autocheckpoint",
89171 db->xWalCallback==sqlite3WalDefaultHook ?
89172 SQLITE_PTR_TO_INT(db->pWalArg) : 0);
89173 }else
89174 #endif
89176 #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
89178 ** Report the current state of file logs for all databases
89180 if( sqlite3StrICmp(zLeft, "lock_status")==0 ){
89181 static const char *const azLockName[] = {
89182 "unlocked", "shared", "reserved", "pending", "exclusive"
89184 int i;
89185 sqlite3VdbeSetNumCols(v, 2);
89186 pParse->nMem = 2;
89187 sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "database", SQLITE_STATIC);
89188 sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "status", SQLITE_STATIC);
89189 for(i=0; i<db->nDb; i++){
89190 Btree *pBt;
89191 Pager *pPager;
89192 const char *zState = "unknown";
89193 int j;
89194 if( db->aDb[i].zName==0 ) continue;
89195 sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, db->aDb[i].zName, P4_STATIC);
89196 pBt = db->aDb[i].pBt;
89197 if( pBt==0 || (pPager = sqlite3BtreePager(pBt))==0 ){
89198 zState = "closed";
89199 }else if( sqlite3_file_control(db, i ? db->aDb[i].zName : 0,
89200 SQLITE_FCNTL_LOCKSTATE, &j)==SQLITE_OK ){
89201 zState = azLockName[j];
89203 sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, zState, P4_STATIC);
89204 sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 2);
89207 }else
89208 #endif
89210 #ifdef SQLITE_HAS_CODEC
89211 if( sqlite3StrICmp(zLeft, "key")==0 && zRight ){
89212 sqlite3_key(db, zRight, sqlite3Strlen30(zRight));
89213 }else
89214 if( sqlite3StrICmp(zLeft, "rekey")==0 && zRight ){
89215 sqlite3_rekey(db, zRight, sqlite3Strlen30(zRight));
89216 }else
89217 if( zRight && (sqlite3StrICmp(zLeft, "hexkey")==0 ||
89218 sqlite3StrICmp(zLeft, "hexrekey")==0) ){
89219 int i, h1, h2;
89220 char zKey[40];
89221 for(i=0; (h1 = zRight[i])!=0 && (h2 = zRight[i+1])!=0; i+=2){
89222 h1 += 9*(1&(h1>>6));
89223 h2 += 9*(1&(h2>>6));
89224 zKey[i/2] = (h2 & 0x0f) | ((h1 & 0xf)<<4);
89226 if( (zLeft[3] & 0xf)==0xb ){
89227 sqlite3_key(db, zKey, i/2);
89228 }else{
89229 sqlite3_rekey(db, zKey, i/2);
89231 }else
89232 #endif
89233 #if defined(SQLITE_HAS_CODEC) || defined(SQLITE_ENABLE_CEROD)
89234 if( sqlite3StrICmp(zLeft, "activate_extensions")==0 ){
89235 #ifdef SQLITE_HAS_CODEC
89236 if( sqlite3StrNICmp(zRight, "see-", 4)==0 ){
89237 sqlite3_activate_see(&zRight[4]);
89239 #endif
89240 #ifdef SQLITE_ENABLE_CEROD
89241 if( sqlite3StrNICmp(zRight, "cerod-", 6)==0 ){
89242 sqlite3_activate_cerod(&zRight[6]);
89244 #endif
89245 }else
89246 #endif
89249 {/* Empty ELSE clause */}
89252 ** Reset the safety level, in case the fullfsync flag or synchronous
89253 ** setting changed.
89255 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
89256 if( db->autoCommit ){
89257 sqlite3BtreeSetSafetyLevel(pDb->pBt, pDb->safety_level,
89258 (db->flags&SQLITE_FullFSync)!=0,
89259 (db->flags&SQLITE_CkptFullFSync)!=0);
89261 #endif
89262 pragma_out:
89263 sqlite3DbFree(db, zLeft);
89264 sqlite3DbFree(db, zRight);
89267 #endif /* SQLITE_OMIT_PRAGMA */
89269 /************** End of pragma.c **********************************************/
89270 /************** Begin file prepare.c *****************************************/
89272 ** 2005 May 25
89274 ** The author disclaims copyright to this source code. In place of
89275 ** a legal notice, here is a blessing:
89277 ** May you do good and not evil.
89278 ** May you find forgiveness for yourself and forgive others.
89279 ** May you share freely, never taking more than you give.
89281 *************************************************************************
89282 ** This file contains the implementation of the sqlite3_prepare()
89283 ** interface, and routines that contribute to loading the database schema
89284 ** from disk.
89288 ** Fill the InitData structure with an error message that indicates
89289 ** that the database is corrupt.
89291 static void corruptSchema(
89292 InitData *pData, /* Initialization context */
89293 const char *zObj, /* Object being parsed at the point of error */
89294 const char *zExtra /* Error information */
89296 sqlite3 *db = pData->db;
89297 if( !db->mallocFailed && (db->flags & SQLITE_RecoveryMode)==0 ){
89298 if( zObj==0 ) zObj = "?";
89299 sqlite3SetString(pData->pzErrMsg, db,
89300 "malformed database schema (%s)", zObj);
89301 if( zExtra ){
89302 *pData->pzErrMsg = sqlite3MAppendf(db, *pData->pzErrMsg,
89303 "%s - %s", *pData->pzErrMsg, zExtra);
89306 pData->rc = db->mallocFailed ? SQLITE_NOMEM : SQLITE_CORRUPT_BKPT;
89310 ** This is the callback routine for the code that initializes the
89311 ** database. See sqlite3Init() below for additional information.
89312 ** This routine is also called from the OP_ParseSchema opcode of the VDBE.
89314 ** Each callback contains the following information:
89316 ** argv[0] = name of thing being created
89317 ** argv[1] = root page number for table or index. 0 for trigger or view.
89318 ** argv[2] = SQL text for the CREATE statement.
89321 SQLITE_PRIVATE int sqlite3InitCallback(void *pInit, int argc, char **argv, char **NotUsed){
89322 InitData *pData = (InitData*)pInit;
89323 sqlite3 *db = pData->db;
89324 int iDb = pData->iDb;
89326 assert( argc==3 );
89327 UNUSED_PARAMETER2(NotUsed, argc);
89328 assert( sqlite3_mutex_held(db->mutex) );
89329 DbClearProperty(db, iDb, DB_Empty);
89330 if( db->mallocFailed ){
89331 corruptSchema(pData, argv[0], 0);
89332 return 1;
89335 assert( iDb>=0 && iDb<db->nDb );
89336 if( argv==0 ) return 0; /* Might happen if EMPTY_RESULT_CALLBACKS are on */
89337 if( argv[1]==0 ){
89338 corruptSchema(pData, argv[0], 0);
89339 }else if( argv[2] && argv[2][0] ){
89340 /* Call the parser to process a CREATE TABLE, INDEX or VIEW.
89341 ** But because db->init.busy is set to 1, no VDBE code is generated
89342 ** or executed. All the parser does is build the internal data
89343 ** structures that describe the table, index, or view.
89345 int rc;
89346 sqlite3_stmt *pStmt;
89347 TESTONLY(int rcp); /* Return code from sqlite3_prepare() */
89349 assert( db->init.busy );
89350 db->init.iDb = iDb;
89351 db->init.newTnum = sqlite3Atoi(argv[1]);
89352 db->init.orphanTrigger = 0;
89353 TESTONLY(rcp = ) sqlite3_prepare(db, argv[2], -1, &pStmt, 0);
89354 rc = db->errCode;
89355 assert( (rc&0xFF)==(rcp&0xFF) );
89356 db->init.iDb = 0;
89357 if( SQLITE_OK!=rc ){
89358 if( db->init.orphanTrigger ){
89359 assert( iDb==1 );
89360 }else{
89361 pData->rc = rc;
89362 if( rc==SQLITE_NOMEM ){
89363 db->mallocFailed = 1;
89364 }else if( rc!=SQLITE_INTERRUPT && (rc&0xFF)!=SQLITE_LOCKED ){
89365 corruptSchema(pData, argv[0], sqlite3_errmsg(db));
89369 sqlite3_finalize(pStmt);
89370 }else if( argv[0]==0 ){
89371 corruptSchema(pData, 0, 0);
89372 }else{
89373 /* If the SQL column is blank it means this is an index that
89374 ** was created to be the PRIMARY KEY or to fulfill a UNIQUE
89375 ** constraint for a CREATE TABLE. The index should have already
89376 ** been created when we processed the CREATE TABLE. All we have
89377 ** to do here is record the root page number for that index.
89379 Index *pIndex;
89380 pIndex = sqlite3FindIndex(db, argv[0], db->aDb[iDb].zName);
89381 if( pIndex==0 ){
89382 /* This can occur if there exists an index on a TEMP table which
89383 ** has the same name as another index on a permanent index. Since
89384 ** the permanent table is hidden by the TEMP table, we can also
89385 ** safely ignore the index on the permanent table.
89387 /* Do Nothing */;
89388 }else if( sqlite3GetInt32(argv[1], &pIndex->tnum)==0 ){
89389 corruptSchema(pData, argv[0], "invalid rootpage");
89392 return 0;
89396 ** Attempt to read the database schema and initialize internal
89397 ** data structures for a single database file. The index of the
89398 ** database file is given by iDb. iDb==0 is used for the main
89399 ** database. iDb==1 should never be used. iDb>=2 is used for
89400 ** auxiliary databases. Return one of the SQLITE_ error codes to
89401 ** indicate success or failure.
89403 static int sqlite3InitOne(sqlite3 *db, int iDb, char **pzErrMsg){
89404 int rc;
89405 int i;
89406 int size;
89407 Table *pTab;
89408 Db *pDb;
89409 char const *azArg[4];
89410 int meta[5];
89411 InitData initData;
89412 char const *zMasterSchema;
89413 char const *zMasterName;
89414 int openedTransaction = 0;
89417 ** The master database table has a structure like this
89419 static const char master_schema[] =
89420 "CREATE TABLE sqlite_master(\n"
89421 " type text,\n"
89422 " name text,\n"
89423 " tbl_name text,\n"
89424 " rootpage integer,\n"
89425 " sql text\n"
89428 #ifndef SQLITE_OMIT_TEMPDB
89429 static const char temp_master_schema[] =
89430 "CREATE TEMP TABLE sqlite_temp_master(\n"
89431 " type text,\n"
89432 " name text,\n"
89433 " tbl_name text,\n"
89434 " rootpage integer,\n"
89435 " sql text\n"
89438 #else
89439 #define temp_master_schema 0
89440 #endif
89442 assert( iDb>=0 && iDb<db->nDb );
89443 assert( db->aDb[iDb].pSchema );
89444 assert( sqlite3_mutex_held(db->mutex) );
89445 assert( iDb==1 || sqlite3BtreeHoldsMutex(db->aDb[iDb].pBt) );
89447 /* zMasterSchema and zInitScript are set to point at the master schema
89448 ** and initialisation script appropriate for the database being
89449 ** initialised. zMasterName is the name of the master table.
89451 if( !OMIT_TEMPDB && iDb==1 ){
89452 zMasterSchema = temp_master_schema;
89453 }else{
89454 zMasterSchema = master_schema;
89456 zMasterName = SCHEMA_TABLE(iDb);
89458 /* Construct the schema tables. */
89459 azArg[0] = zMasterName;
89460 azArg[1] = "1";
89461 azArg[2] = zMasterSchema;
89462 azArg[3] = 0;
89463 initData.db = db;
89464 initData.iDb = iDb;
89465 initData.rc = SQLITE_OK;
89466 initData.pzErrMsg = pzErrMsg;
89467 sqlite3InitCallback(&initData, 3, (char **)azArg, 0);
89468 if( initData.rc ){
89469 rc = initData.rc;
89470 goto error_out;
89472 pTab = sqlite3FindTable(db, zMasterName, db->aDb[iDb].zName);
89473 if( ALWAYS(pTab) ){
89474 pTab->tabFlags |= TF_Readonly;
89477 /* Create a cursor to hold the database open
89479 pDb = &db->aDb[iDb];
89480 if( pDb->pBt==0 ){
89481 if( !OMIT_TEMPDB && ALWAYS(iDb==1) ){
89482 DbSetProperty(db, 1, DB_SchemaLoaded);
89484 return SQLITE_OK;
89487 /* If there is not already a read-only (or read-write) transaction opened
89488 ** on the b-tree database, open one now. If a transaction is opened, it
89489 ** will be closed before this function returns. */
89490 sqlite3BtreeEnter(pDb->pBt);
89491 if( !sqlite3BtreeIsInReadTrans(pDb->pBt) ){
89492 rc = sqlite3BtreeBeginTrans(pDb->pBt, 0);
89493 if( rc!=SQLITE_OK ){
89494 sqlite3SetString(pzErrMsg, db, "%s", sqlite3ErrStr(rc));
89495 goto initone_error_out;
89497 openedTransaction = 1;
89500 /* Get the database meta information.
89502 ** Meta values are as follows:
89503 ** meta[0] Schema cookie. Changes with each schema change.
89504 ** meta[1] File format of schema layer.
89505 ** meta[2] Size of the page cache.
89506 ** meta[3] Largest rootpage (auto/incr_vacuum mode)
89507 ** meta[4] Db text encoding. 1:UTF-8 2:UTF-16LE 3:UTF-16BE
89508 ** meta[5] User version
89509 ** meta[6] Incremental vacuum mode
89510 ** meta[7] unused
89511 ** meta[8] unused
89512 ** meta[9] unused
89514 ** Note: The #defined SQLITE_UTF* symbols in sqliteInt.h correspond to
89515 ** the possible values of meta[4].
89517 for(i=0; i<ArraySize(meta); i++){
89518 sqlite3BtreeGetMeta(pDb->pBt, i+1, (u32 *)&meta[i]);
89520 pDb->pSchema->schema_cookie = meta[BTREE_SCHEMA_VERSION-1];
89522 /* If opening a non-empty database, check the text encoding. For the
89523 ** main database, set sqlite3.enc to the encoding of the main database.
89524 ** For an attached db, it is an error if the encoding is not the same
89525 ** as sqlite3.enc.
89527 if( meta[BTREE_TEXT_ENCODING-1] ){ /* text encoding */
89528 if( iDb==0 ){
89529 u8 encoding;
89530 /* If opening the main database, set ENC(db). */
89531 encoding = (u8)meta[BTREE_TEXT_ENCODING-1] & 3;
89532 if( encoding==0 ) encoding = SQLITE_UTF8;
89533 ENC(db) = encoding;
89534 db->pDfltColl = sqlite3FindCollSeq(db, SQLITE_UTF8, "BINARY", 0);
89535 }else{
89536 /* If opening an attached database, the encoding much match ENC(db) */
89537 if( meta[BTREE_TEXT_ENCODING-1]!=ENC(db) ){
89538 sqlite3SetString(pzErrMsg, db, "attached databases must use the same"
89539 " text encoding as main database");
89540 rc = SQLITE_ERROR;
89541 goto initone_error_out;
89544 }else{
89545 DbSetProperty(db, iDb, DB_Empty);
89547 pDb->pSchema->enc = ENC(db);
89549 if( pDb->pSchema->cache_size==0 ){
89550 size = sqlite3AbsInt32(meta[BTREE_DEFAULT_CACHE_SIZE-1]);
89551 if( size==0 ){ size = SQLITE_DEFAULT_CACHE_SIZE; }
89552 pDb->pSchema->cache_size = size;
89553 sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
89557 ** file_format==1 Version 3.0.0.
89558 ** file_format==2 Version 3.1.3. // ALTER TABLE ADD COLUMN
89559 ** file_format==3 Version 3.1.4. // ditto but with non-NULL defaults
89560 ** file_format==4 Version 3.3.0. // DESC indices. Boolean constants
89562 pDb->pSchema->file_format = (u8)meta[BTREE_FILE_FORMAT-1];
89563 if( pDb->pSchema->file_format==0 ){
89564 pDb->pSchema->file_format = 1;
89566 if( pDb->pSchema->file_format>SQLITE_MAX_FILE_FORMAT ){
89567 sqlite3SetString(pzErrMsg, db, "unsupported file format");
89568 rc = SQLITE_ERROR;
89569 goto initone_error_out;
89572 /* Ticket #2804: When we open a database in the newer file format,
89573 ** clear the legacy_file_format pragma flag so that a VACUUM will
89574 ** not downgrade the database and thus invalidate any descending
89575 ** indices that the user might have created.
89577 if( iDb==0 && meta[BTREE_FILE_FORMAT-1]>=4 ){
89578 db->flags &= ~SQLITE_LegacyFileFmt;
89581 /* Read the schema information out of the schema tables
89583 assert( db->init.busy );
89585 char *zSql;
89586 zSql = sqlite3MPrintf(db,
89587 "SELECT name, rootpage, sql FROM '%q'.%s ORDER BY rowid",
89588 db->aDb[iDb].zName, zMasterName);
89589 #ifndef SQLITE_OMIT_AUTHORIZATION
89591 int (*xAuth)(void*,int,const char*,const char*,const char*,const char*);
89592 xAuth = db->xAuth;
89593 db->xAuth = 0;
89594 #endif
89595 rc = sqlite3_exec(db, zSql, sqlite3InitCallback, &initData, 0);
89596 #ifndef SQLITE_OMIT_AUTHORIZATION
89597 db->xAuth = xAuth;
89599 #endif
89600 if( rc==SQLITE_OK ) rc = initData.rc;
89601 sqlite3DbFree(db, zSql);
89602 #ifndef SQLITE_OMIT_ANALYZE
89603 if( rc==SQLITE_OK ){
89604 sqlite3AnalysisLoad(db, iDb);
89606 #endif
89608 if( db->mallocFailed ){
89609 rc = SQLITE_NOMEM;
89610 sqlite3ResetInternalSchema(db, -1);
89612 if( rc==SQLITE_OK || (db->flags&SQLITE_RecoveryMode)){
89613 /* Black magic: If the SQLITE_RecoveryMode flag is set, then consider
89614 ** the schema loaded, even if errors occurred. In this situation the
89615 ** current sqlite3_prepare() operation will fail, but the following one
89616 ** will attempt to compile the supplied statement against whatever subset
89617 ** of the schema was loaded before the error occurred. The primary
89618 ** purpose of this is to allow access to the sqlite_master table
89619 ** even when its contents have been corrupted.
89621 DbSetProperty(db, iDb, DB_SchemaLoaded);
89622 rc = SQLITE_OK;
89625 /* Jump here for an error that occurs after successfully allocating
89626 ** curMain and calling sqlite3BtreeEnter(). For an error that occurs
89627 ** before that point, jump to error_out.
89629 initone_error_out:
89630 if( openedTransaction ){
89631 sqlite3BtreeCommit(pDb->pBt);
89633 sqlite3BtreeLeave(pDb->pBt);
89635 error_out:
89636 if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){
89637 db->mallocFailed = 1;
89639 return rc;
89643 ** Initialize all database files - the main database file, the file
89644 ** used to store temporary tables, and any additional database files
89645 ** created using ATTACH statements. Return a success code. If an
89646 ** error occurs, write an error message into *pzErrMsg.
89648 ** After a database is initialized, the DB_SchemaLoaded bit is set
89649 ** bit is set in the flags field of the Db structure. If the database
89650 ** file was of zero-length, then the DB_Empty flag is also set.
89652 SQLITE_PRIVATE int sqlite3Init(sqlite3 *db, char **pzErrMsg){
89653 int i, rc;
89654 int commit_internal = !(db->flags&SQLITE_InternChanges);
89656 assert( sqlite3_mutex_held(db->mutex) );
89657 rc = SQLITE_OK;
89658 db->init.busy = 1;
89659 for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
89660 if( DbHasProperty(db, i, DB_SchemaLoaded) || i==1 ) continue;
89661 rc = sqlite3InitOne(db, i, pzErrMsg);
89662 if( rc ){
89663 sqlite3ResetInternalSchema(db, i);
89667 /* Once all the other databases have been initialised, load the schema
89668 ** for the TEMP database. This is loaded last, as the TEMP database
89669 ** schema may contain references to objects in other databases.
89671 #ifndef SQLITE_OMIT_TEMPDB
89672 if( rc==SQLITE_OK && ALWAYS(db->nDb>1)
89673 && !DbHasProperty(db, 1, DB_SchemaLoaded) ){
89674 rc = sqlite3InitOne(db, 1, pzErrMsg);
89675 if( rc ){
89676 sqlite3ResetInternalSchema(db, 1);
89679 #endif
89681 db->init.busy = 0;
89682 if( rc==SQLITE_OK && commit_internal ){
89683 sqlite3CommitInternalChanges(db);
89686 return rc;
89690 ** This routine is a no-op if the database schema is already initialised.
89691 ** Otherwise, the schema is loaded. An error code is returned.
89693 SQLITE_PRIVATE int sqlite3ReadSchema(Parse *pParse){
89694 int rc = SQLITE_OK;
89695 sqlite3 *db = pParse->db;
89696 assert( sqlite3_mutex_held(db->mutex) );
89697 if( !db->init.busy ){
89698 rc = sqlite3Init(db, &pParse->zErrMsg);
89700 if( rc!=SQLITE_OK ){
89701 pParse->rc = rc;
89702 pParse->nErr++;
89704 return rc;
89709 ** Check schema cookies in all databases. If any cookie is out
89710 ** of date set pParse->rc to SQLITE_SCHEMA. If all schema cookies
89711 ** make no changes to pParse->rc.
89713 static void schemaIsValid(Parse *pParse){
89714 sqlite3 *db = pParse->db;
89715 int iDb;
89716 int rc;
89717 int cookie;
89719 assert( pParse->checkSchema );
89720 assert( sqlite3_mutex_held(db->mutex) );
89721 for(iDb=0; iDb<db->nDb; iDb++){
89722 int openedTransaction = 0; /* True if a transaction is opened */
89723 Btree *pBt = db->aDb[iDb].pBt; /* Btree database to read cookie from */
89724 if( pBt==0 ) continue;
89726 /* If there is not already a read-only (or read-write) transaction opened
89727 ** on the b-tree database, open one now. If a transaction is opened, it
89728 ** will be closed immediately after reading the meta-value. */
89729 if( !sqlite3BtreeIsInReadTrans(pBt) ){
89730 rc = sqlite3BtreeBeginTrans(pBt, 0);
89731 if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){
89732 db->mallocFailed = 1;
89734 if( rc!=SQLITE_OK ) return;
89735 openedTransaction = 1;
89738 /* Read the schema cookie from the database. If it does not match the
89739 ** value stored as part of the in-memory schema representation,
89740 ** set Parse.rc to SQLITE_SCHEMA. */
89741 sqlite3BtreeGetMeta(pBt, BTREE_SCHEMA_VERSION, (u32 *)&cookie);
89742 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
89743 if( cookie!=db->aDb[iDb].pSchema->schema_cookie ){
89744 sqlite3ResetInternalSchema(db, iDb);
89745 pParse->rc = SQLITE_SCHEMA;
89748 /* Close the transaction, if one was opened. */
89749 if( openedTransaction ){
89750 sqlite3BtreeCommit(pBt);
89756 ** Convert a schema pointer into the iDb index that indicates
89757 ** which database file in db->aDb[] the schema refers to.
89759 ** If the same database is attached more than once, the first
89760 ** attached database is returned.
89762 SQLITE_PRIVATE int sqlite3SchemaToIndex(sqlite3 *db, Schema *pSchema){
89763 int i = -1000000;
89765 /* If pSchema is NULL, then return -1000000. This happens when code in
89766 ** expr.c is trying to resolve a reference to a transient table (i.e. one
89767 ** created by a sub-select). In this case the return value of this
89768 ** function should never be used.
89770 ** We return -1000000 instead of the more usual -1 simply because using
89771 ** -1000000 as the incorrect index into db->aDb[] is much
89772 ** more likely to cause a segfault than -1 (of course there are assert()
89773 ** statements too, but it never hurts to play the odds).
89775 assert( sqlite3_mutex_held(db->mutex) );
89776 if( pSchema ){
89777 for(i=0; ALWAYS(i<db->nDb); i++){
89778 if( db->aDb[i].pSchema==pSchema ){
89779 break;
89782 assert( i>=0 && i<db->nDb );
89784 return i;
89788 ** Compile the UTF-8 encoded SQL statement zSql into a statement handle.
89790 static int sqlite3Prepare(
89791 sqlite3 *db, /* Database handle. */
89792 const char *zSql, /* UTF-8 encoded SQL statement. */
89793 int nBytes, /* Length of zSql in bytes. */
89794 int saveSqlFlag, /* True to copy SQL text into the sqlite3_stmt */
89795 Vdbe *pReprepare, /* VM being reprepared */
89796 sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
89797 const char **pzTail /* OUT: End of parsed string */
89799 Parse *pParse; /* Parsing context */
89800 char *zErrMsg = 0; /* Error message */
89801 int rc = SQLITE_OK; /* Result code */
89802 int i; /* Loop counter */
89804 /* Allocate the parsing context */
89805 pParse = sqlite3StackAllocZero(db, sizeof(*pParse));
89806 if( pParse==0 ){
89807 rc = SQLITE_NOMEM;
89808 goto end_prepare;
89810 pParse->pReprepare = pReprepare;
89811 assert( ppStmt && *ppStmt==0 );
89812 assert( !db->mallocFailed );
89813 assert( sqlite3_mutex_held(db->mutex) );
89815 /* Check to verify that it is possible to get a read lock on all
89816 ** database schemas. The inability to get a read lock indicates that
89817 ** some other database connection is holding a write-lock, which in
89818 ** turn means that the other connection has made uncommitted changes
89819 ** to the schema.
89821 ** Were we to proceed and prepare the statement against the uncommitted
89822 ** schema changes and if those schema changes are subsequently rolled
89823 ** back and different changes are made in their place, then when this
89824 ** prepared statement goes to run the schema cookie would fail to detect
89825 ** the schema change. Disaster would follow.
89827 ** This thread is currently holding mutexes on all Btrees (because
89828 ** of the sqlite3BtreeEnterAll() in sqlite3LockAndPrepare()) so it
89829 ** is not possible for another thread to start a new schema change
89830 ** while this routine is running. Hence, we do not need to hold
89831 ** locks on the schema, we just need to make sure nobody else is
89832 ** holding them.
89834 ** Note that setting READ_UNCOMMITTED overrides most lock detection,
89835 ** but it does *not* override schema lock detection, so this all still
89836 ** works even if READ_UNCOMMITTED is set.
89838 for(i=0; i<db->nDb; i++) {
89839 Btree *pBt = db->aDb[i].pBt;
89840 if( pBt ){
89841 assert( sqlite3BtreeHoldsMutex(pBt) );
89842 rc = sqlite3BtreeSchemaLocked(pBt);
89843 if( rc ){
89844 const char *zDb = db->aDb[i].zName;
89845 sqlite3Error(db, rc, "database schema is locked: %s", zDb);
89846 testcase( db->flags & SQLITE_ReadUncommitted );
89847 goto end_prepare;
89852 sqlite3VtabUnlockList(db);
89854 pParse->db = db;
89855 pParse->nQueryLoop = (double)1;
89856 if( nBytes>=0 && (nBytes==0 || zSql[nBytes-1]!=0) ){
89857 char *zSqlCopy;
89858 int mxLen = db->aLimit[SQLITE_LIMIT_SQL_LENGTH];
89859 testcase( nBytes==mxLen );
89860 testcase( nBytes==mxLen+1 );
89861 if( nBytes>mxLen ){
89862 sqlite3Error(db, SQLITE_TOOBIG, "statement too long");
89863 rc = sqlite3ApiExit(db, SQLITE_TOOBIG);
89864 goto end_prepare;
89866 zSqlCopy = sqlite3DbStrNDup(db, zSql, nBytes);
89867 if( zSqlCopy ){
89868 sqlite3RunParser(pParse, zSqlCopy, &zErrMsg);
89869 sqlite3DbFree(db, zSqlCopy);
89870 pParse->zTail = &zSql[pParse->zTail-zSqlCopy];
89871 }else{
89872 pParse->zTail = &zSql[nBytes];
89874 }else{
89875 sqlite3RunParser(pParse, zSql, &zErrMsg);
89877 assert( 1==(int)pParse->nQueryLoop );
89879 if( db->mallocFailed ){
89880 pParse->rc = SQLITE_NOMEM;
89882 if( pParse->rc==SQLITE_DONE ) pParse->rc = SQLITE_OK;
89883 if( pParse->checkSchema ){
89884 schemaIsValid(pParse);
89886 if( db->mallocFailed ){
89887 pParse->rc = SQLITE_NOMEM;
89889 if( pzTail ){
89890 *pzTail = pParse->zTail;
89892 rc = pParse->rc;
89894 #ifndef SQLITE_OMIT_EXPLAIN
89895 if( rc==SQLITE_OK && pParse->pVdbe && pParse->explain ){
89896 static const char * const azColName[] = {
89897 "addr", "opcode", "p1", "p2", "p3", "p4", "p5", "comment",
89898 "selectid", "order", "from", "detail"
89900 int iFirst, mx;
89901 if( pParse->explain==2 ){
89902 sqlite3VdbeSetNumCols(pParse->pVdbe, 4);
89903 iFirst = 8;
89904 mx = 12;
89905 }else{
89906 sqlite3VdbeSetNumCols(pParse->pVdbe, 8);
89907 iFirst = 0;
89908 mx = 8;
89910 for(i=iFirst; i<mx; i++){
89911 sqlite3VdbeSetColName(pParse->pVdbe, i-iFirst, COLNAME_NAME,
89912 azColName[i], SQLITE_STATIC);
89915 #endif
89917 assert( db->init.busy==0 || saveSqlFlag==0 );
89918 if( db->init.busy==0 ){
89919 Vdbe *pVdbe = pParse->pVdbe;
89920 sqlite3VdbeSetSql(pVdbe, zSql, (int)(pParse->zTail-zSql), saveSqlFlag);
89922 if( pParse->pVdbe && (rc!=SQLITE_OK || db->mallocFailed) ){
89923 sqlite3VdbeFinalize(pParse->pVdbe);
89924 assert(!(*ppStmt));
89925 }else{
89926 *ppStmt = (sqlite3_stmt*)pParse->pVdbe;
89929 if( zErrMsg ){
89930 sqlite3Error(db, rc, "%s", zErrMsg);
89931 sqlite3DbFree(db, zErrMsg);
89932 }else{
89933 sqlite3Error(db, rc, 0);
89936 /* Delete any TriggerPrg structures allocated while parsing this statement. */
89937 while( pParse->pTriggerPrg ){
89938 TriggerPrg *pT = pParse->pTriggerPrg;
89939 pParse->pTriggerPrg = pT->pNext;
89940 sqlite3DbFree(db, pT);
89943 end_prepare:
89945 sqlite3StackFree(db, pParse);
89946 rc = sqlite3ApiExit(db, rc);
89947 assert( (rc&db->errMask)==rc );
89948 return rc;
89950 static int sqlite3LockAndPrepare(
89951 sqlite3 *db, /* Database handle. */
89952 const char *zSql, /* UTF-8 encoded SQL statement. */
89953 int nBytes, /* Length of zSql in bytes. */
89954 int saveSqlFlag, /* True to copy SQL text into the sqlite3_stmt */
89955 Vdbe *pOld, /* VM being reprepared */
89956 sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
89957 const char **pzTail /* OUT: End of parsed string */
89959 int rc;
89960 assert( ppStmt!=0 );
89961 *ppStmt = 0;
89962 if( !sqlite3SafetyCheckOk(db) ){
89963 return SQLITE_MISUSE_BKPT;
89965 sqlite3_mutex_enter(db->mutex);
89966 sqlite3BtreeEnterAll(db);
89967 rc = sqlite3Prepare(db, zSql, nBytes, saveSqlFlag, pOld, ppStmt, pzTail);
89968 if( rc==SQLITE_SCHEMA ){
89969 sqlite3_finalize(*ppStmt);
89970 rc = sqlite3Prepare(db, zSql, nBytes, saveSqlFlag, pOld, ppStmt, pzTail);
89972 sqlite3BtreeLeaveAll(db);
89973 sqlite3_mutex_leave(db->mutex);
89974 return rc;
89978 ** Rerun the compilation of a statement after a schema change.
89980 ** If the statement is successfully recompiled, return SQLITE_OK. Otherwise,
89981 ** if the statement cannot be recompiled because another connection has
89982 ** locked the sqlite3_master table, return SQLITE_LOCKED. If any other error
89983 ** occurs, return SQLITE_SCHEMA.
89985 SQLITE_PRIVATE int sqlite3Reprepare(Vdbe *p){
89986 int rc;
89987 sqlite3_stmt *pNew;
89988 const char *zSql;
89989 sqlite3 *db;
89991 assert( sqlite3_mutex_held(sqlite3VdbeDb(p)->mutex) );
89992 zSql = sqlite3_sql((sqlite3_stmt *)p);
89993 assert( zSql!=0 ); /* Reprepare only called for prepare_v2() statements */
89994 db = sqlite3VdbeDb(p);
89995 assert( sqlite3_mutex_held(db->mutex) );
89996 rc = sqlite3LockAndPrepare(db, zSql, -1, 0, p, &pNew, 0);
89997 if( rc ){
89998 if( rc==SQLITE_NOMEM ){
89999 db->mallocFailed = 1;
90001 assert( pNew==0 );
90002 return rc;
90003 }else{
90004 assert( pNew!=0 );
90006 sqlite3VdbeSwap((Vdbe*)pNew, p);
90007 sqlite3TransferBindings(pNew, (sqlite3_stmt*)p);
90008 sqlite3VdbeResetStepResult((Vdbe*)pNew);
90009 sqlite3VdbeFinalize((Vdbe*)pNew);
90010 return SQLITE_OK;
90015 ** Two versions of the official API. Legacy and new use. In the legacy
90016 ** version, the original SQL text is not saved in the prepared statement
90017 ** and so if a schema change occurs, SQLITE_SCHEMA is returned by
90018 ** sqlite3_step(). In the new version, the original SQL text is retained
90019 ** and the statement is automatically recompiled if an schema change
90020 ** occurs.
90022 SQLITE_API int sqlite3_prepare(
90023 sqlite3 *db, /* Database handle. */
90024 const char *zSql, /* UTF-8 encoded SQL statement. */
90025 int nBytes, /* Length of zSql in bytes. */
90026 sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
90027 const char **pzTail /* OUT: End of parsed string */
90029 int rc;
90030 rc = sqlite3LockAndPrepare(db,zSql,nBytes,0,0,ppStmt,pzTail);
90031 assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 ); /* VERIFY: F13021 */
90032 return rc;
90034 SQLITE_API int sqlite3_prepare_v2(
90035 sqlite3 *db, /* Database handle. */
90036 const char *zSql, /* UTF-8 encoded SQL statement. */
90037 int nBytes, /* Length of zSql in bytes. */
90038 sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
90039 const char **pzTail /* OUT: End of parsed string */
90041 int rc;
90042 rc = sqlite3LockAndPrepare(db,zSql,nBytes,1,0,ppStmt,pzTail);
90043 assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 ); /* VERIFY: F13021 */
90044 return rc;
90048 #ifndef SQLITE_OMIT_UTF16
90050 ** Compile the UTF-16 encoded SQL statement zSql into a statement handle.
90052 static int sqlite3Prepare16(
90053 sqlite3 *db, /* Database handle. */
90054 const void *zSql, /* UTF-16 encoded SQL statement. */
90055 int nBytes, /* Length of zSql in bytes. */
90056 int saveSqlFlag, /* True to save SQL text into the sqlite3_stmt */
90057 sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
90058 const void **pzTail /* OUT: End of parsed string */
90060 /* This function currently works by first transforming the UTF-16
90061 ** encoded string to UTF-8, then invoking sqlite3_prepare(). The
90062 ** tricky bit is figuring out the pointer to return in *pzTail.
90064 char *zSql8;
90065 const char *zTail8 = 0;
90066 int rc = SQLITE_OK;
90068 assert( ppStmt );
90069 *ppStmt = 0;
90070 if( !sqlite3SafetyCheckOk(db) ){
90071 return SQLITE_MISUSE_BKPT;
90073 sqlite3_mutex_enter(db->mutex);
90074 zSql8 = sqlite3Utf16to8(db, zSql, nBytes, SQLITE_UTF16NATIVE);
90075 if( zSql8 ){
90076 rc = sqlite3LockAndPrepare(db, zSql8, -1, saveSqlFlag, 0, ppStmt, &zTail8);
90079 if( zTail8 && pzTail ){
90080 /* If sqlite3_prepare returns a tail pointer, we calculate the
90081 ** equivalent pointer into the UTF-16 string by counting the unicode
90082 ** characters between zSql8 and zTail8, and then returning a pointer
90083 ** the same number of characters into the UTF-16 string.
90085 int chars_parsed = sqlite3Utf8CharLen(zSql8, (int)(zTail8-zSql8));
90086 *pzTail = (u8 *)zSql + sqlite3Utf16ByteLen(zSql, chars_parsed);
90088 sqlite3DbFree(db, zSql8);
90089 rc = sqlite3ApiExit(db, rc);
90090 sqlite3_mutex_leave(db->mutex);
90091 return rc;
90095 ** Two versions of the official API. Legacy and new use. In the legacy
90096 ** version, the original SQL text is not saved in the prepared statement
90097 ** and so if a schema change occurs, SQLITE_SCHEMA is returned by
90098 ** sqlite3_step(). In the new version, the original SQL text is retained
90099 ** and the statement is automatically recompiled if an schema change
90100 ** occurs.
90102 SQLITE_API int sqlite3_prepare16(
90103 sqlite3 *db, /* Database handle. */
90104 const void *zSql, /* UTF-16 encoded SQL statement. */
90105 int nBytes, /* Length of zSql in bytes. */
90106 sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
90107 const void **pzTail /* OUT: End of parsed string */
90109 int rc;
90110 rc = sqlite3Prepare16(db,zSql,nBytes,0,ppStmt,pzTail);
90111 assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 ); /* VERIFY: F13021 */
90112 return rc;
90114 SQLITE_API int sqlite3_prepare16_v2(
90115 sqlite3 *db, /* Database handle. */
90116 const void *zSql, /* UTF-16 encoded SQL statement. */
90117 int nBytes, /* Length of zSql in bytes. */
90118 sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
90119 const void **pzTail /* OUT: End of parsed string */
90121 int rc;
90122 rc = sqlite3Prepare16(db,zSql,nBytes,1,ppStmt,pzTail);
90123 assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 ); /* VERIFY: F13021 */
90124 return rc;
90127 #endif /* SQLITE_OMIT_UTF16 */
90129 /************** End of prepare.c *********************************************/
90130 /************** Begin file select.c ******************************************/
90132 ** 2001 September 15
90134 ** The author disclaims copyright to this source code. In place of
90135 ** a legal notice, here is a blessing:
90137 ** May you do good and not evil.
90138 ** May you find forgiveness for yourself and forgive others.
90139 ** May you share freely, never taking more than you give.
90141 *************************************************************************
90142 ** This file contains C code routines that are called by the parser
90143 ** to handle SELECT statements in SQLite.
90148 ** Delete all the content of a Select structure but do not deallocate
90149 ** the select structure itself.
90151 static void clearSelect(sqlite3 *db, Select *p){
90152 sqlite3ExprListDelete(db, p->pEList);
90153 sqlite3SrcListDelete(db, p->pSrc);
90154 sqlite3ExprDelete(db, p->pWhere);
90155 sqlite3ExprListDelete(db, p->pGroupBy);
90156 sqlite3ExprDelete(db, p->pHaving);
90157 sqlite3ExprListDelete(db, p->pOrderBy);
90158 sqlite3SelectDelete(db, p->pPrior);
90159 sqlite3ExprDelete(db, p->pLimit);
90160 sqlite3ExprDelete(db, p->pOffset);
90164 ** Initialize a SelectDest structure.
90166 SQLITE_PRIVATE void sqlite3SelectDestInit(SelectDest *pDest, int eDest, int iParm){
90167 pDest->eDest = (u8)eDest;
90168 pDest->iParm = iParm;
90169 pDest->affinity = 0;
90170 pDest->iMem = 0;
90171 pDest->nMem = 0;
90176 ** Allocate a new Select structure and return a pointer to that
90177 ** structure.
90179 SQLITE_PRIVATE Select *sqlite3SelectNew(
90180 Parse *pParse, /* Parsing context */
90181 ExprList *pEList, /* which columns to include in the result */
90182 SrcList *pSrc, /* the FROM clause -- which tables to scan */
90183 Expr *pWhere, /* the WHERE clause */
90184 ExprList *pGroupBy, /* the GROUP BY clause */
90185 Expr *pHaving, /* the HAVING clause */
90186 ExprList *pOrderBy, /* the ORDER BY clause */
90187 int isDistinct, /* true if the DISTINCT keyword is present */
90188 Expr *pLimit, /* LIMIT value. NULL means not used */
90189 Expr *pOffset /* OFFSET value. NULL means no offset */
90191 Select *pNew;
90192 Select standin;
90193 sqlite3 *db = pParse->db;
90194 pNew = sqlite3DbMallocZero(db, sizeof(*pNew) );
90195 assert( db->mallocFailed || !pOffset || pLimit ); /* OFFSET implies LIMIT */
90196 if( pNew==0 ){
90197 pNew = &standin;
90198 memset(pNew, 0, sizeof(*pNew));
90200 if( pEList==0 ){
90201 pEList = sqlite3ExprListAppend(pParse, 0, sqlite3Expr(db,TK_ALL,0));
90203 pNew->pEList = pEList;
90204 pNew->pSrc = pSrc;
90205 pNew->pWhere = pWhere;
90206 pNew->pGroupBy = pGroupBy;
90207 pNew->pHaving = pHaving;
90208 pNew->pOrderBy = pOrderBy;
90209 pNew->selFlags = isDistinct ? SF_Distinct : 0;
90210 pNew->op = TK_SELECT;
90211 pNew->pLimit = pLimit;
90212 pNew->pOffset = pOffset;
90213 assert( pOffset==0 || pLimit!=0 );
90214 pNew->addrOpenEphm[0] = -1;
90215 pNew->addrOpenEphm[1] = -1;
90216 pNew->addrOpenEphm[2] = -1;
90217 if( db->mallocFailed ) {
90218 clearSelect(db, pNew);
90219 if( pNew!=&standin ) sqlite3DbFree(db, pNew);
90220 pNew = 0;
90222 return pNew;
90226 ** Delete the given Select structure and all of its substructures.
90228 SQLITE_PRIVATE void sqlite3SelectDelete(sqlite3 *db, Select *p){
90229 if( p ){
90230 clearSelect(db, p);
90231 sqlite3DbFree(db, p);
90236 ** Given 1 to 3 identifiers preceeding the JOIN keyword, determine the
90237 ** type of join. Return an integer constant that expresses that type
90238 ** in terms of the following bit values:
90240 ** JT_INNER
90241 ** JT_CROSS
90242 ** JT_OUTER
90243 ** JT_NATURAL
90244 ** JT_LEFT
90245 ** JT_RIGHT
90247 ** A full outer join is the combination of JT_LEFT and JT_RIGHT.
90249 ** If an illegal or unsupported join type is seen, then still return
90250 ** a join type, but put an error in the pParse structure.
90252 SQLITE_PRIVATE int sqlite3JoinType(Parse *pParse, Token *pA, Token *pB, Token *pC){
90253 int jointype = 0;
90254 Token *apAll[3];
90255 Token *p;
90256 /* 0123456789 123456789 123456789 123 */
90257 static const char zKeyText[] = "naturaleftouterightfullinnercross";
90258 static const struct {
90259 u8 i; /* Beginning of keyword text in zKeyText[] */
90260 u8 nChar; /* Length of the keyword in characters */
90261 u8 code; /* Join type mask */
90262 } aKeyword[] = {
90263 /* natural */ { 0, 7, JT_NATURAL },
90264 /* left */ { 6, 4, JT_LEFT|JT_OUTER },
90265 /* outer */ { 10, 5, JT_OUTER },
90266 /* right */ { 14, 5, JT_RIGHT|JT_OUTER },
90267 /* full */ { 19, 4, JT_LEFT|JT_RIGHT|JT_OUTER },
90268 /* inner */ { 23, 5, JT_INNER },
90269 /* cross */ { 28, 5, JT_INNER|JT_CROSS },
90271 int i, j;
90272 apAll[0] = pA;
90273 apAll[1] = pB;
90274 apAll[2] = pC;
90275 for(i=0; i<3 && apAll[i]; i++){
90276 p = apAll[i];
90277 for(j=0; j<ArraySize(aKeyword); j++){
90278 if( p->n==aKeyword[j].nChar
90279 && sqlite3StrNICmp((char*)p->z, &zKeyText[aKeyword[j].i], p->n)==0 ){
90280 jointype |= aKeyword[j].code;
90281 break;
90284 testcase( j==0 || j==1 || j==2 || j==3 || j==4 || j==5 || j==6 );
90285 if( j>=ArraySize(aKeyword) ){
90286 jointype |= JT_ERROR;
90287 break;
90291 (jointype & (JT_INNER|JT_OUTER))==(JT_INNER|JT_OUTER) ||
90292 (jointype & JT_ERROR)!=0
90294 const char *zSp = " ";
90295 assert( pB!=0 );
90296 if( pC==0 ){ zSp++; }
90297 sqlite3ErrorMsg(pParse, "unknown or unsupported join type: "
90298 "%T %T%s%T", pA, pB, zSp, pC);
90299 jointype = JT_INNER;
90300 }else if( (jointype & JT_OUTER)!=0
90301 && (jointype & (JT_LEFT|JT_RIGHT))!=JT_LEFT ){
90302 sqlite3ErrorMsg(pParse,
90303 "RIGHT and FULL OUTER JOINs are not currently supported");
90304 jointype = JT_INNER;
90306 return jointype;
90310 ** Return the index of a column in a table. Return -1 if the column
90311 ** is not contained in the table.
90313 static int columnIndex(Table *pTab, const char *zCol){
90314 int i;
90315 for(i=0; i<pTab->nCol; i++){
90316 if( sqlite3StrICmp(pTab->aCol[i].zName, zCol)==0 ) return i;
90318 return -1;
90322 ** Search the first N tables in pSrc, from left to right, looking for a
90323 ** table that has a column named zCol.
90325 ** When found, set *piTab and *piCol to the table index and column index
90326 ** of the matching column and return TRUE.
90328 ** If not found, return FALSE.
90330 static int tableAndColumnIndex(
90331 SrcList *pSrc, /* Array of tables to search */
90332 int N, /* Number of tables in pSrc->a[] to search */
90333 const char *zCol, /* Name of the column we are looking for */
90334 int *piTab, /* Write index of pSrc->a[] here */
90335 int *piCol /* Write index of pSrc->a[*piTab].pTab->aCol[] here */
90337 int i; /* For looping over tables in pSrc */
90338 int iCol; /* Index of column matching zCol */
90340 assert( (piTab==0)==(piCol==0) ); /* Both or neither are NULL */
90341 for(i=0; i<N; i++){
90342 iCol = columnIndex(pSrc->a[i].pTab, zCol);
90343 if( iCol>=0 ){
90344 if( piTab ){
90345 *piTab = i;
90346 *piCol = iCol;
90348 return 1;
90351 return 0;
90355 ** This function is used to add terms implied by JOIN syntax to the
90356 ** WHERE clause expression of a SELECT statement. The new term, which
90357 ** is ANDed with the existing WHERE clause, is of the form:
90359 ** (tab1.col1 = tab2.col2)
90361 ** where tab1 is the iSrc'th table in SrcList pSrc and tab2 is the
90362 ** (iSrc+1)'th. Column col1 is column iColLeft of tab1, and col2 is
90363 ** column iColRight of tab2.
90365 static void addWhereTerm(
90366 Parse *pParse, /* Parsing context */
90367 SrcList *pSrc, /* List of tables in FROM clause */
90368 int iLeft, /* Index of first table to join in pSrc */
90369 int iColLeft, /* Index of column in first table */
90370 int iRight, /* Index of second table in pSrc */
90371 int iColRight, /* Index of column in second table */
90372 int isOuterJoin, /* True if this is an OUTER join */
90373 Expr **ppWhere /* IN/OUT: The WHERE clause to add to */
90375 sqlite3 *db = pParse->db;
90376 Expr *pE1;
90377 Expr *pE2;
90378 Expr *pEq;
90380 assert( iLeft<iRight );
90381 assert( pSrc->nSrc>iRight );
90382 assert( pSrc->a[iLeft].pTab );
90383 assert( pSrc->a[iRight].pTab );
90385 pE1 = sqlite3CreateColumnExpr(db, pSrc, iLeft, iColLeft);
90386 pE2 = sqlite3CreateColumnExpr(db, pSrc, iRight, iColRight);
90388 pEq = sqlite3PExpr(pParse, TK_EQ, pE1, pE2, 0);
90389 if( pEq && isOuterJoin ){
90390 ExprSetProperty(pEq, EP_FromJoin);
90391 assert( !ExprHasAnyProperty(pEq, EP_TokenOnly|EP_Reduced) );
90392 ExprSetIrreducible(pEq);
90393 pEq->iRightJoinTable = (i16)pE2->iTable;
90395 *ppWhere = sqlite3ExprAnd(db, *ppWhere, pEq);
90399 ** Set the EP_FromJoin property on all terms of the given expression.
90400 ** And set the Expr.iRightJoinTable to iTable for every term in the
90401 ** expression.
90403 ** The EP_FromJoin property is used on terms of an expression to tell
90404 ** the LEFT OUTER JOIN processing logic that this term is part of the
90405 ** join restriction specified in the ON or USING clause and not a part
90406 ** of the more general WHERE clause. These terms are moved over to the
90407 ** WHERE clause during join processing but we need to remember that they
90408 ** originated in the ON or USING clause.
90410 ** The Expr.iRightJoinTable tells the WHERE clause processing that the
90411 ** expression depends on table iRightJoinTable even if that table is not
90412 ** explicitly mentioned in the expression. That information is needed
90413 ** for cases like this:
90415 ** SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.b AND t1.x=5
90417 ** The where clause needs to defer the handling of the t1.x=5
90418 ** term until after the t2 loop of the join. In that way, a
90419 ** NULL t2 row will be inserted whenever t1.x!=5. If we do not
90420 ** defer the handling of t1.x=5, it will be processed immediately
90421 ** after the t1 loop and rows with t1.x!=5 will never appear in
90422 ** the output, which is incorrect.
90424 static void setJoinExpr(Expr *p, int iTable){
90425 while( p ){
90426 ExprSetProperty(p, EP_FromJoin);
90427 assert( !ExprHasAnyProperty(p, EP_TokenOnly|EP_Reduced) );
90428 ExprSetIrreducible(p);
90429 p->iRightJoinTable = (i16)iTable;
90430 setJoinExpr(p->pLeft, iTable);
90431 p = p->pRight;
90436 ** This routine processes the join information for a SELECT statement.
90437 ** ON and USING clauses are converted into extra terms of the WHERE clause.
90438 ** NATURAL joins also create extra WHERE clause terms.
90440 ** The terms of a FROM clause are contained in the Select.pSrc structure.
90441 ** The left most table is the first entry in Select.pSrc. The right-most
90442 ** table is the last entry. The join operator is held in the entry to
90443 ** the left. Thus entry 0 contains the join operator for the join between
90444 ** entries 0 and 1. Any ON or USING clauses associated with the join are
90445 ** also attached to the left entry.
90447 ** This routine returns the number of errors encountered.
90449 static int sqliteProcessJoin(Parse *pParse, Select *p){
90450 SrcList *pSrc; /* All tables in the FROM clause */
90451 int i, j; /* Loop counters */
90452 struct SrcList_item *pLeft; /* Left table being joined */
90453 struct SrcList_item *pRight; /* Right table being joined */
90455 pSrc = p->pSrc;
90456 pLeft = &pSrc->a[0];
90457 pRight = &pLeft[1];
90458 for(i=0; i<pSrc->nSrc-1; i++, pRight++, pLeft++){
90459 Table *pLeftTab = pLeft->pTab;
90460 Table *pRightTab = pRight->pTab;
90461 int isOuter;
90463 if( NEVER(pLeftTab==0 || pRightTab==0) ) continue;
90464 isOuter = (pRight->jointype & JT_OUTER)!=0;
90466 /* When the NATURAL keyword is present, add WHERE clause terms for
90467 ** every column that the two tables have in common.
90469 if( pRight->jointype & JT_NATURAL ){
90470 if( pRight->pOn || pRight->pUsing ){
90471 sqlite3ErrorMsg(pParse, "a NATURAL join may not have "
90472 "an ON or USING clause", 0);
90473 return 1;
90475 for(j=0; j<pRightTab->nCol; j++){
90476 char *zName; /* Name of column in the right table */
90477 int iLeft; /* Matching left table */
90478 int iLeftCol; /* Matching column in the left table */
90480 zName = pRightTab->aCol[j].zName;
90481 if( tableAndColumnIndex(pSrc, i+1, zName, &iLeft, &iLeftCol) ){
90482 addWhereTerm(pParse, pSrc, iLeft, iLeftCol, i+1, j,
90483 isOuter, &p->pWhere);
90488 /* Disallow both ON and USING clauses in the same join
90490 if( pRight->pOn && pRight->pUsing ){
90491 sqlite3ErrorMsg(pParse, "cannot have both ON and USING "
90492 "clauses in the same join");
90493 return 1;
90496 /* Add the ON clause to the end of the WHERE clause, connected by
90497 ** an AND operator.
90499 if( pRight->pOn ){
90500 if( isOuter ) setJoinExpr(pRight->pOn, pRight->iCursor);
90501 p->pWhere = sqlite3ExprAnd(pParse->db, p->pWhere, pRight->pOn);
90502 pRight->pOn = 0;
90505 /* Create extra terms on the WHERE clause for each column named
90506 ** in the USING clause. Example: If the two tables to be joined are
90507 ** A and B and the USING clause names X, Y, and Z, then add this
90508 ** to the WHERE clause: A.X=B.X AND A.Y=B.Y AND A.Z=B.Z
90509 ** Report an error if any column mentioned in the USING clause is
90510 ** not contained in both tables to be joined.
90512 if( pRight->pUsing ){
90513 IdList *pList = pRight->pUsing;
90514 for(j=0; j<pList->nId; j++){
90515 char *zName; /* Name of the term in the USING clause */
90516 int iLeft; /* Table on the left with matching column name */
90517 int iLeftCol; /* Column number of matching column on the left */
90518 int iRightCol; /* Column number of matching column on the right */
90520 zName = pList->a[j].zName;
90521 iRightCol = columnIndex(pRightTab, zName);
90522 if( iRightCol<0
90523 || !tableAndColumnIndex(pSrc, i+1, zName, &iLeft, &iLeftCol)
90525 sqlite3ErrorMsg(pParse, "cannot join using column %s - column "
90526 "not present in both tables", zName);
90527 return 1;
90529 addWhereTerm(pParse, pSrc, iLeft, iLeftCol, i+1, iRightCol,
90530 isOuter, &p->pWhere);
90534 return 0;
90538 ** Insert code into "v" that will push the record on the top of the
90539 ** stack into the sorter.
90541 static void pushOntoSorter(
90542 Parse *pParse, /* Parser context */
90543 ExprList *pOrderBy, /* The ORDER BY clause */
90544 Select *pSelect, /* The whole SELECT statement */
90545 int regData /* Register holding data to be sorted */
90547 Vdbe *v = pParse->pVdbe;
90548 int nExpr = pOrderBy->nExpr;
90549 int regBase = sqlite3GetTempRange(pParse, nExpr+2);
90550 int regRecord = sqlite3GetTempReg(pParse);
90551 sqlite3ExprCacheClear(pParse);
90552 sqlite3ExprCodeExprList(pParse, pOrderBy, regBase, 0);
90553 sqlite3VdbeAddOp2(v, OP_Sequence, pOrderBy->iECursor, regBase+nExpr);
90554 sqlite3ExprCodeMove(pParse, regData, regBase+nExpr+1, 1);
90555 sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nExpr + 2, regRecord);
90556 sqlite3VdbeAddOp2(v, OP_IdxInsert, pOrderBy->iECursor, regRecord);
90557 sqlite3ReleaseTempReg(pParse, regRecord);
90558 sqlite3ReleaseTempRange(pParse, regBase, nExpr+2);
90559 if( pSelect->iLimit ){
90560 int addr1, addr2;
90561 int iLimit;
90562 if( pSelect->iOffset ){
90563 iLimit = pSelect->iOffset+1;
90564 }else{
90565 iLimit = pSelect->iLimit;
90567 addr1 = sqlite3VdbeAddOp1(v, OP_IfZero, iLimit);
90568 sqlite3VdbeAddOp2(v, OP_AddImm, iLimit, -1);
90569 addr2 = sqlite3VdbeAddOp0(v, OP_Goto);
90570 sqlite3VdbeJumpHere(v, addr1);
90571 sqlite3VdbeAddOp1(v, OP_Last, pOrderBy->iECursor);
90572 sqlite3VdbeAddOp1(v, OP_Delete, pOrderBy->iECursor);
90573 sqlite3VdbeJumpHere(v, addr2);
90578 ** Add code to implement the OFFSET
90580 static void codeOffset(
90581 Vdbe *v, /* Generate code into this VM */
90582 Select *p, /* The SELECT statement being coded */
90583 int iContinue /* Jump here to skip the current record */
90585 if( p->iOffset && iContinue!=0 ){
90586 int addr;
90587 sqlite3VdbeAddOp2(v, OP_AddImm, p->iOffset, -1);
90588 addr = sqlite3VdbeAddOp1(v, OP_IfNeg, p->iOffset);
90589 sqlite3VdbeAddOp2(v, OP_Goto, 0, iContinue);
90590 VdbeComment((v, "skip OFFSET records"));
90591 sqlite3VdbeJumpHere(v, addr);
90596 ** Add code that will check to make sure the N registers starting at iMem
90597 ** form a distinct entry. iTab is a sorting index that holds previously
90598 ** seen combinations of the N values. A new entry is made in iTab
90599 ** if the current N values are new.
90601 ** A jump to addrRepeat is made and the N+1 values are popped from the
90602 ** stack if the top N elements are not distinct.
90604 static void codeDistinct(
90605 Parse *pParse, /* Parsing and code generating context */
90606 int iTab, /* A sorting index used to test for distinctness */
90607 int addrRepeat, /* Jump to here if not distinct */
90608 int N, /* Number of elements */
90609 int iMem /* First element */
90611 Vdbe *v;
90612 int r1;
90614 v = pParse->pVdbe;
90615 r1 = sqlite3GetTempReg(pParse);
90616 sqlite3VdbeAddOp4Int(v, OP_Found, iTab, addrRepeat, iMem, N);
90617 sqlite3VdbeAddOp3(v, OP_MakeRecord, iMem, N, r1);
90618 sqlite3VdbeAddOp2(v, OP_IdxInsert, iTab, r1);
90619 sqlite3ReleaseTempReg(pParse, r1);
90622 #ifndef SQLITE_OMIT_SUBQUERY
90624 ** Generate an error message when a SELECT is used within a subexpression
90625 ** (example: "a IN (SELECT * FROM table)") but it has more than 1 result
90626 ** column. We do this in a subroutine because the error used to occur
90627 ** in multiple places. (The error only occurs in one place now, but we
90628 ** retain the subroutine to minimize code disruption.)
90630 static int checkForMultiColumnSelectError(
90631 Parse *pParse, /* Parse context. */
90632 SelectDest *pDest, /* Destination of SELECT results */
90633 int nExpr /* Number of result columns returned by SELECT */
90635 int eDest = pDest->eDest;
90636 if( nExpr>1 && (eDest==SRT_Mem || eDest==SRT_Set) ){
90637 sqlite3ErrorMsg(pParse, "only a single result allowed for "
90638 "a SELECT that is part of an expression");
90639 return 1;
90640 }else{
90641 return 0;
90644 #endif
90647 ** This routine generates the code for the inside of the inner loop
90648 ** of a SELECT.
90650 ** If srcTab and nColumn are both zero, then the pEList expressions
90651 ** are evaluated in order to get the data for this row. If nColumn>0
90652 ** then data is pulled from srcTab and pEList is used only to get the
90653 ** datatypes for each column.
90655 static void selectInnerLoop(
90656 Parse *pParse, /* The parser context */
90657 Select *p, /* The complete select statement being coded */
90658 ExprList *pEList, /* List of values being extracted */
90659 int srcTab, /* Pull data from this table */
90660 int nColumn, /* Number of columns in the source table */
90661 ExprList *pOrderBy, /* If not NULL, sort results using this key */
90662 int distinct, /* If >=0, make sure results are distinct */
90663 SelectDest *pDest, /* How to dispose of the results */
90664 int iContinue, /* Jump here to continue with next row */
90665 int iBreak /* Jump here to break out of the inner loop */
90667 Vdbe *v = pParse->pVdbe;
90668 int i;
90669 int hasDistinct; /* True if the DISTINCT keyword is present */
90670 int regResult; /* Start of memory holding result set */
90671 int eDest = pDest->eDest; /* How to dispose of results */
90672 int iParm = pDest->iParm; /* First argument to disposal method */
90673 int nResultCol; /* Number of result columns */
90675 assert( v );
90676 if( NEVER(v==0) ) return;
90677 assert( pEList!=0 );
90678 hasDistinct = distinct>=0;
90679 if( pOrderBy==0 && !hasDistinct ){
90680 codeOffset(v, p, iContinue);
90683 /* Pull the requested columns.
90685 if( nColumn>0 ){
90686 nResultCol = nColumn;
90687 }else{
90688 nResultCol = pEList->nExpr;
90690 if( pDest->iMem==0 ){
90691 pDest->iMem = pParse->nMem+1;
90692 pDest->nMem = nResultCol;
90693 pParse->nMem += nResultCol;
90694 }else{
90695 assert( pDest->nMem==nResultCol );
90697 regResult = pDest->iMem;
90698 if( nColumn>0 ){
90699 for(i=0; i<nColumn; i++){
90700 sqlite3VdbeAddOp3(v, OP_Column, srcTab, i, regResult+i);
90702 }else if( eDest!=SRT_Exists ){
90703 /* If the destination is an EXISTS(...) expression, the actual
90704 ** values returned by the SELECT are not required.
90706 sqlite3ExprCacheClear(pParse);
90707 sqlite3ExprCodeExprList(pParse, pEList, regResult, eDest==SRT_Output);
90709 nColumn = nResultCol;
90711 /* If the DISTINCT keyword was present on the SELECT statement
90712 ** and this row has been seen before, then do not make this row
90713 ** part of the result.
90715 if( hasDistinct ){
90716 assert( pEList!=0 );
90717 assert( pEList->nExpr==nColumn );
90718 codeDistinct(pParse, distinct, iContinue, nColumn, regResult);
90719 if( pOrderBy==0 ){
90720 codeOffset(v, p, iContinue);
90724 switch( eDest ){
90725 /* In this mode, write each query result to the key of the temporary
90726 ** table iParm.
90728 #ifndef SQLITE_OMIT_COMPOUND_SELECT
90729 case SRT_Union: {
90730 int r1;
90731 r1 = sqlite3GetTempReg(pParse);
90732 sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nColumn, r1);
90733 sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, r1);
90734 sqlite3ReleaseTempReg(pParse, r1);
90735 break;
90738 /* Construct a record from the query result, but instead of
90739 ** saving that record, use it as a key to delete elements from
90740 ** the temporary table iParm.
90742 case SRT_Except: {
90743 sqlite3VdbeAddOp3(v, OP_IdxDelete, iParm, regResult, nColumn);
90744 break;
90746 #endif
90748 /* Store the result as data using a unique key.
90750 case SRT_Table:
90751 case SRT_EphemTab: {
90752 int r1 = sqlite3GetTempReg(pParse);
90753 testcase( eDest==SRT_Table );
90754 testcase( eDest==SRT_EphemTab );
90755 sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nColumn, r1);
90756 if( pOrderBy ){
90757 pushOntoSorter(pParse, pOrderBy, p, r1);
90758 }else{
90759 int r2 = sqlite3GetTempReg(pParse);
90760 sqlite3VdbeAddOp2(v, OP_NewRowid, iParm, r2);
90761 sqlite3VdbeAddOp3(v, OP_Insert, iParm, r1, r2);
90762 sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
90763 sqlite3ReleaseTempReg(pParse, r2);
90765 sqlite3ReleaseTempReg(pParse, r1);
90766 break;
90769 #ifndef SQLITE_OMIT_SUBQUERY
90770 /* If we are creating a set for an "expr IN (SELECT ...)" construct,
90771 ** then there should be a single item on the stack. Write this
90772 ** item into the set table with bogus data.
90774 case SRT_Set: {
90775 assert( nColumn==1 );
90776 p->affinity = sqlite3CompareAffinity(pEList->a[0].pExpr, pDest->affinity);
90777 if( pOrderBy ){
90778 /* At first glance you would think we could optimize out the
90779 ** ORDER BY in this case since the order of entries in the set
90780 ** does not matter. But there might be a LIMIT clause, in which
90781 ** case the order does matter */
90782 pushOntoSorter(pParse, pOrderBy, p, regResult);
90783 }else{
90784 int r1 = sqlite3GetTempReg(pParse);
90785 sqlite3VdbeAddOp4(v, OP_MakeRecord, regResult, 1, r1, &p->affinity, 1);
90786 sqlite3ExprCacheAffinityChange(pParse, regResult, 1);
90787 sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, r1);
90788 sqlite3ReleaseTempReg(pParse, r1);
90790 break;
90793 /* If any row exist in the result set, record that fact and abort.
90795 case SRT_Exists: {
90796 sqlite3VdbeAddOp2(v, OP_Integer, 1, iParm);
90797 /* The LIMIT clause will terminate the loop for us */
90798 break;
90801 /* If this is a scalar select that is part of an expression, then
90802 ** store the results in the appropriate memory cell and break out
90803 ** of the scan loop.
90805 case SRT_Mem: {
90806 assert( nColumn==1 );
90807 if( pOrderBy ){
90808 pushOntoSorter(pParse, pOrderBy, p, regResult);
90809 }else{
90810 sqlite3ExprCodeMove(pParse, regResult, iParm, 1);
90811 /* The LIMIT clause will jump out of the loop for us */
90813 break;
90815 #endif /* #ifndef SQLITE_OMIT_SUBQUERY */
90817 /* Send the data to the callback function or to a subroutine. In the
90818 ** case of a subroutine, the subroutine itself is responsible for
90819 ** popping the data from the stack.
90821 case SRT_Coroutine:
90822 case SRT_Output: {
90823 testcase( eDest==SRT_Coroutine );
90824 testcase( eDest==SRT_Output );
90825 if( pOrderBy ){
90826 int r1 = sqlite3GetTempReg(pParse);
90827 sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nColumn, r1);
90828 pushOntoSorter(pParse, pOrderBy, p, r1);
90829 sqlite3ReleaseTempReg(pParse, r1);
90830 }else if( eDest==SRT_Coroutine ){
90831 sqlite3VdbeAddOp1(v, OP_Yield, pDest->iParm);
90832 }else{
90833 sqlite3VdbeAddOp2(v, OP_ResultRow, regResult, nColumn);
90834 sqlite3ExprCacheAffinityChange(pParse, regResult, nColumn);
90836 break;
90839 #if !defined(SQLITE_OMIT_TRIGGER)
90840 /* Discard the results. This is used for SELECT statements inside
90841 ** the body of a TRIGGER. The purpose of such selects is to call
90842 ** user-defined functions that have side effects. We do not care
90843 ** about the actual results of the select.
90845 default: {
90846 assert( eDest==SRT_Discard );
90847 break;
90849 #endif
90852 /* Jump to the end of the loop if the LIMIT is reached. Except, if
90853 ** there is a sorter, in which case the sorter has already limited
90854 ** the output for us.
90856 if( pOrderBy==0 && p->iLimit ){
90857 sqlite3VdbeAddOp3(v, OP_IfZero, p->iLimit, iBreak, -1);
90862 ** Given an expression list, generate a KeyInfo structure that records
90863 ** the collating sequence for each expression in that expression list.
90865 ** If the ExprList is an ORDER BY or GROUP BY clause then the resulting
90866 ** KeyInfo structure is appropriate for initializing a virtual index to
90867 ** implement that clause. If the ExprList is the result set of a SELECT
90868 ** then the KeyInfo structure is appropriate for initializing a virtual
90869 ** index to implement a DISTINCT test.
90871 ** Space to hold the KeyInfo structure is obtain from malloc. The calling
90872 ** function is responsible for seeing that this structure is eventually
90873 ** freed. Add the KeyInfo structure to the P4 field of an opcode using
90874 ** P4_KEYINFO_HANDOFF is the usual way of dealing with this.
90876 static KeyInfo *keyInfoFromExprList(Parse *pParse, ExprList *pList){
90877 sqlite3 *db = pParse->db;
90878 int nExpr;
90879 KeyInfo *pInfo;
90880 struct ExprList_item *pItem;
90881 int i;
90883 nExpr = pList->nExpr;
90884 pInfo = sqlite3DbMallocZero(db, sizeof(*pInfo) + nExpr*(sizeof(CollSeq*)+1) );
90885 if( pInfo ){
90886 pInfo->aSortOrder = (u8*)&pInfo->aColl[nExpr];
90887 pInfo->nField = (u16)nExpr;
90888 pInfo->enc = ENC(db);
90889 pInfo->db = db;
90890 for(i=0, pItem=pList->a; i<nExpr; i++, pItem++){
90891 CollSeq *pColl;
90892 pColl = sqlite3ExprCollSeq(pParse, pItem->pExpr);
90893 if( !pColl ){
90894 pColl = db->pDfltColl;
90896 pInfo->aColl[i] = pColl;
90897 pInfo->aSortOrder[i] = pItem->sortOrder;
90900 return pInfo;
90903 #ifndef SQLITE_OMIT_COMPOUND_SELECT
90905 ** Name of the connection operator, used for error messages.
90907 static const char *selectOpName(int id){
90908 char *z;
90909 switch( id ){
90910 case TK_ALL: z = "UNION ALL"; break;
90911 case TK_INTERSECT: z = "INTERSECT"; break;
90912 case TK_EXCEPT: z = "EXCEPT"; break;
90913 default: z = "UNION"; break;
90915 return z;
90917 #endif /* SQLITE_OMIT_COMPOUND_SELECT */
90919 #ifndef SQLITE_OMIT_EXPLAIN
90921 ** Unless an "EXPLAIN QUERY PLAN" command is being processed, this function
90922 ** is a no-op. Otherwise, it adds a single row of output to the EQP result,
90923 ** where the caption is of the form:
90925 ** "USE TEMP B-TREE FOR xxx"
90927 ** where xxx is one of "DISTINCT", "ORDER BY" or "GROUP BY". Exactly which
90928 ** is determined by the zUsage argument.
90930 static void explainTempTable(Parse *pParse, const char *zUsage){
90931 if( pParse->explain==2 ){
90932 Vdbe *v = pParse->pVdbe;
90933 char *zMsg = sqlite3MPrintf(pParse->db, "USE TEMP B-TREE FOR %s", zUsage);
90934 sqlite3VdbeAddOp4(v, OP_Explain, pParse->iSelectId, 0, 0, zMsg, P4_DYNAMIC);
90939 ** Assign expression b to lvalue a. A second, no-op, version of this macro
90940 ** is provided when SQLITE_OMIT_EXPLAIN is defined. This allows the code
90941 ** in sqlite3Select() to assign values to structure member variables that
90942 ** only exist if SQLITE_OMIT_EXPLAIN is not defined without polluting the
90943 ** code with #ifndef directives.
90945 # define explainSetInteger(a, b) a = b
90947 #else
90948 /* No-op versions of the explainXXX() functions and macros. */
90949 # define explainTempTable(y,z)
90950 # define explainSetInteger(y,z)
90951 #endif
90953 #if !defined(SQLITE_OMIT_EXPLAIN) && !defined(SQLITE_OMIT_COMPOUND_SELECT)
90955 ** Unless an "EXPLAIN QUERY PLAN" command is being processed, this function
90956 ** is a no-op. Otherwise, it adds a single row of output to the EQP result,
90957 ** where the caption is of one of the two forms:
90959 ** "COMPOSITE SUBQUERIES iSub1 and iSub2 (op)"
90960 ** "COMPOSITE SUBQUERIES iSub1 and iSub2 USING TEMP B-TREE (op)"
90962 ** where iSub1 and iSub2 are the integers passed as the corresponding
90963 ** function parameters, and op is the text representation of the parameter
90964 ** of the same name. The parameter "op" must be one of TK_UNION, TK_EXCEPT,
90965 ** TK_INTERSECT or TK_ALL. The first form is used if argument bUseTmp is
90966 ** false, or the second form if it is true.
90968 static void explainComposite(
90969 Parse *pParse, /* Parse context */
90970 int op, /* One of TK_UNION, TK_EXCEPT etc. */
90971 int iSub1, /* Subquery id 1 */
90972 int iSub2, /* Subquery id 2 */
90973 int bUseTmp /* True if a temp table was used */
90975 assert( op==TK_UNION || op==TK_EXCEPT || op==TK_INTERSECT || op==TK_ALL );
90976 if( pParse->explain==2 ){
90977 Vdbe *v = pParse->pVdbe;
90978 char *zMsg = sqlite3MPrintf(
90979 pParse->db, "COMPOUND SUBQUERIES %d AND %d %s(%s)", iSub1, iSub2,
90980 bUseTmp?"USING TEMP B-TREE ":"", selectOpName(op)
90982 sqlite3VdbeAddOp4(v, OP_Explain, pParse->iSelectId, 0, 0, zMsg, P4_DYNAMIC);
90985 #else
90986 /* No-op versions of the explainXXX() functions and macros. */
90987 # define explainComposite(v,w,x,y,z)
90988 #endif
90991 ** If the inner loop was generated using a non-null pOrderBy argument,
90992 ** then the results were placed in a sorter. After the loop is terminated
90993 ** we need to run the sorter and output the results. The following
90994 ** routine generates the code needed to do that.
90996 static void generateSortTail(
90997 Parse *pParse, /* Parsing context */
90998 Select *p, /* The SELECT statement */
90999 Vdbe *v, /* Generate code into this VDBE */
91000 int nColumn, /* Number of columns of data */
91001 SelectDest *pDest /* Write the sorted results here */
91003 int addrBreak = sqlite3VdbeMakeLabel(v); /* Jump here to exit loop */
91004 int addrContinue = sqlite3VdbeMakeLabel(v); /* Jump here for next cycle */
91005 int addr;
91006 int iTab;
91007 int pseudoTab = 0;
91008 ExprList *pOrderBy = p->pOrderBy;
91010 int eDest = pDest->eDest;
91011 int iParm = pDest->iParm;
91013 int regRow;
91014 int regRowid;
91016 iTab = pOrderBy->iECursor;
91017 regRow = sqlite3GetTempReg(pParse);
91018 if( eDest==SRT_Output || eDest==SRT_Coroutine ){
91019 pseudoTab = pParse->nTab++;
91020 sqlite3VdbeAddOp3(v, OP_OpenPseudo, pseudoTab, regRow, nColumn);
91021 regRowid = 0;
91022 }else{
91023 regRowid = sqlite3GetTempReg(pParse);
91025 addr = 1 + sqlite3VdbeAddOp2(v, OP_Sort, iTab, addrBreak);
91026 codeOffset(v, p, addrContinue);
91027 sqlite3VdbeAddOp3(v, OP_Column, iTab, pOrderBy->nExpr + 1, regRow);
91028 switch( eDest ){
91029 case SRT_Table:
91030 case SRT_EphemTab: {
91031 testcase( eDest==SRT_Table );
91032 testcase( eDest==SRT_EphemTab );
91033 sqlite3VdbeAddOp2(v, OP_NewRowid, iParm, regRowid);
91034 sqlite3VdbeAddOp3(v, OP_Insert, iParm, regRow, regRowid);
91035 sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
91036 break;
91038 #ifndef SQLITE_OMIT_SUBQUERY
91039 case SRT_Set: {
91040 assert( nColumn==1 );
91041 sqlite3VdbeAddOp4(v, OP_MakeRecord, regRow, 1, regRowid, &p->affinity, 1);
91042 sqlite3ExprCacheAffinityChange(pParse, regRow, 1);
91043 sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, regRowid);
91044 break;
91046 case SRT_Mem: {
91047 assert( nColumn==1 );
91048 sqlite3ExprCodeMove(pParse, regRow, iParm, 1);
91049 /* The LIMIT clause will terminate the loop for us */
91050 break;
91052 #endif
91053 default: {
91054 int i;
91055 assert( eDest==SRT_Output || eDest==SRT_Coroutine );
91056 testcase( eDest==SRT_Output );
91057 testcase( eDest==SRT_Coroutine );
91058 for(i=0; i<nColumn; i++){
91059 assert( regRow!=pDest->iMem+i );
91060 sqlite3VdbeAddOp3(v, OP_Column, pseudoTab, i, pDest->iMem+i);
91061 if( i==0 ){
91062 sqlite3VdbeChangeP5(v, OPFLAG_CLEARCACHE);
91065 if( eDest==SRT_Output ){
91066 sqlite3VdbeAddOp2(v, OP_ResultRow, pDest->iMem, nColumn);
91067 sqlite3ExprCacheAffinityChange(pParse, pDest->iMem, nColumn);
91068 }else{
91069 sqlite3VdbeAddOp1(v, OP_Yield, pDest->iParm);
91071 break;
91074 sqlite3ReleaseTempReg(pParse, regRow);
91075 sqlite3ReleaseTempReg(pParse, regRowid);
91077 /* The bottom of the loop
91079 sqlite3VdbeResolveLabel(v, addrContinue);
91080 sqlite3VdbeAddOp2(v, OP_Next, iTab, addr);
91081 sqlite3VdbeResolveLabel(v, addrBreak);
91082 if( eDest==SRT_Output || eDest==SRT_Coroutine ){
91083 sqlite3VdbeAddOp2(v, OP_Close, pseudoTab, 0);
91088 ** Return a pointer to a string containing the 'declaration type' of the
91089 ** expression pExpr. The string may be treated as static by the caller.
91091 ** The declaration type is the exact datatype definition extracted from the
91092 ** original CREATE TABLE statement if the expression is a column. The
91093 ** declaration type for a ROWID field is INTEGER. Exactly when an expression
91094 ** is considered a column can be complex in the presence of subqueries. The
91095 ** result-set expression in all of the following SELECT statements is
91096 ** considered a column by this function.
91098 ** SELECT col FROM tbl;
91099 ** SELECT (SELECT col FROM tbl;
91100 ** SELECT (SELECT col FROM tbl);
91101 ** SELECT abc FROM (SELECT col AS abc FROM tbl);
91103 ** The declaration type for any expression other than a column is NULL.
91105 static const char *columnType(
91106 NameContext *pNC,
91107 Expr *pExpr,
91108 const char **pzOriginDb,
91109 const char **pzOriginTab,
91110 const char **pzOriginCol
91112 char const *zType = 0;
91113 char const *zOriginDb = 0;
91114 char const *zOriginTab = 0;
91115 char const *zOriginCol = 0;
91116 int j;
91117 if( NEVER(pExpr==0) || pNC->pSrcList==0 ) return 0;
91119 switch( pExpr->op ){
91120 case TK_AGG_COLUMN:
91121 case TK_COLUMN: {
91122 /* The expression is a column. Locate the table the column is being
91123 ** extracted from in NameContext.pSrcList. This table may be real
91124 ** database table or a subquery.
91126 Table *pTab = 0; /* Table structure column is extracted from */
91127 Select *pS = 0; /* Select the column is extracted from */
91128 int iCol = pExpr->iColumn; /* Index of column in pTab */
91129 testcase( pExpr->op==TK_AGG_COLUMN );
91130 testcase( pExpr->op==TK_COLUMN );
91131 while( pNC && !pTab ){
91132 SrcList *pTabList = pNC->pSrcList;
91133 for(j=0;j<pTabList->nSrc && pTabList->a[j].iCursor!=pExpr->iTable;j++);
91134 if( j<pTabList->nSrc ){
91135 pTab = pTabList->a[j].pTab;
91136 pS = pTabList->a[j].pSelect;
91137 }else{
91138 pNC = pNC->pNext;
91142 if( pTab==0 ){
91143 /* At one time, code such as "SELECT new.x" within a trigger would
91144 ** cause this condition to run. Since then, we have restructured how
91145 ** trigger code is generated and so this condition is no longer
91146 ** possible. However, it can still be true for statements like
91147 ** the following:
91149 ** CREATE TABLE t1(col INTEGER);
91150 ** SELECT (SELECT t1.col) FROM FROM t1;
91152 ** when columnType() is called on the expression "t1.col" in the
91153 ** sub-select. In this case, set the column type to NULL, even
91154 ** though it should really be "INTEGER".
91156 ** This is not a problem, as the column type of "t1.col" is never
91157 ** used. When columnType() is called on the expression
91158 ** "(SELECT t1.col)", the correct type is returned (see the TK_SELECT
91159 ** branch below. */
91160 break;
91163 assert( pTab && pExpr->pTab==pTab );
91164 if( pS ){
91165 /* The "table" is actually a sub-select or a view in the FROM clause
91166 ** of the SELECT statement. Return the declaration type and origin
91167 ** data for the result-set column of the sub-select.
91169 if( iCol>=0 && ALWAYS(iCol<pS->pEList->nExpr) ){
91170 /* If iCol is less than zero, then the expression requests the
91171 ** rowid of the sub-select or view. This expression is legal (see
91172 ** test case misc2.2.2) - it always evaluates to NULL.
91174 NameContext sNC;
91175 Expr *p = pS->pEList->a[iCol].pExpr;
91176 sNC.pSrcList = pS->pSrc;
91177 sNC.pNext = pNC;
91178 sNC.pParse = pNC->pParse;
91179 zType = columnType(&sNC, p, &zOriginDb, &zOriginTab, &zOriginCol);
91181 }else if( ALWAYS(pTab->pSchema) ){
91182 /* A real table */
91183 assert( !pS );
91184 if( iCol<0 ) iCol = pTab->iPKey;
91185 assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );
91186 if( iCol<0 ){
91187 zType = "INTEGER";
91188 zOriginCol = "rowid";
91189 }else{
91190 zType = pTab->aCol[iCol].zType;
91191 zOriginCol = pTab->aCol[iCol].zName;
91193 zOriginTab = pTab->zName;
91194 if( pNC->pParse ){
91195 int iDb = sqlite3SchemaToIndex(pNC->pParse->db, pTab->pSchema);
91196 zOriginDb = pNC->pParse->db->aDb[iDb].zName;
91199 break;
91201 #ifndef SQLITE_OMIT_SUBQUERY
91202 case TK_SELECT: {
91203 /* The expression is a sub-select. Return the declaration type and
91204 ** origin info for the single column in the result set of the SELECT
91205 ** statement.
91207 NameContext sNC;
91208 Select *pS = pExpr->x.pSelect;
91209 Expr *p = pS->pEList->a[0].pExpr;
91210 assert( ExprHasProperty(pExpr, EP_xIsSelect) );
91211 sNC.pSrcList = pS->pSrc;
91212 sNC.pNext = pNC;
91213 sNC.pParse = pNC->pParse;
91214 zType = columnType(&sNC, p, &zOriginDb, &zOriginTab, &zOriginCol);
91215 break;
91217 #endif
91220 if( pzOriginDb ){
91221 assert( pzOriginTab && pzOriginCol );
91222 *pzOriginDb = zOriginDb;
91223 *pzOriginTab = zOriginTab;
91224 *pzOriginCol = zOriginCol;
91226 return zType;
91230 ** Generate code that will tell the VDBE the declaration types of columns
91231 ** in the result set.
91233 static void generateColumnTypes(
91234 Parse *pParse, /* Parser context */
91235 SrcList *pTabList, /* List of tables */
91236 ExprList *pEList /* Expressions defining the result set */
91238 #ifndef SQLITE_OMIT_DECLTYPE
91239 Vdbe *v = pParse->pVdbe;
91240 int i;
91241 NameContext sNC;
91242 sNC.pSrcList = pTabList;
91243 sNC.pParse = pParse;
91244 for(i=0; i<pEList->nExpr; i++){
91245 Expr *p = pEList->a[i].pExpr;
91246 const char *zType;
91247 #ifdef SQLITE_ENABLE_COLUMN_METADATA
91248 const char *zOrigDb = 0;
91249 const char *zOrigTab = 0;
91250 const char *zOrigCol = 0;
91251 zType = columnType(&sNC, p, &zOrigDb, &zOrigTab, &zOrigCol);
91253 /* The vdbe must make its own copy of the column-type and other
91254 ** column specific strings, in case the schema is reset before this
91255 ** virtual machine is deleted.
91257 sqlite3VdbeSetColName(v, i, COLNAME_DATABASE, zOrigDb, SQLITE_TRANSIENT);
91258 sqlite3VdbeSetColName(v, i, COLNAME_TABLE, zOrigTab, SQLITE_TRANSIENT);
91259 sqlite3VdbeSetColName(v, i, COLNAME_COLUMN, zOrigCol, SQLITE_TRANSIENT);
91260 #else
91261 zType = columnType(&sNC, p, 0, 0, 0);
91262 #endif
91263 sqlite3VdbeSetColName(v, i, COLNAME_DECLTYPE, zType, SQLITE_TRANSIENT);
91265 #endif /* SQLITE_OMIT_DECLTYPE */
91269 ** Generate code that will tell the VDBE the names of columns
91270 ** in the result set. This information is used to provide the
91271 ** azCol[] values in the callback.
91273 static void generateColumnNames(
91274 Parse *pParse, /* Parser context */
91275 SrcList *pTabList, /* List of tables */
91276 ExprList *pEList /* Expressions defining the result set */
91278 Vdbe *v = pParse->pVdbe;
91279 int i, j;
91280 sqlite3 *db = pParse->db;
91281 int fullNames, shortNames;
91283 #ifndef SQLITE_OMIT_EXPLAIN
91284 /* If this is an EXPLAIN, skip this step */
91285 if( pParse->explain ){
91286 return;
91288 #endif
91290 if( pParse->colNamesSet || NEVER(v==0) || db->mallocFailed ) return;
91291 pParse->colNamesSet = 1;
91292 fullNames = (db->flags & SQLITE_FullColNames)!=0;
91293 shortNames = (db->flags & SQLITE_ShortColNames)!=0;
91294 sqlite3VdbeSetNumCols(v, pEList->nExpr);
91295 for(i=0; i<pEList->nExpr; i++){
91296 Expr *p;
91297 p = pEList->a[i].pExpr;
91298 if( NEVER(p==0) ) continue;
91299 if( pEList->a[i].zName ){
91300 char *zName = pEList->a[i].zName;
91301 sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, SQLITE_TRANSIENT);
91302 }else if( (p->op==TK_COLUMN || p->op==TK_AGG_COLUMN) && pTabList ){
91303 Table *pTab;
91304 char *zCol;
91305 int iCol = p->iColumn;
91306 for(j=0; ALWAYS(j<pTabList->nSrc); j++){
91307 if( pTabList->a[j].iCursor==p->iTable ) break;
91309 assert( j<pTabList->nSrc );
91310 pTab = pTabList->a[j].pTab;
91311 if( iCol<0 ) iCol = pTab->iPKey;
91312 assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );
91313 if( iCol<0 ){
91314 zCol = "rowid";
91315 }else{
91316 zCol = pTab->aCol[iCol].zName;
91318 if( !shortNames && !fullNames ){
91319 sqlite3VdbeSetColName(v, i, COLNAME_NAME,
91320 sqlite3DbStrDup(db, pEList->a[i].zSpan), SQLITE_DYNAMIC);
91321 }else if( fullNames ){
91322 char *zName = 0;
91323 zName = sqlite3MPrintf(db, "%s.%s", pTab->zName, zCol);
91324 sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, SQLITE_DYNAMIC);
91325 }else{
91326 sqlite3VdbeSetColName(v, i, COLNAME_NAME, zCol, SQLITE_TRANSIENT);
91328 }else{
91329 sqlite3VdbeSetColName(v, i, COLNAME_NAME,
91330 sqlite3DbStrDup(db, pEList->a[i].zSpan), SQLITE_DYNAMIC);
91333 generateColumnTypes(pParse, pTabList, pEList);
91337 ** Given a an expression list (which is really the list of expressions
91338 ** that form the result set of a SELECT statement) compute appropriate
91339 ** column names for a table that would hold the expression list.
91341 ** All column names will be unique.
91343 ** Only the column names are computed. Column.zType, Column.zColl,
91344 ** and other fields of Column are zeroed.
91346 ** Return SQLITE_OK on success. If a memory allocation error occurs,
91347 ** store NULL in *paCol and 0 in *pnCol and return SQLITE_NOMEM.
91349 static int selectColumnsFromExprList(
91350 Parse *pParse, /* Parsing context */
91351 ExprList *pEList, /* Expr list from which to derive column names */
91352 int *pnCol, /* Write the number of columns here */
91353 Column **paCol /* Write the new column list here */
91355 sqlite3 *db = pParse->db; /* Database connection */
91356 int i, j; /* Loop counters */
91357 int cnt; /* Index added to make the name unique */
91358 Column *aCol, *pCol; /* For looping over result columns */
91359 int nCol; /* Number of columns in the result set */
91360 Expr *p; /* Expression for a single result column */
91361 char *zName; /* Column name */
91362 int nName; /* Size of name in zName[] */
91364 *pnCol = nCol = pEList->nExpr;
91365 aCol = *paCol = sqlite3DbMallocZero(db, sizeof(aCol[0])*nCol);
91366 if( aCol==0 ) return SQLITE_NOMEM;
91367 for(i=0, pCol=aCol; i<nCol; i++, pCol++){
91368 /* Get an appropriate name for the column
91370 p = pEList->a[i].pExpr;
91371 assert( p->pRight==0 || ExprHasProperty(p->pRight, EP_IntValue)
91372 || p->pRight->u.zToken==0 || p->pRight->u.zToken[0]!=0 );
91373 if( (zName = pEList->a[i].zName)!=0 ){
91374 /* If the column contains an "AS <name>" phrase, use <name> as the name */
91375 zName = sqlite3DbStrDup(db, zName);
91376 }else{
91377 Expr *pColExpr = p; /* The expression that is the result column name */
91378 Table *pTab; /* Table associated with this expression */
91379 while( pColExpr->op==TK_DOT ) pColExpr = pColExpr->pRight;
91380 if( pColExpr->op==TK_COLUMN && ALWAYS(pColExpr->pTab!=0) ){
91381 /* For columns use the column name name */
91382 int iCol = pColExpr->iColumn;
91383 pTab = pColExpr->pTab;
91384 if( iCol<0 ) iCol = pTab->iPKey;
91385 zName = sqlite3MPrintf(db, "%s",
91386 iCol>=0 ? pTab->aCol[iCol].zName : "rowid");
91387 }else if( pColExpr->op==TK_ID ){
91388 assert( !ExprHasProperty(pColExpr, EP_IntValue) );
91389 zName = sqlite3MPrintf(db, "%s", pColExpr->u.zToken);
91390 }else{
91391 /* Use the original text of the column expression as its name */
91392 zName = sqlite3MPrintf(db, "%s", pEList->a[i].zSpan);
91395 if( db->mallocFailed ){
91396 sqlite3DbFree(db, zName);
91397 break;
91400 /* Make sure the column name is unique. If the name is not unique,
91401 ** append a integer to the name so that it becomes unique.
91403 nName = sqlite3Strlen30(zName);
91404 for(j=cnt=0; j<i; j++){
91405 if( sqlite3StrICmp(aCol[j].zName, zName)==0 ){
91406 char *zNewName;
91407 zName[nName] = 0;
91408 zNewName = sqlite3MPrintf(db, "%s:%d", zName, ++cnt);
91409 sqlite3DbFree(db, zName);
91410 zName = zNewName;
91411 j = -1;
91412 if( zName==0 ) break;
91415 pCol->zName = zName;
91417 if( db->mallocFailed ){
91418 for(j=0; j<i; j++){
91419 sqlite3DbFree(db, aCol[j].zName);
91421 sqlite3DbFree(db, aCol);
91422 *paCol = 0;
91423 *pnCol = 0;
91424 return SQLITE_NOMEM;
91426 return SQLITE_OK;
91430 ** Add type and collation information to a column list based on
91431 ** a SELECT statement.
91433 ** The column list presumably came from selectColumnNamesFromExprList().
91434 ** The column list has only names, not types or collations. This
91435 ** routine goes through and adds the types and collations.
91437 ** This routine requires that all identifiers in the SELECT
91438 ** statement be resolved.
91440 static void selectAddColumnTypeAndCollation(
91441 Parse *pParse, /* Parsing contexts */
91442 int nCol, /* Number of columns */
91443 Column *aCol, /* List of columns */
91444 Select *pSelect /* SELECT used to determine types and collations */
91446 sqlite3 *db = pParse->db;
91447 NameContext sNC;
91448 Column *pCol;
91449 CollSeq *pColl;
91450 int i;
91451 Expr *p;
91452 struct ExprList_item *a;
91454 assert( pSelect!=0 );
91455 assert( (pSelect->selFlags & SF_Resolved)!=0 );
91456 assert( nCol==pSelect->pEList->nExpr || db->mallocFailed );
91457 if( db->mallocFailed ) return;
91458 memset(&sNC, 0, sizeof(sNC));
91459 sNC.pSrcList = pSelect->pSrc;
91460 a = pSelect->pEList->a;
91461 for(i=0, pCol=aCol; i<nCol; i++, pCol++){
91462 p = a[i].pExpr;
91463 pCol->zType = sqlite3DbStrDup(db, columnType(&sNC, p, 0, 0, 0));
91464 pCol->affinity = sqlite3ExprAffinity(p);
91465 if( pCol->affinity==0 ) pCol->affinity = SQLITE_AFF_NONE;
91466 pColl = sqlite3ExprCollSeq(pParse, p);
91467 if( pColl ){
91468 pCol->zColl = sqlite3DbStrDup(db, pColl->zName);
91474 ** Given a SELECT statement, generate a Table structure that describes
91475 ** the result set of that SELECT.
91477 SQLITE_PRIVATE Table *sqlite3ResultSetOfSelect(Parse *pParse, Select *pSelect){
91478 Table *pTab;
91479 sqlite3 *db = pParse->db;
91480 int savedFlags;
91482 savedFlags = db->flags;
91483 db->flags &= ~SQLITE_FullColNames;
91484 db->flags |= SQLITE_ShortColNames;
91485 sqlite3SelectPrep(pParse, pSelect, 0);
91486 if( pParse->nErr ) return 0;
91487 while( pSelect->pPrior ) pSelect = pSelect->pPrior;
91488 db->flags = savedFlags;
91489 pTab = sqlite3DbMallocZero(db, sizeof(Table) );
91490 if( pTab==0 ){
91491 return 0;
91493 /* The sqlite3ResultSetOfSelect() is only used n contexts where lookaside
91494 ** is disabled */
91495 assert( db->lookaside.bEnabled==0 );
91496 pTab->nRef = 1;
91497 pTab->zName = 0;
91498 pTab->nRowEst = 1000000;
91499 selectColumnsFromExprList(pParse, pSelect->pEList, &pTab->nCol, &pTab->aCol);
91500 selectAddColumnTypeAndCollation(pParse, pTab->nCol, pTab->aCol, pSelect);
91501 pTab->iPKey = -1;
91502 if( db->mallocFailed ){
91503 sqlite3DeleteTable(db, pTab);
91504 return 0;
91506 return pTab;
91510 ** Get a VDBE for the given parser context. Create a new one if necessary.
91511 ** If an error occurs, return NULL and leave a message in pParse.
91513 SQLITE_PRIVATE Vdbe *sqlite3GetVdbe(Parse *pParse){
91514 Vdbe *v = pParse->pVdbe;
91515 if( v==0 ){
91516 v = pParse->pVdbe = sqlite3VdbeCreate(pParse->db);
91517 #ifndef SQLITE_OMIT_TRACE
91518 if( v ){
91519 sqlite3VdbeAddOp0(v, OP_Trace);
91521 #endif
91523 return v;
91528 ** Compute the iLimit and iOffset fields of the SELECT based on the
91529 ** pLimit and pOffset expressions. pLimit and pOffset hold the expressions
91530 ** that appear in the original SQL statement after the LIMIT and OFFSET
91531 ** keywords. Or NULL if those keywords are omitted. iLimit and iOffset
91532 ** are the integer memory register numbers for counters used to compute
91533 ** the limit and offset. If there is no limit and/or offset, then
91534 ** iLimit and iOffset are negative.
91536 ** This routine changes the values of iLimit and iOffset only if
91537 ** a limit or offset is defined by pLimit and pOffset. iLimit and
91538 ** iOffset should have been preset to appropriate default values
91539 ** (usually but not always -1) prior to calling this routine.
91540 ** Only if pLimit!=0 or pOffset!=0 do the limit registers get
91541 ** redefined. The UNION ALL operator uses this property to force
91542 ** the reuse of the same limit and offset registers across multiple
91543 ** SELECT statements.
91545 static void computeLimitRegisters(Parse *pParse, Select *p, int iBreak){
91546 Vdbe *v = 0;
91547 int iLimit = 0;
91548 int iOffset;
91549 int addr1, n;
91550 if( p->iLimit ) return;
91553 ** "LIMIT -1" always shows all rows. There is some
91554 ** contraversy about what the correct behavior should be.
91555 ** The current implementation interprets "LIMIT 0" to mean
91556 ** no rows.
91558 sqlite3ExprCacheClear(pParse);
91559 assert( p->pOffset==0 || p->pLimit!=0 );
91560 if( p->pLimit ){
91561 p->iLimit = iLimit = ++pParse->nMem;
91562 v = sqlite3GetVdbe(pParse);
91563 if( NEVER(v==0) ) return; /* VDBE should have already been allocated */
91564 if( sqlite3ExprIsInteger(p->pLimit, &n) ){
91565 sqlite3VdbeAddOp2(v, OP_Integer, n, iLimit);
91566 VdbeComment((v, "LIMIT counter"));
91567 if( n==0 ){
91568 sqlite3VdbeAddOp2(v, OP_Goto, 0, iBreak);
91569 }else{
91570 if( p->nSelectRow > (double)n ) p->nSelectRow = (double)n;
91572 }else{
91573 sqlite3ExprCode(pParse, p->pLimit, iLimit);
91574 sqlite3VdbeAddOp1(v, OP_MustBeInt, iLimit);
91575 VdbeComment((v, "LIMIT counter"));
91576 sqlite3VdbeAddOp2(v, OP_IfZero, iLimit, iBreak);
91578 if( p->pOffset ){
91579 p->iOffset = iOffset = ++pParse->nMem;
91580 pParse->nMem++; /* Allocate an extra register for limit+offset */
91581 sqlite3ExprCode(pParse, p->pOffset, iOffset);
91582 sqlite3VdbeAddOp1(v, OP_MustBeInt, iOffset);
91583 VdbeComment((v, "OFFSET counter"));
91584 addr1 = sqlite3VdbeAddOp1(v, OP_IfPos, iOffset);
91585 sqlite3VdbeAddOp2(v, OP_Integer, 0, iOffset);
91586 sqlite3VdbeJumpHere(v, addr1);
91587 sqlite3VdbeAddOp3(v, OP_Add, iLimit, iOffset, iOffset+1);
91588 VdbeComment((v, "LIMIT+OFFSET"));
91589 addr1 = sqlite3VdbeAddOp1(v, OP_IfPos, iLimit);
91590 sqlite3VdbeAddOp2(v, OP_Integer, -1, iOffset+1);
91591 sqlite3VdbeJumpHere(v, addr1);
91596 #ifndef SQLITE_OMIT_COMPOUND_SELECT
91598 ** Return the appropriate collating sequence for the iCol-th column of
91599 ** the result set for the compound-select statement "p". Return NULL if
91600 ** the column has no default collating sequence.
91602 ** The collating sequence for the compound select is taken from the
91603 ** left-most term of the select that has a collating sequence.
91605 static CollSeq *multiSelectCollSeq(Parse *pParse, Select *p, int iCol){
91606 CollSeq *pRet;
91607 if( p->pPrior ){
91608 pRet = multiSelectCollSeq(pParse, p->pPrior, iCol);
91609 }else{
91610 pRet = 0;
91612 assert( iCol>=0 );
91613 if( pRet==0 && iCol<p->pEList->nExpr ){
91614 pRet = sqlite3ExprCollSeq(pParse, p->pEList->a[iCol].pExpr);
91616 return pRet;
91618 #endif /* SQLITE_OMIT_COMPOUND_SELECT */
91620 /* Forward reference */
91621 static int multiSelectOrderBy(
91622 Parse *pParse, /* Parsing context */
91623 Select *p, /* The right-most of SELECTs to be coded */
91624 SelectDest *pDest /* What to do with query results */
91628 #ifndef SQLITE_OMIT_COMPOUND_SELECT
91630 ** This routine is called to process a compound query form from
91631 ** two or more separate queries using UNION, UNION ALL, EXCEPT, or
91632 ** INTERSECT
91634 ** "p" points to the right-most of the two queries. the query on the
91635 ** left is p->pPrior. The left query could also be a compound query
91636 ** in which case this routine will be called recursively.
91638 ** The results of the total query are to be written into a destination
91639 ** of type eDest with parameter iParm.
91641 ** Example 1: Consider a three-way compound SQL statement.
91643 ** SELECT a FROM t1 UNION SELECT b FROM t2 UNION SELECT c FROM t3
91645 ** This statement is parsed up as follows:
91647 ** SELECT c FROM t3
91648 ** |
91649 ** `-----> SELECT b FROM t2
91650 ** |
91651 ** `------> SELECT a FROM t1
91653 ** The arrows in the diagram above represent the Select.pPrior pointer.
91654 ** So if this routine is called with p equal to the t3 query, then
91655 ** pPrior will be the t2 query. p->op will be TK_UNION in this case.
91657 ** Notice that because of the way SQLite parses compound SELECTs, the
91658 ** individual selects always group from left to right.
91660 static int multiSelect(
91661 Parse *pParse, /* Parsing context */
91662 Select *p, /* The right-most of SELECTs to be coded */
91663 SelectDest *pDest /* What to do with query results */
91665 int rc = SQLITE_OK; /* Success code from a subroutine */
91666 Select *pPrior; /* Another SELECT immediately to our left */
91667 Vdbe *v; /* Generate code to this VDBE */
91668 SelectDest dest; /* Alternative data destination */
91669 Select *pDelete = 0; /* Chain of simple selects to delete */
91670 sqlite3 *db; /* Database connection */
91671 #ifndef SQLITE_OMIT_EXPLAIN
91672 int iSub1; /* EQP id of left-hand query */
91673 int iSub2; /* EQP id of right-hand query */
91674 #endif
91676 /* Make sure there is no ORDER BY or LIMIT clause on prior SELECTs. Only
91677 ** the last (right-most) SELECT in the series may have an ORDER BY or LIMIT.
91679 assert( p && p->pPrior ); /* Calling function guarantees this much */
91680 db = pParse->db;
91681 pPrior = p->pPrior;
91682 assert( pPrior->pRightmost!=pPrior );
91683 assert( pPrior->pRightmost==p->pRightmost );
91684 dest = *pDest;
91685 if( pPrior->pOrderBy ){
91686 sqlite3ErrorMsg(pParse,"ORDER BY clause should come after %s not before",
91687 selectOpName(p->op));
91688 rc = 1;
91689 goto multi_select_end;
91691 if( pPrior->pLimit ){
91692 sqlite3ErrorMsg(pParse,"LIMIT clause should come after %s not before",
91693 selectOpName(p->op));
91694 rc = 1;
91695 goto multi_select_end;
91698 v = sqlite3GetVdbe(pParse);
91699 assert( v!=0 ); /* The VDBE already created by calling function */
91701 /* Create the destination temporary table if necessary
91703 if( dest.eDest==SRT_EphemTab ){
91704 assert( p->pEList );
91705 sqlite3VdbeAddOp2(v, OP_OpenEphemeral, dest.iParm, p->pEList->nExpr);
91706 sqlite3VdbeChangeP5(v, BTREE_UNORDERED);
91707 dest.eDest = SRT_Table;
91710 /* Make sure all SELECTs in the statement have the same number of elements
91711 ** in their result sets.
91713 assert( p->pEList && pPrior->pEList );
91714 if( p->pEList->nExpr!=pPrior->pEList->nExpr ){
91715 sqlite3ErrorMsg(pParse, "SELECTs to the left and right of %s"
91716 " do not have the same number of result columns", selectOpName(p->op));
91717 rc = 1;
91718 goto multi_select_end;
91721 /* Compound SELECTs that have an ORDER BY clause are handled separately.
91723 if( p->pOrderBy ){
91724 return multiSelectOrderBy(pParse, p, pDest);
91727 /* Generate code for the left and right SELECT statements.
91729 switch( p->op ){
91730 case TK_ALL: {
91731 int addr = 0;
91732 int nLimit;
91733 assert( !pPrior->pLimit );
91734 pPrior->pLimit = p->pLimit;
91735 pPrior->pOffset = p->pOffset;
91736 explainSetInteger(iSub1, pParse->iNextSelectId);
91737 rc = sqlite3Select(pParse, pPrior, &dest);
91738 p->pLimit = 0;
91739 p->pOffset = 0;
91740 if( rc ){
91741 goto multi_select_end;
91743 p->pPrior = 0;
91744 p->iLimit = pPrior->iLimit;
91745 p->iOffset = pPrior->iOffset;
91746 if( p->iLimit ){
91747 addr = sqlite3VdbeAddOp1(v, OP_IfZero, p->iLimit);
91748 VdbeComment((v, "Jump ahead if LIMIT reached"));
91750 explainSetInteger(iSub2, pParse->iNextSelectId);
91751 rc = sqlite3Select(pParse, p, &dest);
91752 testcase( rc!=SQLITE_OK );
91753 pDelete = p->pPrior;
91754 p->pPrior = pPrior;
91755 p->nSelectRow += pPrior->nSelectRow;
91756 if( pPrior->pLimit
91757 && sqlite3ExprIsInteger(pPrior->pLimit, &nLimit)
91758 && p->nSelectRow > (double)nLimit
91760 p->nSelectRow = (double)nLimit;
91762 if( addr ){
91763 sqlite3VdbeJumpHere(v, addr);
91765 break;
91767 case TK_EXCEPT:
91768 case TK_UNION: {
91769 int unionTab; /* Cursor number of the temporary table holding result */
91770 u8 op = 0; /* One of the SRT_ operations to apply to self */
91771 int priorOp; /* The SRT_ operation to apply to prior selects */
91772 Expr *pLimit, *pOffset; /* Saved values of p->nLimit and p->nOffset */
91773 int addr;
91774 SelectDest uniondest;
91776 testcase( p->op==TK_EXCEPT );
91777 testcase( p->op==TK_UNION );
91778 priorOp = SRT_Union;
91779 if( dest.eDest==priorOp && ALWAYS(!p->pLimit &&!p->pOffset) ){
91780 /* We can reuse a temporary table generated by a SELECT to our
91781 ** right.
91783 assert( p->pRightmost!=p ); /* Can only happen for leftward elements
91784 ** of a 3-way or more compound */
91785 assert( p->pLimit==0 ); /* Not allowed on leftward elements */
91786 assert( p->pOffset==0 ); /* Not allowed on leftward elements */
91787 unionTab = dest.iParm;
91788 }else{
91789 /* We will need to create our own temporary table to hold the
91790 ** intermediate results.
91792 unionTab = pParse->nTab++;
91793 assert( p->pOrderBy==0 );
91794 addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, unionTab, 0);
91795 assert( p->addrOpenEphm[0] == -1 );
91796 p->addrOpenEphm[0] = addr;
91797 p->pRightmost->selFlags |= SF_UsesEphemeral;
91798 assert( p->pEList );
91801 /* Code the SELECT statements to our left
91803 assert( !pPrior->pOrderBy );
91804 sqlite3SelectDestInit(&uniondest, priorOp, unionTab);
91805 explainSetInteger(iSub1, pParse->iNextSelectId);
91806 rc = sqlite3Select(pParse, pPrior, &uniondest);
91807 if( rc ){
91808 goto multi_select_end;
91811 /* Code the current SELECT statement
91813 if( p->op==TK_EXCEPT ){
91814 op = SRT_Except;
91815 }else{
91816 assert( p->op==TK_UNION );
91817 op = SRT_Union;
91819 p->pPrior = 0;
91820 pLimit = p->pLimit;
91821 p->pLimit = 0;
91822 pOffset = p->pOffset;
91823 p->pOffset = 0;
91824 uniondest.eDest = op;
91825 explainSetInteger(iSub2, pParse->iNextSelectId);
91826 rc = sqlite3Select(pParse, p, &uniondest);
91827 testcase( rc!=SQLITE_OK );
91828 /* Query flattening in sqlite3Select() might refill p->pOrderBy.
91829 ** Be sure to delete p->pOrderBy, therefore, to avoid a memory leak. */
91830 sqlite3ExprListDelete(db, p->pOrderBy);
91831 pDelete = p->pPrior;
91832 p->pPrior = pPrior;
91833 p->pOrderBy = 0;
91834 if( p->op==TK_UNION ) p->nSelectRow += pPrior->nSelectRow;
91835 sqlite3ExprDelete(db, p->pLimit);
91836 p->pLimit = pLimit;
91837 p->pOffset = pOffset;
91838 p->iLimit = 0;
91839 p->iOffset = 0;
91841 /* Convert the data in the temporary table into whatever form
91842 ** it is that we currently need.
91844 assert( unionTab==dest.iParm || dest.eDest!=priorOp );
91845 if( dest.eDest!=priorOp ){
91846 int iCont, iBreak, iStart;
91847 assert( p->pEList );
91848 if( dest.eDest==SRT_Output ){
91849 Select *pFirst = p;
91850 while( pFirst->pPrior ) pFirst = pFirst->pPrior;
91851 generateColumnNames(pParse, 0, pFirst->pEList);
91853 iBreak = sqlite3VdbeMakeLabel(v);
91854 iCont = sqlite3VdbeMakeLabel(v);
91855 computeLimitRegisters(pParse, p, iBreak);
91856 sqlite3VdbeAddOp2(v, OP_Rewind, unionTab, iBreak);
91857 iStart = sqlite3VdbeCurrentAddr(v);
91858 selectInnerLoop(pParse, p, p->pEList, unionTab, p->pEList->nExpr,
91859 0, -1, &dest, iCont, iBreak);
91860 sqlite3VdbeResolveLabel(v, iCont);
91861 sqlite3VdbeAddOp2(v, OP_Next, unionTab, iStart);
91862 sqlite3VdbeResolveLabel(v, iBreak);
91863 sqlite3VdbeAddOp2(v, OP_Close, unionTab, 0);
91865 break;
91867 default: assert( p->op==TK_INTERSECT ); {
91868 int tab1, tab2;
91869 int iCont, iBreak, iStart;
91870 Expr *pLimit, *pOffset;
91871 int addr;
91872 SelectDest intersectdest;
91873 int r1;
91875 /* INTERSECT is different from the others since it requires
91876 ** two temporary tables. Hence it has its own case. Begin
91877 ** by allocating the tables we will need.
91879 tab1 = pParse->nTab++;
91880 tab2 = pParse->nTab++;
91881 assert( p->pOrderBy==0 );
91883 addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, tab1, 0);
91884 assert( p->addrOpenEphm[0] == -1 );
91885 p->addrOpenEphm[0] = addr;
91886 p->pRightmost->selFlags |= SF_UsesEphemeral;
91887 assert( p->pEList );
91889 /* Code the SELECTs to our left into temporary table "tab1".
91891 sqlite3SelectDestInit(&intersectdest, SRT_Union, tab1);
91892 explainSetInteger(iSub1, pParse->iNextSelectId);
91893 rc = sqlite3Select(pParse, pPrior, &intersectdest);
91894 if( rc ){
91895 goto multi_select_end;
91898 /* Code the current SELECT into temporary table "tab2"
91900 addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, tab2, 0);
91901 assert( p->addrOpenEphm[1] == -1 );
91902 p->addrOpenEphm[1] = addr;
91903 p->pPrior = 0;
91904 pLimit = p->pLimit;
91905 p->pLimit = 0;
91906 pOffset = p->pOffset;
91907 p->pOffset = 0;
91908 intersectdest.iParm = tab2;
91909 explainSetInteger(iSub2, pParse->iNextSelectId);
91910 rc = sqlite3Select(pParse, p, &intersectdest);
91911 testcase( rc!=SQLITE_OK );
91912 pDelete = p->pPrior;
91913 p->pPrior = pPrior;
91914 if( p->nSelectRow>pPrior->nSelectRow ) p->nSelectRow = pPrior->nSelectRow;
91915 sqlite3ExprDelete(db, p->pLimit);
91916 p->pLimit = pLimit;
91917 p->pOffset = pOffset;
91919 /* Generate code to take the intersection of the two temporary
91920 ** tables.
91922 assert( p->pEList );
91923 if( dest.eDest==SRT_Output ){
91924 Select *pFirst = p;
91925 while( pFirst->pPrior ) pFirst = pFirst->pPrior;
91926 generateColumnNames(pParse, 0, pFirst->pEList);
91928 iBreak = sqlite3VdbeMakeLabel(v);
91929 iCont = sqlite3VdbeMakeLabel(v);
91930 computeLimitRegisters(pParse, p, iBreak);
91931 sqlite3VdbeAddOp2(v, OP_Rewind, tab1, iBreak);
91932 r1 = sqlite3GetTempReg(pParse);
91933 iStart = sqlite3VdbeAddOp2(v, OP_RowKey, tab1, r1);
91934 sqlite3VdbeAddOp4Int(v, OP_NotFound, tab2, iCont, r1, 0);
91935 sqlite3ReleaseTempReg(pParse, r1);
91936 selectInnerLoop(pParse, p, p->pEList, tab1, p->pEList->nExpr,
91937 0, -1, &dest, iCont, iBreak);
91938 sqlite3VdbeResolveLabel(v, iCont);
91939 sqlite3VdbeAddOp2(v, OP_Next, tab1, iStart);
91940 sqlite3VdbeResolveLabel(v, iBreak);
91941 sqlite3VdbeAddOp2(v, OP_Close, tab2, 0);
91942 sqlite3VdbeAddOp2(v, OP_Close, tab1, 0);
91943 break;
91947 explainComposite(pParse, p->op, iSub1, iSub2, p->op!=TK_ALL);
91949 /* Compute collating sequences used by
91950 ** temporary tables needed to implement the compound select.
91951 ** Attach the KeyInfo structure to all temporary tables.
91953 ** This section is run by the right-most SELECT statement only.
91954 ** SELECT statements to the left always skip this part. The right-most
91955 ** SELECT might also skip this part if it has no ORDER BY clause and
91956 ** no temp tables are required.
91958 if( p->selFlags & SF_UsesEphemeral ){
91959 int i; /* Loop counter */
91960 KeyInfo *pKeyInfo; /* Collating sequence for the result set */
91961 Select *pLoop; /* For looping through SELECT statements */
91962 CollSeq **apColl; /* For looping through pKeyInfo->aColl[] */
91963 int nCol; /* Number of columns in result set */
91965 assert( p->pRightmost==p );
91966 nCol = p->pEList->nExpr;
91967 pKeyInfo = sqlite3DbMallocZero(db,
91968 sizeof(*pKeyInfo)+nCol*(sizeof(CollSeq*) + 1));
91969 if( !pKeyInfo ){
91970 rc = SQLITE_NOMEM;
91971 goto multi_select_end;
91974 pKeyInfo->enc = ENC(db);
91975 pKeyInfo->nField = (u16)nCol;
91977 for(i=0, apColl=pKeyInfo->aColl; i<nCol; i++, apColl++){
91978 *apColl = multiSelectCollSeq(pParse, p, i);
91979 if( 0==*apColl ){
91980 *apColl = db->pDfltColl;
91984 for(pLoop=p; pLoop; pLoop=pLoop->pPrior){
91985 for(i=0; i<2; i++){
91986 int addr = pLoop->addrOpenEphm[i];
91987 if( addr<0 ){
91988 /* If [0] is unused then [1] is also unused. So we can
91989 ** always safely abort as soon as the first unused slot is found */
91990 assert( pLoop->addrOpenEphm[1]<0 );
91991 break;
91993 sqlite3VdbeChangeP2(v, addr, nCol);
91994 sqlite3VdbeChangeP4(v, addr, (char*)pKeyInfo, P4_KEYINFO);
91995 pLoop->addrOpenEphm[i] = -1;
91998 sqlite3DbFree(db, pKeyInfo);
92001 multi_select_end:
92002 pDest->iMem = dest.iMem;
92003 pDest->nMem = dest.nMem;
92004 sqlite3SelectDelete(db, pDelete);
92005 return rc;
92007 #endif /* SQLITE_OMIT_COMPOUND_SELECT */
92010 ** Code an output subroutine for a coroutine implementation of a
92011 ** SELECT statment.
92013 ** The data to be output is contained in pIn->iMem. There are
92014 ** pIn->nMem columns to be output. pDest is where the output should
92015 ** be sent.
92017 ** regReturn is the number of the register holding the subroutine
92018 ** return address.
92020 ** If regPrev>0 then it is the first register in a vector that
92021 ** records the previous output. mem[regPrev] is a flag that is false
92022 ** if there has been no previous output. If regPrev>0 then code is
92023 ** generated to suppress duplicates. pKeyInfo is used for comparing
92024 ** keys.
92026 ** If the LIMIT found in p->iLimit is reached, jump immediately to
92027 ** iBreak.
92029 static int generateOutputSubroutine(
92030 Parse *pParse, /* Parsing context */
92031 Select *p, /* The SELECT statement */
92032 SelectDest *pIn, /* Coroutine supplying data */
92033 SelectDest *pDest, /* Where to send the data */
92034 int regReturn, /* The return address register */
92035 int regPrev, /* Previous result register. No uniqueness if 0 */
92036 KeyInfo *pKeyInfo, /* For comparing with previous entry */
92037 int p4type, /* The p4 type for pKeyInfo */
92038 int iBreak /* Jump here if we hit the LIMIT */
92040 Vdbe *v = pParse->pVdbe;
92041 int iContinue;
92042 int addr;
92044 addr = sqlite3VdbeCurrentAddr(v);
92045 iContinue = sqlite3VdbeMakeLabel(v);
92047 /* Suppress duplicates for UNION, EXCEPT, and INTERSECT
92049 if( regPrev ){
92050 int j1, j2;
92051 j1 = sqlite3VdbeAddOp1(v, OP_IfNot, regPrev);
92052 j2 = sqlite3VdbeAddOp4(v, OP_Compare, pIn->iMem, regPrev+1, pIn->nMem,
92053 (char*)pKeyInfo, p4type);
92054 sqlite3VdbeAddOp3(v, OP_Jump, j2+2, iContinue, j2+2);
92055 sqlite3VdbeJumpHere(v, j1);
92056 sqlite3ExprCodeCopy(pParse, pIn->iMem, regPrev+1, pIn->nMem);
92057 sqlite3VdbeAddOp2(v, OP_Integer, 1, regPrev);
92059 if( pParse->db->mallocFailed ) return 0;
92061 /* Suppress the the first OFFSET entries if there is an OFFSET clause
92063 codeOffset(v, p, iContinue);
92065 switch( pDest->eDest ){
92066 /* Store the result as data using a unique key.
92068 case SRT_Table:
92069 case SRT_EphemTab: {
92070 int r1 = sqlite3GetTempReg(pParse);
92071 int r2 = sqlite3GetTempReg(pParse);
92072 testcase( pDest->eDest==SRT_Table );
92073 testcase( pDest->eDest==SRT_EphemTab );
92074 sqlite3VdbeAddOp3(v, OP_MakeRecord, pIn->iMem, pIn->nMem, r1);
92075 sqlite3VdbeAddOp2(v, OP_NewRowid, pDest->iParm, r2);
92076 sqlite3VdbeAddOp3(v, OP_Insert, pDest->iParm, r1, r2);
92077 sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
92078 sqlite3ReleaseTempReg(pParse, r2);
92079 sqlite3ReleaseTempReg(pParse, r1);
92080 break;
92083 #ifndef SQLITE_OMIT_SUBQUERY
92084 /* If we are creating a set for an "expr IN (SELECT ...)" construct,
92085 ** then there should be a single item on the stack. Write this
92086 ** item into the set table with bogus data.
92088 case SRT_Set: {
92089 int r1;
92090 assert( pIn->nMem==1 );
92091 p->affinity =
92092 sqlite3CompareAffinity(p->pEList->a[0].pExpr, pDest->affinity);
92093 r1 = sqlite3GetTempReg(pParse);
92094 sqlite3VdbeAddOp4(v, OP_MakeRecord, pIn->iMem, 1, r1, &p->affinity, 1);
92095 sqlite3ExprCacheAffinityChange(pParse, pIn->iMem, 1);
92096 sqlite3VdbeAddOp2(v, OP_IdxInsert, pDest->iParm, r1);
92097 sqlite3ReleaseTempReg(pParse, r1);
92098 break;
92101 #if 0 /* Never occurs on an ORDER BY query */
92102 /* If any row exist in the result set, record that fact and abort.
92104 case SRT_Exists: {
92105 sqlite3VdbeAddOp2(v, OP_Integer, 1, pDest->iParm);
92106 /* The LIMIT clause will terminate the loop for us */
92107 break;
92109 #endif
92111 /* If this is a scalar select that is part of an expression, then
92112 ** store the results in the appropriate memory cell and break out
92113 ** of the scan loop.
92115 case SRT_Mem: {
92116 assert( pIn->nMem==1 );
92117 sqlite3ExprCodeMove(pParse, pIn->iMem, pDest->iParm, 1);
92118 /* The LIMIT clause will jump out of the loop for us */
92119 break;
92121 #endif /* #ifndef SQLITE_OMIT_SUBQUERY */
92123 /* The results are stored in a sequence of registers
92124 ** starting at pDest->iMem. Then the co-routine yields.
92126 case SRT_Coroutine: {
92127 if( pDest->iMem==0 ){
92128 pDest->iMem = sqlite3GetTempRange(pParse, pIn->nMem);
92129 pDest->nMem = pIn->nMem;
92131 sqlite3ExprCodeMove(pParse, pIn->iMem, pDest->iMem, pDest->nMem);
92132 sqlite3VdbeAddOp1(v, OP_Yield, pDest->iParm);
92133 break;
92136 /* If none of the above, then the result destination must be
92137 ** SRT_Output. This routine is never called with any other
92138 ** destination other than the ones handled above or SRT_Output.
92140 ** For SRT_Output, results are stored in a sequence of registers.
92141 ** Then the OP_ResultRow opcode is used to cause sqlite3_step() to
92142 ** return the next row of result.
92144 default: {
92145 assert( pDest->eDest==SRT_Output );
92146 sqlite3VdbeAddOp2(v, OP_ResultRow, pIn->iMem, pIn->nMem);
92147 sqlite3ExprCacheAffinityChange(pParse, pIn->iMem, pIn->nMem);
92148 break;
92152 /* Jump to the end of the loop if the LIMIT is reached.
92154 if( p->iLimit ){
92155 sqlite3VdbeAddOp3(v, OP_IfZero, p->iLimit, iBreak, -1);
92158 /* Generate the subroutine return
92160 sqlite3VdbeResolveLabel(v, iContinue);
92161 sqlite3VdbeAddOp1(v, OP_Return, regReturn);
92163 return addr;
92167 ** Alternative compound select code generator for cases when there
92168 ** is an ORDER BY clause.
92170 ** We assume a query of the following form:
92172 ** <selectA> <operator> <selectB> ORDER BY <orderbylist>
92174 ** <operator> is one of UNION ALL, UNION, EXCEPT, or INTERSECT. The idea
92175 ** is to code both <selectA> and <selectB> with the ORDER BY clause as
92176 ** co-routines. Then run the co-routines in parallel and merge the results
92177 ** into the output. In addition to the two coroutines (called selectA and
92178 ** selectB) there are 7 subroutines:
92180 ** outA: Move the output of the selectA coroutine into the output
92181 ** of the compound query.
92183 ** outB: Move the output of the selectB coroutine into the output
92184 ** of the compound query. (Only generated for UNION and
92185 ** UNION ALL. EXCEPT and INSERTSECT never output a row that
92186 ** appears only in B.)
92188 ** AltB: Called when there is data from both coroutines and A<B.
92190 ** AeqB: Called when there is data from both coroutines and A==B.
92192 ** AgtB: Called when there is data from both coroutines and A>B.
92194 ** EofA: Called when data is exhausted from selectA.
92196 ** EofB: Called when data is exhausted from selectB.
92198 ** The implementation of the latter five subroutines depend on which
92199 ** <operator> is used:
92202 ** UNION ALL UNION EXCEPT INTERSECT
92203 ** ------------- ----------------- -------------- -----------------
92204 ** AltB: outA, nextA outA, nextA outA, nextA nextA
92206 ** AeqB: outA, nextA nextA nextA outA, nextA
92208 ** AgtB: outB, nextB outB, nextB nextB nextB
92210 ** EofA: outB, nextB outB, nextB halt halt
92212 ** EofB: outA, nextA outA, nextA outA, nextA halt
92214 ** In the AltB, AeqB, and AgtB subroutines, an EOF on A following nextA
92215 ** causes an immediate jump to EofA and an EOF on B following nextB causes
92216 ** an immediate jump to EofB. Within EofA and EofB, and EOF on entry or
92217 ** following nextX causes a jump to the end of the select processing.
92219 ** Duplicate removal in the UNION, EXCEPT, and INTERSECT cases is handled
92220 ** within the output subroutine. The regPrev register set holds the previously
92221 ** output value. A comparison is made against this value and the output
92222 ** is skipped if the next results would be the same as the previous.
92224 ** The implementation plan is to implement the two coroutines and seven
92225 ** subroutines first, then put the control logic at the bottom. Like this:
92227 ** goto Init
92228 ** coA: coroutine for left query (A)
92229 ** coB: coroutine for right query (B)
92230 ** outA: output one row of A
92231 ** outB: output one row of B (UNION and UNION ALL only)
92232 ** EofA: ...
92233 ** EofB: ...
92234 ** AltB: ...
92235 ** AeqB: ...
92236 ** AgtB: ...
92237 ** Init: initialize coroutine registers
92238 ** yield coA
92239 ** if eof(A) goto EofA
92240 ** yield coB
92241 ** if eof(B) goto EofB
92242 ** Cmpr: Compare A, B
92243 ** Jump AltB, AeqB, AgtB
92244 ** End: ...
92246 ** We call AltB, AeqB, AgtB, EofA, and EofB "subroutines" but they are not
92247 ** actually called using Gosub and they do not Return. EofA and EofB loop
92248 ** until all data is exhausted then jump to the "end" labe. AltB, AeqB,
92249 ** and AgtB jump to either L2 or to one of EofA or EofB.
92251 #ifndef SQLITE_OMIT_COMPOUND_SELECT
92252 static int multiSelectOrderBy(
92253 Parse *pParse, /* Parsing context */
92254 Select *p, /* The right-most of SELECTs to be coded */
92255 SelectDest *pDest /* What to do with query results */
92257 int i, j; /* Loop counters */
92258 Select *pPrior; /* Another SELECT immediately to our left */
92259 Vdbe *v; /* Generate code to this VDBE */
92260 SelectDest destA; /* Destination for coroutine A */
92261 SelectDest destB; /* Destination for coroutine B */
92262 int regAddrA; /* Address register for select-A coroutine */
92263 int regEofA; /* Flag to indicate when select-A is complete */
92264 int regAddrB; /* Address register for select-B coroutine */
92265 int regEofB; /* Flag to indicate when select-B is complete */
92266 int addrSelectA; /* Address of the select-A coroutine */
92267 int addrSelectB; /* Address of the select-B coroutine */
92268 int regOutA; /* Address register for the output-A subroutine */
92269 int regOutB; /* Address register for the output-B subroutine */
92270 int addrOutA; /* Address of the output-A subroutine */
92271 int addrOutB = 0; /* Address of the output-B subroutine */
92272 int addrEofA; /* Address of the select-A-exhausted subroutine */
92273 int addrEofB; /* Address of the select-B-exhausted subroutine */
92274 int addrAltB; /* Address of the A<B subroutine */
92275 int addrAeqB; /* Address of the A==B subroutine */
92276 int addrAgtB; /* Address of the A>B subroutine */
92277 int regLimitA; /* Limit register for select-A */
92278 int regLimitB; /* Limit register for select-A */
92279 int regPrev; /* A range of registers to hold previous output */
92280 int savedLimit; /* Saved value of p->iLimit */
92281 int savedOffset; /* Saved value of p->iOffset */
92282 int labelCmpr; /* Label for the start of the merge algorithm */
92283 int labelEnd; /* Label for the end of the overall SELECT stmt */
92284 int j1; /* Jump instructions that get retargetted */
92285 int op; /* One of TK_ALL, TK_UNION, TK_EXCEPT, TK_INTERSECT */
92286 KeyInfo *pKeyDup = 0; /* Comparison information for duplicate removal */
92287 KeyInfo *pKeyMerge; /* Comparison information for merging rows */
92288 sqlite3 *db; /* Database connection */
92289 ExprList *pOrderBy; /* The ORDER BY clause */
92290 int nOrderBy; /* Number of terms in the ORDER BY clause */
92291 int *aPermute; /* Mapping from ORDER BY terms to result set columns */
92292 #ifndef SQLITE_OMIT_EXPLAIN
92293 int iSub1; /* EQP id of left-hand query */
92294 int iSub2; /* EQP id of right-hand query */
92295 #endif
92297 assert( p->pOrderBy!=0 );
92298 assert( pKeyDup==0 ); /* "Managed" code needs this. Ticket #3382. */
92299 db = pParse->db;
92300 v = pParse->pVdbe;
92301 assert( v!=0 ); /* Already thrown the error if VDBE alloc failed */
92302 labelEnd = sqlite3VdbeMakeLabel(v);
92303 labelCmpr = sqlite3VdbeMakeLabel(v);
92306 /* Patch up the ORDER BY clause
92308 op = p->op;
92309 pPrior = p->pPrior;
92310 assert( pPrior->pOrderBy==0 );
92311 pOrderBy = p->pOrderBy;
92312 assert( pOrderBy );
92313 nOrderBy = pOrderBy->nExpr;
92315 /* For operators other than UNION ALL we have to make sure that
92316 ** the ORDER BY clause covers every term of the result set. Add
92317 ** terms to the ORDER BY clause as necessary.
92319 if( op!=TK_ALL ){
92320 for(i=1; db->mallocFailed==0 && i<=p->pEList->nExpr; i++){
92321 struct ExprList_item *pItem;
92322 for(j=0, pItem=pOrderBy->a; j<nOrderBy; j++, pItem++){
92323 assert( pItem->iCol>0 );
92324 if( pItem->iCol==i ) break;
92326 if( j==nOrderBy ){
92327 Expr *pNew = sqlite3Expr(db, TK_INTEGER, 0);
92328 if( pNew==0 ) return SQLITE_NOMEM;
92329 pNew->flags |= EP_IntValue;
92330 pNew->u.iValue = i;
92331 pOrderBy = sqlite3ExprListAppend(pParse, pOrderBy, pNew);
92332 pOrderBy->a[nOrderBy++].iCol = (u16)i;
92337 /* Compute the comparison permutation and keyinfo that is used with
92338 ** the permutation used to determine if the next
92339 ** row of results comes from selectA or selectB. Also add explicit
92340 ** collations to the ORDER BY clause terms so that when the subqueries
92341 ** to the right and the left are evaluated, they use the correct
92342 ** collation.
92344 aPermute = sqlite3DbMallocRaw(db, sizeof(int)*nOrderBy);
92345 if( aPermute ){
92346 struct ExprList_item *pItem;
92347 for(i=0, pItem=pOrderBy->a; i<nOrderBy; i++, pItem++){
92348 assert( pItem->iCol>0 && pItem->iCol<=p->pEList->nExpr );
92349 aPermute[i] = pItem->iCol - 1;
92351 pKeyMerge =
92352 sqlite3DbMallocRaw(db, sizeof(*pKeyMerge)+nOrderBy*(sizeof(CollSeq*)+1));
92353 if( pKeyMerge ){
92354 pKeyMerge->aSortOrder = (u8*)&pKeyMerge->aColl[nOrderBy];
92355 pKeyMerge->nField = (u16)nOrderBy;
92356 pKeyMerge->enc = ENC(db);
92357 for(i=0; i<nOrderBy; i++){
92358 CollSeq *pColl;
92359 Expr *pTerm = pOrderBy->a[i].pExpr;
92360 if( pTerm->flags & EP_ExpCollate ){
92361 pColl = pTerm->pColl;
92362 }else{
92363 pColl = multiSelectCollSeq(pParse, p, aPermute[i]);
92364 pTerm->flags |= EP_ExpCollate;
92365 pTerm->pColl = pColl;
92367 pKeyMerge->aColl[i] = pColl;
92368 pKeyMerge->aSortOrder[i] = pOrderBy->a[i].sortOrder;
92371 }else{
92372 pKeyMerge = 0;
92375 /* Reattach the ORDER BY clause to the query.
92377 p->pOrderBy = pOrderBy;
92378 pPrior->pOrderBy = sqlite3ExprListDup(pParse->db, pOrderBy, 0);
92380 /* Allocate a range of temporary registers and the KeyInfo needed
92381 ** for the logic that removes duplicate result rows when the
92382 ** operator is UNION, EXCEPT, or INTERSECT (but not UNION ALL).
92384 if( op==TK_ALL ){
92385 regPrev = 0;
92386 }else{
92387 int nExpr = p->pEList->nExpr;
92388 assert( nOrderBy>=nExpr || db->mallocFailed );
92389 regPrev = sqlite3GetTempRange(pParse, nExpr+1);
92390 sqlite3VdbeAddOp2(v, OP_Integer, 0, regPrev);
92391 pKeyDup = sqlite3DbMallocZero(db,
92392 sizeof(*pKeyDup) + nExpr*(sizeof(CollSeq*)+1) );
92393 if( pKeyDup ){
92394 pKeyDup->aSortOrder = (u8*)&pKeyDup->aColl[nExpr];
92395 pKeyDup->nField = (u16)nExpr;
92396 pKeyDup->enc = ENC(db);
92397 for(i=0; i<nExpr; i++){
92398 pKeyDup->aColl[i] = multiSelectCollSeq(pParse, p, i);
92399 pKeyDup->aSortOrder[i] = 0;
92404 /* Separate the left and the right query from one another
92406 p->pPrior = 0;
92407 sqlite3ResolveOrderGroupBy(pParse, p, p->pOrderBy, "ORDER");
92408 if( pPrior->pPrior==0 ){
92409 sqlite3ResolveOrderGroupBy(pParse, pPrior, pPrior->pOrderBy, "ORDER");
92412 /* Compute the limit registers */
92413 computeLimitRegisters(pParse, p, labelEnd);
92414 if( p->iLimit && op==TK_ALL ){
92415 regLimitA = ++pParse->nMem;
92416 regLimitB = ++pParse->nMem;
92417 sqlite3VdbeAddOp2(v, OP_Copy, p->iOffset ? p->iOffset+1 : p->iLimit,
92418 regLimitA);
92419 sqlite3VdbeAddOp2(v, OP_Copy, regLimitA, regLimitB);
92420 }else{
92421 regLimitA = regLimitB = 0;
92423 sqlite3ExprDelete(db, p->pLimit);
92424 p->pLimit = 0;
92425 sqlite3ExprDelete(db, p->pOffset);
92426 p->pOffset = 0;
92428 regAddrA = ++pParse->nMem;
92429 regEofA = ++pParse->nMem;
92430 regAddrB = ++pParse->nMem;
92431 regEofB = ++pParse->nMem;
92432 regOutA = ++pParse->nMem;
92433 regOutB = ++pParse->nMem;
92434 sqlite3SelectDestInit(&destA, SRT_Coroutine, regAddrA);
92435 sqlite3SelectDestInit(&destB, SRT_Coroutine, regAddrB);
92437 /* Jump past the various subroutines and coroutines to the main
92438 ** merge loop
92440 j1 = sqlite3VdbeAddOp0(v, OP_Goto);
92441 addrSelectA = sqlite3VdbeCurrentAddr(v);
92444 /* Generate a coroutine to evaluate the SELECT statement to the
92445 ** left of the compound operator - the "A" select.
92447 VdbeNoopComment((v, "Begin coroutine for left SELECT"));
92448 pPrior->iLimit = regLimitA;
92449 explainSetInteger(iSub1, pParse->iNextSelectId);
92450 sqlite3Select(pParse, pPrior, &destA);
92451 sqlite3VdbeAddOp2(v, OP_Integer, 1, regEofA);
92452 sqlite3VdbeAddOp1(v, OP_Yield, regAddrA);
92453 VdbeNoopComment((v, "End coroutine for left SELECT"));
92455 /* Generate a coroutine to evaluate the SELECT statement on
92456 ** the right - the "B" select
92458 addrSelectB = sqlite3VdbeCurrentAddr(v);
92459 VdbeNoopComment((v, "Begin coroutine for right SELECT"));
92460 savedLimit = p->iLimit;
92461 savedOffset = p->iOffset;
92462 p->iLimit = regLimitB;
92463 p->iOffset = 0;
92464 explainSetInteger(iSub2, pParse->iNextSelectId);
92465 sqlite3Select(pParse, p, &destB);
92466 p->iLimit = savedLimit;
92467 p->iOffset = savedOffset;
92468 sqlite3VdbeAddOp2(v, OP_Integer, 1, regEofB);
92469 sqlite3VdbeAddOp1(v, OP_Yield, regAddrB);
92470 VdbeNoopComment((v, "End coroutine for right SELECT"));
92472 /* Generate a subroutine that outputs the current row of the A
92473 ** select as the next output row of the compound select.
92475 VdbeNoopComment((v, "Output routine for A"));
92476 addrOutA = generateOutputSubroutine(pParse,
92477 p, &destA, pDest, regOutA,
92478 regPrev, pKeyDup, P4_KEYINFO_HANDOFF, labelEnd);
92480 /* Generate a subroutine that outputs the current row of the B
92481 ** select as the next output row of the compound select.
92483 if( op==TK_ALL || op==TK_UNION ){
92484 VdbeNoopComment((v, "Output routine for B"));
92485 addrOutB = generateOutputSubroutine(pParse,
92486 p, &destB, pDest, regOutB,
92487 regPrev, pKeyDup, P4_KEYINFO_STATIC, labelEnd);
92490 /* Generate a subroutine to run when the results from select A
92491 ** are exhausted and only data in select B remains.
92493 VdbeNoopComment((v, "eof-A subroutine"));
92494 if( op==TK_EXCEPT || op==TK_INTERSECT ){
92495 addrEofA = sqlite3VdbeAddOp2(v, OP_Goto, 0, labelEnd);
92496 }else{
92497 addrEofA = sqlite3VdbeAddOp2(v, OP_If, regEofB, labelEnd);
92498 sqlite3VdbeAddOp2(v, OP_Gosub, regOutB, addrOutB);
92499 sqlite3VdbeAddOp1(v, OP_Yield, regAddrB);
92500 sqlite3VdbeAddOp2(v, OP_Goto, 0, addrEofA);
92501 p->nSelectRow += pPrior->nSelectRow;
92504 /* Generate a subroutine to run when the results from select B
92505 ** are exhausted and only data in select A remains.
92507 if( op==TK_INTERSECT ){
92508 addrEofB = addrEofA;
92509 if( p->nSelectRow > pPrior->nSelectRow ) p->nSelectRow = pPrior->nSelectRow;
92510 }else{
92511 VdbeNoopComment((v, "eof-B subroutine"));
92512 addrEofB = sqlite3VdbeAddOp2(v, OP_If, regEofA, labelEnd);
92513 sqlite3VdbeAddOp2(v, OP_Gosub, regOutA, addrOutA);
92514 sqlite3VdbeAddOp1(v, OP_Yield, regAddrA);
92515 sqlite3VdbeAddOp2(v, OP_Goto, 0, addrEofB);
92518 /* Generate code to handle the case of A<B
92520 VdbeNoopComment((v, "A-lt-B subroutine"));
92521 addrAltB = sqlite3VdbeAddOp2(v, OP_Gosub, regOutA, addrOutA);
92522 sqlite3VdbeAddOp1(v, OP_Yield, regAddrA);
92523 sqlite3VdbeAddOp2(v, OP_If, regEofA, addrEofA);
92524 sqlite3VdbeAddOp2(v, OP_Goto, 0, labelCmpr);
92526 /* Generate code to handle the case of A==B
92528 if( op==TK_ALL ){
92529 addrAeqB = addrAltB;
92530 }else if( op==TK_INTERSECT ){
92531 addrAeqB = addrAltB;
92532 addrAltB++;
92533 }else{
92534 VdbeNoopComment((v, "A-eq-B subroutine"));
92535 addrAeqB =
92536 sqlite3VdbeAddOp1(v, OP_Yield, regAddrA);
92537 sqlite3VdbeAddOp2(v, OP_If, regEofA, addrEofA);
92538 sqlite3VdbeAddOp2(v, OP_Goto, 0, labelCmpr);
92541 /* Generate code to handle the case of A>B
92543 VdbeNoopComment((v, "A-gt-B subroutine"));
92544 addrAgtB = sqlite3VdbeCurrentAddr(v);
92545 if( op==TK_ALL || op==TK_UNION ){
92546 sqlite3VdbeAddOp2(v, OP_Gosub, regOutB, addrOutB);
92548 sqlite3VdbeAddOp1(v, OP_Yield, regAddrB);
92549 sqlite3VdbeAddOp2(v, OP_If, regEofB, addrEofB);
92550 sqlite3VdbeAddOp2(v, OP_Goto, 0, labelCmpr);
92552 /* This code runs once to initialize everything.
92554 sqlite3VdbeJumpHere(v, j1);
92555 sqlite3VdbeAddOp2(v, OP_Integer, 0, regEofA);
92556 sqlite3VdbeAddOp2(v, OP_Integer, 0, regEofB);
92557 sqlite3VdbeAddOp2(v, OP_Gosub, regAddrA, addrSelectA);
92558 sqlite3VdbeAddOp2(v, OP_Gosub, regAddrB, addrSelectB);
92559 sqlite3VdbeAddOp2(v, OP_If, regEofA, addrEofA);
92560 sqlite3VdbeAddOp2(v, OP_If, regEofB, addrEofB);
92562 /* Implement the main merge loop
92564 sqlite3VdbeResolveLabel(v, labelCmpr);
92565 sqlite3VdbeAddOp4(v, OP_Permutation, 0, 0, 0, (char*)aPermute, P4_INTARRAY);
92566 sqlite3VdbeAddOp4(v, OP_Compare, destA.iMem, destB.iMem, nOrderBy,
92567 (char*)pKeyMerge, P4_KEYINFO_HANDOFF);
92568 sqlite3VdbeAddOp3(v, OP_Jump, addrAltB, addrAeqB, addrAgtB);
92570 /* Release temporary registers
92572 if( regPrev ){
92573 sqlite3ReleaseTempRange(pParse, regPrev, nOrderBy+1);
92576 /* Jump to the this point in order to terminate the query.
92578 sqlite3VdbeResolveLabel(v, labelEnd);
92580 /* Set the number of output columns
92582 if( pDest->eDest==SRT_Output ){
92583 Select *pFirst = pPrior;
92584 while( pFirst->pPrior ) pFirst = pFirst->pPrior;
92585 generateColumnNames(pParse, 0, pFirst->pEList);
92588 /* Reassembly the compound query so that it will be freed correctly
92589 ** by the calling function */
92590 if( p->pPrior ){
92591 sqlite3SelectDelete(db, p->pPrior);
92593 p->pPrior = pPrior;
92595 /*** TBD: Insert subroutine calls to close cursors on incomplete
92596 **** subqueries ****/
92597 explainComposite(pParse, p->op, iSub1, iSub2, 0);
92598 return SQLITE_OK;
92600 #endif
92602 #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
92603 /* Forward Declarations */
92604 static void substExprList(sqlite3*, ExprList*, int, ExprList*);
92605 static void substSelect(sqlite3*, Select *, int, ExprList *);
92608 ** Scan through the expression pExpr. Replace every reference to
92609 ** a column in table number iTable with a copy of the iColumn-th
92610 ** entry in pEList. (But leave references to the ROWID column
92611 ** unchanged.)
92613 ** This routine is part of the flattening procedure. A subquery
92614 ** whose result set is defined by pEList appears as entry in the
92615 ** FROM clause of a SELECT such that the VDBE cursor assigned to that
92616 ** FORM clause entry is iTable. This routine make the necessary
92617 ** changes to pExpr so that it refers directly to the source table
92618 ** of the subquery rather the result set of the subquery.
92620 static Expr *substExpr(
92621 sqlite3 *db, /* Report malloc errors to this connection */
92622 Expr *pExpr, /* Expr in which substitution occurs */
92623 int iTable, /* Table to be substituted */
92624 ExprList *pEList /* Substitute expressions */
92626 if( pExpr==0 ) return 0;
92627 if( pExpr->op==TK_COLUMN && pExpr->iTable==iTable ){
92628 if( pExpr->iColumn<0 ){
92629 pExpr->op = TK_NULL;
92630 }else{
92631 Expr *pNew;
92632 assert( pEList!=0 && pExpr->iColumn<pEList->nExpr );
92633 assert( pExpr->pLeft==0 && pExpr->pRight==0 );
92634 pNew = sqlite3ExprDup(db, pEList->a[pExpr->iColumn].pExpr, 0);
92635 if( pNew && pExpr->pColl ){
92636 pNew->pColl = pExpr->pColl;
92638 sqlite3ExprDelete(db, pExpr);
92639 pExpr = pNew;
92641 }else{
92642 pExpr->pLeft = substExpr(db, pExpr->pLeft, iTable, pEList);
92643 pExpr->pRight = substExpr(db, pExpr->pRight, iTable, pEList);
92644 if( ExprHasProperty(pExpr, EP_xIsSelect) ){
92645 substSelect(db, pExpr->x.pSelect, iTable, pEList);
92646 }else{
92647 substExprList(db, pExpr->x.pList, iTable, pEList);
92650 return pExpr;
92652 static void substExprList(
92653 sqlite3 *db, /* Report malloc errors here */
92654 ExprList *pList, /* List to scan and in which to make substitutes */
92655 int iTable, /* Table to be substituted */
92656 ExprList *pEList /* Substitute values */
92658 int i;
92659 if( pList==0 ) return;
92660 for(i=0; i<pList->nExpr; i++){
92661 pList->a[i].pExpr = substExpr(db, pList->a[i].pExpr, iTable, pEList);
92664 static void substSelect(
92665 sqlite3 *db, /* Report malloc errors here */
92666 Select *p, /* SELECT statement in which to make substitutions */
92667 int iTable, /* Table to be replaced */
92668 ExprList *pEList /* Substitute values */
92670 SrcList *pSrc;
92671 struct SrcList_item *pItem;
92672 int i;
92673 if( !p ) return;
92674 substExprList(db, p->pEList, iTable, pEList);
92675 substExprList(db, p->pGroupBy, iTable, pEList);
92676 substExprList(db, p->pOrderBy, iTable, pEList);
92677 p->pHaving = substExpr(db, p->pHaving, iTable, pEList);
92678 p->pWhere = substExpr(db, p->pWhere, iTable, pEList);
92679 substSelect(db, p->pPrior, iTable, pEList);
92680 pSrc = p->pSrc;
92681 assert( pSrc ); /* Even for (SELECT 1) we have: pSrc!=0 but pSrc->nSrc==0 */
92682 if( ALWAYS(pSrc) ){
92683 for(i=pSrc->nSrc, pItem=pSrc->a; i>0; i--, pItem++){
92684 substSelect(db, pItem->pSelect, iTable, pEList);
92688 #endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */
92690 #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
92692 ** This routine attempts to flatten subqueries in order to speed
92693 ** execution. It returns 1 if it makes changes and 0 if no flattening
92694 ** occurs.
92696 ** To understand the concept of flattening, consider the following
92697 ** query:
92699 ** SELECT a FROM (SELECT x+y AS a FROM t1 WHERE z<100) WHERE a>5
92701 ** The default way of implementing this query is to execute the
92702 ** subquery first and store the results in a temporary table, then
92703 ** run the outer query on that temporary table. This requires two
92704 ** passes over the data. Furthermore, because the temporary table
92705 ** has no indices, the WHERE clause on the outer query cannot be
92706 ** optimized.
92708 ** This routine attempts to rewrite queries such as the above into
92709 ** a single flat select, like this:
92711 ** SELECT x+y AS a FROM t1 WHERE z<100 AND a>5
92713 ** The code generated for this simpification gives the same result
92714 ** but only has to scan the data once. And because indices might
92715 ** exist on the table t1, a complete scan of the data might be
92716 ** avoided.
92718 ** Flattening is only attempted if all of the following are true:
92720 ** (1) The subquery and the outer query do not both use aggregates.
92722 ** (2) The subquery is not an aggregate or the outer query is not a join.
92724 ** (3) The subquery is not the right operand of a left outer join
92725 ** (Originally ticket #306. Strengthened by ticket #3300)
92727 ** (4) The subquery is not DISTINCT.
92729 ** (**) At one point restrictions (4) and (5) defined a subset of DISTINCT
92730 ** sub-queries that were excluded from this optimization. Restriction
92731 ** (4) has since been expanded to exclude all DISTINCT subqueries.
92733 ** (6) The subquery does not use aggregates or the outer query is not
92734 ** DISTINCT.
92736 ** (7) The subquery has a FROM clause.
92738 ** (8) The subquery does not use LIMIT or the outer query is not a join.
92740 ** (9) The subquery does not use LIMIT or the outer query does not use
92741 ** aggregates.
92743 ** (10) The subquery does not use aggregates or the outer query does not
92744 ** use LIMIT.
92746 ** (11) The subquery and the outer query do not both have ORDER BY clauses.
92748 ** (**) Not implemented. Subsumed into restriction (3). Was previously
92749 ** a separate restriction deriving from ticket #350.
92751 ** (13) The subquery and outer query do not both use LIMIT.
92753 ** (14) The subquery does not use OFFSET.
92755 ** (15) The outer query is not part of a compound select or the
92756 ** subquery does not have a LIMIT clause.
92757 ** (See ticket #2339 and ticket [02a8e81d44]).
92759 ** (16) The outer query is not an aggregate or the subquery does
92760 ** not contain ORDER BY. (Ticket #2942) This used to not matter
92761 ** until we introduced the group_concat() function.
92763 ** (17) The sub-query is not a compound select, or it is a UNION ALL
92764 ** compound clause made up entirely of non-aggregate queries, and
92765 ** the parent query:
92767 ** * is not itself part of a compound select,
92768 ** * is not an aggregate or DISTINCT query, and
92769 ** * has no other tables or sub-selects in the FROM clause.
92771 ** The parent and sub-query may contain WHERE clauses. Subject to
92772 ** rules (11), (13) and (14), they may also contain ORDER BY,
92773 ** LIMIT and OFFSET clauses.
92775 ** (18) If the sub-query is a compound select, then all terms of the
92776 ** ORDER by clause of the parent must be simple references to
92777 ** columns of the sub-query.
92779 ** (19) The subquery does not use LIMIT or the outer query does not
92780 ** have a WHERE clause.
92782 ** (20) If the sub-query is a compound select, then it must not use
92783 ** an ORDER BY clause. Ticket #3773. We could relax this constraint
92784 ** somewhat by saying that the terms of the ORDER BY clause must
92785 ** appear as unmodified result columns in the outer query. But
92786 ** have other optimizations in mind to deal with that case.
92788 ** (21) The subquery does not use LIMIT or the outer query is not
92789 ** DISTINCT. (See ticket [752e1646fc]).
92791 ** In this routine, the "p" parameter is a pointer to the outer query.
92792 ** The subquery is p->pSrc->a[iFrom]. isAgg is true if the outer query
92793 ** uses aggregates and subqueryIsAgg is true if the subquery uses aggregates.
92795 ** If flattening is not attempted, this routine is a no-op and returns 0.
92796 ** If flattening is attempted this routine returns 1.
92798 ** All of the expression analysis must occur on both the outer query and
92799 ** the subquery before this routine runs.
92801 static int flattenSubquery(
92802 Parse *pParse, /* Parsing context */
92803 Select *p, /* The parent or outer SELECT statement */
92804 int iFrom, /* Index in p->pSrc->a[] of the inner subquery */
92805 int isAgg, /* True if outer SELECT uses aggregate functions */
92806 int subqueryIsAgg /* True if the subquery uses aggregate functions */
92808 const char *zSavedAuthContext = pParse->zAuthContext;
92809 Select *pParent;
92810 Select *pSub; /* The inner query or "subquery" */
92811 Select *pSub1; /* Pointer to the rightmost select in sub-query */
92812 SrcList *pSrc; /* The FROM clause of the outer query */
92813 SrcList *pSubSrc; /* The FROM clause of the subquery */
92814 ExprList *pList; /* The result set of the outer query */
92815 int iParent; /* VDBE cursor number of the pSub result set temp table */
92816 int i; /* Loop counter */
92817 Expr *pWhere; /* The WHERE clause */
92818 struct SrcList_item *pSubitem; /* The subquery */
92819 sqlite3 *db = pParse->db;
92821 /* Check to see if flattening is permitted. Return 0 if not.
92823 assert( p!=0 );
92824 assert( p->pPrior==0 ); /* Unable to flatten compound queries */
92825 if( db->flags & SQLITE_QueryFlattener ) return 0;
92826 pSrc = p->pSrc;
92827 assert( pSrc && iFrom>=0 && iFrom<pSrc->nSrc );
92828 pSubitem = &pSrc->a[iFrom];
92829 iParent = pSubitem->iCursor;
92830 pSub = pSubitem->pSelect;
92831 assert( pSub!=0 );
92832 if( isAgg && subqueryIsAgg ) return 0; /* Restriction (1) */
92833 if( subqueryIsAgg && pSrc->nSrc>1 ) return 0; /* Restriction (2) */
92834 pSubSrc = pSub->pSrc;
92835 assert( pSubSrc );
92836 /* Prior to version 3.1.2, when LIMIT and OFFSET had to be simple constants,
92837 ** not arbitrary expresssions, we allowed some combining of LIMIT and OFFSET
92838 ** because they could be computed at compile-time. But when LIMIT and OFFSET
92839 ** became arbitrary expressions, we were forced to add restrictions (13)
92840 ** and (14). */
92841 if( pSub->pLimit && p->pLimit ) return 0; /* Restriction (13) */
92842 if( pSub->pOffset ) return 0; /* Restriction (14) */
92843 if( p->pRightmost && pSub->pLimit ){
92844 return 0; /* Restriction (15) */
92846 if( pSubSrc->nSrc==0 ) return 0; /* Restriction (7) */
92847 if( pSub->selFlags & SF_Distinct ) return 0; /* Restriction (5) */
92848 if( pSub->pLimit && (pSrc->nSrc>1 || isAgg) ){
92849 return 0; /* Restrictions (8)(9) */
92851 if( (p->selFlags & SF_Distinct)!=0 && subqueryIsAgg ){
92852 return 0; /* Restriction (6) */
92854 if( p->pOrderBy && pSub->pOrderBy ){
92855 return 0; /* Restriction (11) */
92857 if( isAgg && pSub->pOrderBy ) return 0; /* Restriction (16) */
92858 if( pSub->pLimit && p->pWhere ) return 0; /* Restriction (19) */
92859 if( pSub->pLimit && (p->selFlags & SF_Distinct)!=0 ){
92860 return 0; /* Restriction (21) */
92863 /* OBSOLETE COMMENT 1:
92864 ** Restriction 3: If the subquery is a join, make sure the subquery is
92865 ** not used as the right operand of an outer join. Examples of why this
92866 ** is not allowed:
92868 ** t1 LEFT OUTER JOIN (t2 JOIN t3)
92870 ** If we flatten the above, we would get
92872 ** (t1 LEFT OUTER JOIN t2) JOIN t3
92874 ** which is not at all the same thing.
92876 ** OBSOLETE COMMENT 2:
92877 ** Restriction 12: If the subquery is the right operand of a left outer
92878 ** join, make sure the subquery has no WHERE clause.
92879 ** An examples of why this is not allowed:
92881 ** t1 LEFT OUTER JOIN (SELECT * FROM t2 WHERE t2.x>0)
92883 ** If we flatten the above, we would get
92885 ** (t1 LEFT OUTER JOIN t2) WHERE t2.x>0
92887 ** But the t2.x>0 test will always fail on a NULL row of t2, which
92888 ** effectively converts the OUTER JOIN into an INNER JOIN.
92890 ** THIS OVERRIDES OBSOLETE COMMENTS 1 AND 2 ABOVE:
92891 ** Ticket #3300 shows that flattening the right term of a LEFT JOIN
92892 ** is fraught with danger. Best to avoid the whole thing. If the
92893 ** subquery is the right term of a LEFT JOIN, then do not flatten.
92895 if( (pSubitem->jointype & JT_OUTER)!=0 ){
92896 return 0;
92899 /* Restriction 17: If the sub-query is a compound SELECT, then it must
92900 ** use only the UNION ALL operator. And none of the simple select queries
92901 ** that make up the compound SELECT are allowed to be aggregate or distinct
92902 ** queries.
92904 if( pSub->pPrior ){
92905 if( pSub->pOrderBy ){
92906 return 0; /* Restriction 20 */
92908 if( isAgg || (p->selFlags & SF_Distinct)!=0 || pSrc->nSrc!=1 ){
92909 return 0;
92911 for(pSub1=pSub; pSub1; pSub1=pSub1->pPrior){
92912 testcase( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct );
92913 testcase( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))==SF_Aggregate );
92914 if( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))!=0
92915 || (pSub1->pPrior && pSub1->op!=TK_ALL)
92916 || NEVER(pSub1->pSrc==0) || pSub1->pSrc->nSrc!=1
92918 return 0;
92922 /* Restriction 18. */
92923 if( p->pOrderBy ){
92924 int ii;
92925 for(ii=0; ii<p->pOrderBy->nExpr; ii++){
92926 if( p->pOrderBy->a[ii].iCol==0 ) return 0;
92931 /***** If we reach this point, flattening is permitted. *****/
92933 /* Authorize the subquery */
92934 pParse->zAuthContext = pSubitem->zName;
92935 sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0);
92936 pParse->zAuthContext = zSavedAuthContext;
92938 /* If the sub-query is a compound SELECT statement, then (by restrictions
92939 ** 17 and 18 above) it must be a UNION ALL and the parent query must
92940 ** be of the form:
92942 ** SELECT <expr-list> FROM (<sub-query>) <where-clause>
92944 ** followed by any ORDER BY, LIMIT and/or OFFSET clauses. This block
92945 ** creates N-1 copies of the parent query without any ORDER BY, LIMIT or
92946 ** OFFSET clauses and joins them to the left-hand-side of the original
92947 ** using UNION ALL operators. In this case N is the number of simple
92948 ** select statements in the compound sub-query.
92950 ** Example:
92952 ** SELECT a+1 FROM (
92953 ** SELECT x FROM tab
92954 ** UNION ALL
92955 ** SELECT y FROM tab
92956 ** UNION ALL
92957 ** SELECT abs(z*2) FROM tab2
92958 ** ) WHERE a!=5 ORDER BY 1
92960 ** Transformed into:
92962 ** SELECT x+1 FROM tab WHERE x+1!=5
92963 ** UNION ALL
92964 ** SELECT y+1 FROM tab WHERE y+1!=5
92965 ** UNION ALL
92966 ** SELECT abs(z*2)+1 FROM tab2 WHERE abs(z*2)+1!=5
92967 ** ORDER BY 1
92969 ** We call this the "compound-subquery flattening".
92971 for(pSub=pSub->pPrior; pSub; pSub=pSub->pPrior){
92972 Select *pNew;
92973 ExprList *pOrderBy = p->pOrderBy;
92974 Expr *pLimit = p->pLimit;
92975 Select *pPrior = p->pPrior;
92976 p->pOrderBy = 0;
92977 p->pSrc = 0;
92978 p->pPrior = 0;
92979 p->pLimit = 0;
92980 pNew = sqlite3SelectDup(db, p, 0);
92981 p->pLimit = pLimit;
92982 p->pOrderBy = pOrderBy;
92983 p->pSrc = pSrc;
92984 p->op = TK_ALL;
92985 p->pRightmost = 0;
92986 if( pNew==0 ){
92987 pNew = pPrior;
92988 }else{
92989 pNew->pPrior = pPrior;
92990 pNew->pRightmost = 0;
92992 p->pPrior = pNew;
92993 if( db->mallocFailed ) return 1;
92996 /* Begin flattening the iFrom-th entry of the FROM clause
92997 ** in the outer query.
92999 pSub = pSub1 = pSubitem->pSelect;
93001 /* Delete the transient table structure associated with the
93002 ** subquery
93004 sqlite3DbFree(db, pSubitem->zDatabase);
93005 sqlite3DbFree(db, pSubitem->zName);
93006 sqlite3DbFree(db, pSubitem->zAlias);
93007 pSubitem->zDatabase = 0;
93008 pSubitem->zName = 0;
93009 pSubitem->zAlias = 0;
93010 pSubitem->pSelect = 0;
93012 /* Defer deleting the Table object associated with the
93013 ** subquery until code generation is
93014 ** complete, since there may still exist Expr.pTab entries that
93015 ** refer to the subquery even after flattening. Ticket #3346.
93017 ** pSubitem->pTab is always non-NULL by test restrictions and tests above.
93019 if( ALWAYS(pSubitem->pTab!=0) ){
93020 Table *pTabToDel = pSubitem->pTab;
93021 if( pTabToDel->nRef==1 ){
93022 Parse *pToplevel = sqlite3ParseToplevel(pParse);
93023 pTabToDel->pNextZombie = pToplevel->pZombieTab;
93024 pToplevel->pZombieTab = pTabToDel;
93025 }else{
93026 pTabToDel->nRef--;
93028 pSubitem->pTab = 0;
93031 /* The following loop runs once for each term in a compound-subquery
93032 ** flattening (as described above). If we are doing a different kind
93033 ** of flattening - a flattening other than a compound-subquery flattening -
93034 ** then this loop only runs once.
93036 ** This loop moves all of the FROM elements of the subquery into the
93037 ** the FROM clause of the outer query. Before doing this, remember
93038 ** the cursor number for the original outer query FROM element in
93039 ** iParent. The iParent cursor will never be used. Subsequent code
93040 ** will scan expressions looking for iParent references and replace
93041 ** those references with expressions that resolve to the subquery FROM
93042 ** elements we are now copying in.
93044 for(pParent=p; pParent; pParent=pParent->pPrior, pSub=pSub->pPrior){
93045 int nSubSrc;
93046 u8 jointype = 0;
93047 pSubSrc = pSub->pSrc; /* FROM clause of subquery */
93048 nSubSrc = pSubSrc->nSrc; /* Number of terms in subquery FROM clause */
93049 pSrc = pParent->pSrc; /* FROM clause of the outer query */
93051 if( pSrc ){
93052 assert( pParent==p ); /* First time through the loop */
93053 jointype = pSubitem->jointype;
93054 }else{
93055 assert( pParent!=p ); /* 2nd and subsequent times through the loop */
93056 pSrc = pParent->pSrc = sqlite3SrcListAppend(db, 0, 0, 0);
93057 if( pSrc==0 ){
93058 assert( db->mallocFailed );
93059 break;
93063 /* The subquery uses a single slot of the FROM clause of the outer
93064 ** query. If the subquery has more than one element in its FROM clause,
93065 ** then expand the outer query to make space for it to hold all elements
93066 ** of the subquery.
93068 ** Example:
93070 ** SELECT * FROM tabA, (SELECT * FROM sub1, sub2), tabB;
93072 ** The outer query has 3 slots in its FROM clause. One slot of the
93073 ** outer query (the middle slot) is used by the subquery. The next
93074 ** block of code will expand the out query to 4 slots. The middle
93075 ** slot is expanded to two slots in order to make space for the
93076 ** two elements in the FROM clause of the subquery.
93078 if( nSubSrc>1 ){
93079 pParent->pSrc = pSrc = sqlite3SrcListEnlarge(db, pSrc, nSubSrc-1,iFrom+1);
93080 if( db->mallocFailed ){
93081 break;
93085 /* Transfer the FROM clause terms from the subquery into the
93086 ** outer query.
93088 for(i=0; i<nSubSrc; i++){
93089 sqlite3IdListDelete(db, pSrc->a[i+iFrom].pUsing);
93090 pSrc->a[i+iFrom] = pSubSrc->a[i];
93091 memset(&pSubSrc->a[i], 0, sizeof(pSubSrc->a[i]));
93093 pSrc->a[iFrom].jointype = jointype;
93095 /* Now begin substituting subquery result set expressions for
93096 ** references to the iParent in the outer query.
93098 ** Example:
93100 ** SELECT a+5, b*10 FROM (SELECT x*3 AS a, y+10 AS b FROM t1) WHERE a>b;
93101 ** \ \_____________ subquery __________/ /
93102 ** \_____________________ outer query ______________________________/
93104 ** We look at every expression in the outer query and every place we see
93105 ** "a" we substitute "x*3" and every place we see "b" we substitute "y+10".
93107 pList = pParent->pEList;
93108 for(i=0; i<pList->nExpr; i++){
93109 if( pList->a[i].zName==0 ){
93110 const char *zSpan = pList->a[i].zSpan;
93111 if( ALWAYS(zSpan) ){
93112 pList->a[i].zName = sqlite3DbStrDup(db, zSpan);
93116 substExprList(db, pParent->pEList, iParent, pSub->pEList);
93117 if( isAgg ){
93118 substExprList(db, pParent->pGroupBy, iParent, pSub->pEList);
93119 pParent->pHaving = substExpr(db, pParent->pHaving, iParent, pSub->pEList);
93121 if( pSub->pOrderBy ){
93122 assert( pParent->pOrderBy==0 );
93123 pParent->pOrderBy = pSub->pOrderBy;
93124 pSub->pOrderBy = 0;
93125 }else if( pParent->pOrderBy ){
93126 substExprList(db, pParent->pOrderBy, iParent, pSub->pEList);
93128 if( pSub->pWhere ){
93129 pWhere = sqlite3ExprDup(db, pSub->pWhere, 0);
93130 }else{
93131 pWhere = 0;
93133 if( subqueryIsAgg ){
93134 assert( pParent->pHaving==0 );
93135 pParent->pHaving = pParent->pWhere;
93136 pParent->pWhere = pWhere;
93137 pParent->pHaving = substExpr(db, pParent->pHaving, iParent, pSub->pEList);
93138 pParent->pHaving = sqlite3ExprAnd(db, pParent->pHaving,
93139 sqlite3ExprDup(db, pSub->pHaving, 0));
93140 assert( pParent->pGroupBy==0 );
93141 pParent->pGroupBy = sqlite3ExprListDup(db, pSub->pGroupBy, 0);
93142 }else{
93143 pParent->pWhere = substExpr(db, pParent->pWhere, iParent, pSub->pEList);
93144 pParent->pWhere = sqlite3ExprAnd(db, pParent->pWhere, pWhere);
93147 /* The flattened query is distinct if either the inner or the
93148 ** outer query is distinct.
93150 pParent->selFlags |= pSub->selFlags & SF_Distinct;
93153 ** SELECT ... FROM (SELECT ... LIMIT a OFFSET b) LIMIT x OFFSET y;
93155 ** One is tempted to try to add a and b to combine the limits. But this
93156 ** does not work if either limit is negative.
93158 if( pSub->pLimit ){
93159 pParent->pLimit = pSub->pLimit;
93160 pSub->pLimit = 0;
93164 /* Finially, delete what is left of the subquery and return
93165 ** success.
93167 sqlite3SelectDelete(db, pSub1);
93169 return 1;
93171 #endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */
93174 ** Analyze the SELECT statement passed as an argument to see if it
93175 ** is a min() or max() query. Return WHERE_ORDERBY_MIN or WHERE_ORDERBY_MAX if
93176 ** it is, or 0 otherwise. At present, a query is considered to be
93177 ** a min()/max() query if:
93179 ** 1. There is a single object in the FROM clause.
93181 ** 2. There is a single expression in the result set, and it is
93182 ** either min(x) or max(x), where x is a column reference.
93184 static u8 minMaxQuery(Select *p){
93185 Expr *pExpr;
93186 ExprList *pEList = p->pEList;
93188 if( pEList->nExpr!=1 ) return WHERE_ORDERBY_NORMAL;
93189 pExpr = pEList->a[0].pExpr;
93190 if( pExpr->op!=TK_AGG_FUNCTION ) return 0;
93191 if( NEVER(ExprHasProperty(pExpr, EP_xIsSelect)) ) return 0;
93192 pEList = pExpr->x.pList;
93193 if( pEList==0 || pEList->nExpr!=1 ) return 0;
93194 if( pEList->a[0].pExpr->op!=TK_AGG_COLUMN ) return WHERE_ORDERBY_NORMAL;
93195 assert( !ExprHasProperty(pExpr, EP_IntValue) );
93196 if( sqlite3StrICmp(pExpr->u.zToken,"min")==0 ){
93197 return WHERE_ORDERBY_MIN;
93198 }else if( sqlite3StrICmp(pExpr->u.zToken,"max")==0 ){
93199 return WHERE_ORDERBY_MAX;
93201 return WHERE_ORDERBY_NORMAL;
93205 ** The select statement passed as the first argument is an aggregate query.
93206 ** The second argment is the associated aggregate-info object. This
93207 ** function tests if the SELECT is of the form:
93209 ** SELECT count(*) FROM <tbl>
93211 ** where table is a database table, not a sub-select or view. If the query
93212 ** does match this pattern, then a pointer to the Table object representing
93213 ** <tbl> is returned. Otherwise, 0 is returned.
93215 static Table *isSimpleCount(Select *p, AggInfo *pAggInfo){
93216 Table *pTab;
93217 Expr *pExpr;
93219 assert( !p->pGroupBy );
93221 if( p->pWhere || p->pEList->nExpr!=1
93222 || p->pSrc->nSrc!=1 || p->pSrc->a[0].pSelect
93224 return 0;
93226 pTab = p->pSrc->a[0].pTab;
93227 pExpr = p->pEList->a[0].pExpr;
93228 assert( pTab && !pTab->pSelect && pExpr );
93230 if( IsVirtual(pTab) ) return 0;
93231 if( pExpr->op!=TK_AGG_FUNCTION ) return 0;
93232 if( (pAggInfo->aFunc[0].pFunc->flags&SQLITE_FUNC_COUNT)==0 ) return 0;
93233 if( pExpr->flags&EP_Distinct ) return 0;
93235 return pTab;
93239 ** If the source-list item passed as an argument was augmented with an
93240 ** INDEXED BY clause, then try to locate the specified index. If there
93241 ** was such a clause and the named index cannot be found, return
93242 ** SQLITE_ERROR and leave an error in pParse. Otherwise, populate
93243 ** pFrom->pIndex and return SQLITE_OK.
93245 SQLITE_PRIVATE int sqlite3IndexedByLookup(Parse *pParse, struct SrcList_item *pFrom){
93246 if( pFrom->pTab && pFrom->zIndex ){
93247 Table *pTab = pFrom->pTab;
93248 char *zIndex = pFrom->zIndex;
93249 Index *pIdx;
93250 for(pIdx=pTab->pIndex;
93251 pIdx && sqlite3StrICmp(pIdx->zName, zIndex);
93252 pIdx=pIdx->pNext
93254 if( !pIdx ){
93255 sqlite3ErrorMsg(pParse, "no such index: %s", zIndex, 0);
93256 pParse->checkSchema = 1;
93257 return SQLITE_ERROR;
93259 pFrom->pIndex = pIdx;
93261 return SQLITE_OK;
93265 ** This routine is a Walker callback for "expanding" a SELECT statement.
93266 ** "Expanding" means to do the following:
93268 ** (1) Make sure VDBE cursor numbers have been assigned to every
93269 ** element of the FROM clause.
93271 ** (2) Fill in the pTabList->a[].pTab fields in the SrcList that
93272 ** defines FROM clause. When views appear in the FROM clause,
93273 ** fill pTabList->a[].pSelect with a copy of the SELECT statement
93274 ** that implements the view. A copy is made of the view's SELECT
93275 ** statement so that we can freely modify or delete that statement
93276 ** without worrying about messing up the presistent representation
93277 ** of the view.
93279 ** (3) Add terms to the WHERE clause to accomodate the NATURAL keyword
93280 ** on joins and the ON and USING clause of joins.
93282 ** (4) Scan the list of columns in the result set (pEList) looking
93283 ** for instances of the "*" operator or the TABLE.* operator.
93284 ** If found, expand each "*" to be every column in every table
93285 ** and TABLE.* to be every column in TABLE.
93288 static int selectExpander(Walker *pWalker, Select *p){
93289 Parse *pParse = pWalker->pParse;
93290 int i, j, k;
93291 SrcList *pTabList;
93292 ExprList *pEList;
93293 struct SrcList_item *pFrom;
93294 sqlite3 *db = pParse->db;
93296 if( db->mallocFailed ){
93297 return WRC_Abort;
93299 if( NEVER(p->pSrc==0) || (p->selFlags & SF_Expanded)!=0 ){
93300 return WRC_Prune;
93302 p->selFlags |= SF_Expanded;
93303 pTabList = p->pSrc;
93304 pEList = p->pEList;
93306 /* Make sure cursor numbers have been assigned to all entries in
93307 ** the FROM clause of the SELECT statement.
93309 sqlite3SrcListAssignCursors(pParse, pTabList);
93311 /* Look up every table named in the FROM clause of the select. If
93312 ** an entry of the FROM clause is a subquery instead of a table or view,
93313 ** then create a transient table structure to describe the subquery.
93315 for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
93316 Table *pTab;
93317 if( pFrom->pTab!=0 ){
93318 /* This statement has already been prepared. There is no need
93319 ** to go further. */
93320 assert( i==0 );
93321 return WRC_Prune;
93323 if( pFrom->zName==0 ){
93324 #ifndef SQLITE_OMIT_SUBQUERY
93325 Select *pSel = pFrom->pSelect;
93326 /* A sub-query in the FROM clause of a SELECT */
93327 assert( pSel!=0 );
93328 assert( pFrom->pTab==0 );
93329 sqlite3WalkSelect(pWalker, pSel);
93330 pFrom->pTab = pTab = sqlite3DbMallocZero(db, sizeof(Table));
93331 if( pTab==0 ) return WRC_Abort;
93332 pTab->nRef = 1;
93333 pTab->zName = sqlite3MPrintf(db, "sqlite_subquery_%p_", (void*)pTab);
93334 while( pSel->pPrior ){ pSel = pSel->pPrior; }
93335 selectColumnsFromExprList(pParse, pSel->pEList, &pTab->nCol, &pTab->aCol);
93336 pTab->iPKey = -1;
93337 pTab->nRowEst = 1000000;
93338 pTab->tabFlags |= TF_Ephemeral;
93339 #endif
93340 }else{
93341 /* An ordinary table or view name in the FROM clause */
93342 assert( pFrom->pTab==0 );
93343 pFrom->pTab = pTab =
93344 sqlite3LocateTable(pParse,0,pFrom->zName,pFrom->zDatabase);
93345 if( pTab==0 ) return WRC_Abort;
93346 pTab->nRef++;
93347 #if !defined(SQLITE_OMIT_VIEW) || !defined (SQLITE_OMIT_VIRTUALTABLE)
93348 if( pTab->pSelect || IsVirtual(pTab) ){
93349 /* We reach here if the named table is a really a view */
93350 if( sqlite3ViewGetColumnNames(pParse, pTab) ) return WRC_Abort;
93351 assert( pFrom->pSelect==0 );
93352 pFrom->pSelect = sqlite3SelectDup(db, pTab->pSelect, 0);
93353 sqlite3WalkSelect(pWalker, pFrom->pSelect);
93355 #endif
93358 /* Locate the index named by the INDEXED BY clause, if any. */
93359 if( sqlite3IndexedByLookup(pParse, pFrom) ){
93360 return WRC_Abort;
93364 /* Process NATURAL keywords, and ON and USING clauses of joins.
93366 if( db->mallocFailed || sqliteProcessJoin(pParse, p) ){
93367 return WRC_Abort;
93370 /* For every "*" that occurs in the column list, insert the names of
93371 ** all columns in all tables. And for every TABLE.* insert the names
93372 ** of all columns in TABLE. The parser inserted a special expression
93373 ** with the TK_ALL operator for each "*" that it found in the column list.
93374 ** The following code just has to locate the TK_ALL expressions and expand
93375 ** each one to the list of all columns in all tables.
93377 ** The first loop just checks to see if there are any "*" operators
93378 ** that need expanding.
93380 for(k=0; k<pEList->nExpr; k++){
93381 Expr *pE = pEList->a[k].pExpr;
93382 if( pE->op==TK_ALL ) break;
93383 assert( pE->op!=TK_DOT || pE->pRight!=0 );
93384 assert( pE->op!=TK_DOT || (pE->pLeft!=0 && pE->pLeft->op==TK_ID) );
93385 if( pE->op==TK_DOT && pE->pRight->op==TK_ALL ) break;
93387 if( k<pEList->nExpr ){
93389 ** If we get here it means the result set contains one or more "*"
93390 ** operators that need to be expanded. Loop through each expression
93391 ** in the result set and expand them one by one.
93393 struct ExprList_item *a = pEList->a;
93394 ExprList *pNew = 0;
93395 int flags = pParse->db->flags;
93396 int longNames = (flags & SQLITE_FullColNames)!=0
93397 && (flags & SQLITE_ShortColNames)==0;
93399 for(k=0; k<pEList->nExpr; k++){
93400 Expr *pE = a[k].pExpr;
93401 assert( pE->op!=TK_DOT || pE->pRight!=0 );
93402 if( pE->op!=TK_ALL && (pE->op!=TK_DOT || pE->pRight->op!=TK_ALL) ){
93403 /* This particular expression does not need to be expanded.
93405 pNew = sqlite3ExprListAppend(pParse, pNew, a[k].pExpr);
93406 if( pNew ){
93407 pNew->a[pNew->nExpr-1].zName = a[k].zName;
93408 pNew->a[pNew->nExpr-1].zSpan = a[k].zSpan;
93409 a[k].zName = 0;
93410 a[k].zSpan = 0;
93412 a[k].pExpr = 0;
93413 }else{
93414 /* This expression is a "*" or a "TABLE.*" and needs to be
93415 ** expanded. */
93416 int tableSeen = 0; /* Set to 1 when TABLE matches */
93417 char *zTName; /* text of name of TABLE */
93418 if( pE->op==TK_DOT ){
93419 assert( pE->pLeft!=0 );
93420 assert( !ExprHasProperty(pE->pLeft, EP_IntValue) );
93421 zTName = pE->pLeft->u.zToken;
93422 }else{
93423 zTName = 0;
93425 for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
93426 Table *pTab = pFrom->pTab;
93427 char *zTabName = pFrom->zAlias;
93428 if( zTabName==0 ){
93429 zTabName = pTab->zName;
93431 if( db->mallocFailed ) break;
93432 if( zTName && sqlite3StrICmp(zTName, zTabName)!=0 ){
93433 continue;
93435 tableSeen = 1;
93436 for(j=0; j<pTab->nCol; j++){
93437 Expr *pExpr, *pRight;
93438 char *zName = pTab->aCol[j].zName;
93439 char *zColname; /* The computed column name */
93440 char *zToFree; /* Malloced string that needs to be freed */
93441 Token sColname; /* Computed column name as a token */
93443 /* If a column is marked as 'hidden' (currently only possible
93444 ** for virtual tables), do not include it in the expanded
93445 ** result-set list.
93447 if( IsHiddenColumn(&pTab->aCol[j]) ){
93448 assert(IsVirtual(pTab));
93449 continue;
93452 if( i>0 && zTName==0 ){
93453 if( (pFrom->jointype & JT_NATURAL)!=0
93454 && tableAndColumnIndex(pTabList, i, zName, 0, 0)
93456 /* In a NATURAL join, omit the join columns from the
93457 ** table to the right of the join */
93458 continue;
93460 if( sqlite3IdListIndex(pFrom->pUsing, zName)>=0 ){
93461 /* In a join with a USING clause, omit columns in the
93462 ** using clause from the table on the right. */
93463 continue;
93466 pRight = sqlite3Expr(db, TK_ID, zName);
93467 zColname = zName;
93468 zToFree = 0;
93469 if( longNames || pTabList->nSrc>1 ){
93470 Expr *pLeft;
93471 pLeft = sqlite3Expr(db, TK_ID, zTabName);
93472 pExpr = sqlite3PExpr(pParse, TK_DOT, pLeft, pRight, 0);
93473 if( longNames ){
93474 zColname = sqlite3MPrintf(db, "%s.%s", zTabName, zName);
93475 zToFree = zColname;
93477 }else{
93478 pExpr = pRight;
93480 pNew = sqlite3ExprListAppend(pParse, pNew, pExpr);
93481 sColname.z = zColname;
93482 sColname.n = sqlite3Strlen30(zColname);
93483 sqlite3ExprListSetName(pParse, pNew, &sColname, 0);
93484 sqlite3DbFree(db, zToFree);
93487 if( !tableSeen ){
93488 if( zTName ){
93489 sqlite3ErrorMsg(pParse, "no such table: %s", zTName);
93490 }else{
93491 sqlite3ErrorMsg(pParse, "no tables specified");
93496 sqlite3ExprListDelete(db, pEList);
93497 p->pEList = pNew;
93499 #if SQLITE_MAX_COLUMN
93500 if( p->pEList && p->pEList->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
93501 sqlite3ErrorMsg(pParse, "too many columns in result set");
93503 #endif
93504 return WRC_Continue;
93508 ** No-op routine for the parse-tree walker.
93510 ** When this routine is the Walker.xExprCallback then expression trees
93511 ** are walked without any actions being taken at each node. Presumably,
93512 ** when this routine is used for Walker.xExprCallback then
93513 ** Walker.xSelectCallback is set to do something useful for every
93514 ** subquery in the parser tree.
93516 static int exprWalkNoop(Walker *NotUsed, Expr *NotUsed2){
93517 UNUSED_PARAMETER2(NotUsed, NotUsed2);
93518 return WRC_Continue;
93522 ** This routine "expands" a SELECT statement and all of its subqueries.
93523 ** For additional information on what it means to "expand" a SELECT
93524 ** statement, see the comment on the selectExpand worker callback above.
93526 ** Expanding a SELECT statement is the first step in processing a
93527 ** SELECT statement. The SELECT statement must be expanded before
93528 ** name resolution is performed.
93530 ** If anything goes wrong, an error message is written into pParse.
93531 ** The calling function can detect the problem by looking at pParse->nErr
93532 ** and/or pParse->db->mallocFailed.
93534 static void sqlite3SelectExpand(Parse *pParse, Select *pSelect){
93535 Walker w;
93536 w.xSelectCallback = selectExpander;
93537 w.xExprCallback = exprWalkNoop;
93538 w.pParse = pParse;
93539 sqlite3WalkSelect(&w, pSelect);
93543 #ifndef SQLITE_OMIT_SUBQUERY
93545 ** This is a Walker.xSelectCallback callback for the sqlite3SelectTypeInfo()
93546 ** interface.
93548 ** For each FROM-clause subquery, add Column.zType and Column.zColl
93549 ** information to the Table structure that represents the result set
93550 ** of that subquery.
93552 ** The Table structure that represents the result set was constructed
93553 ** by selectExpander() but the type and collation information was omitted
93554 ** at that point because identifiers had not yet been resolved. This
93555 ** routine is called after identifier resolution.
93557 static int selectAddSubqueryTypeInfo(Walker *pWalker, Select *p){
93558 Parse *pParse;
93559 int i;
93560 SrcList *pTabList;
93561 struct SrcList_item *pFrom;
93563 assert( p->selFlags & SF_Resolved );
93564 if( (p->selFlags & SF_HasTypeInfo)==0 ){
93565 p->selFlags |= SF_HasTypeInfo;
93566 pParse = pWalker->pParse;
93567 pTabList = p->pSrc;
93568 for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
93569 Table *pTab = pFrom->pTab;
93570 if( ALWAYS(pTab!=0) && (pTab->tabFlags & TF_Ephemeral)!=0 ){
93571 /* A sub-query in the FROM clause of a SELECT */
93572 Select *pSel = pFrom->pSelect;
93573 assert( pSel );
93574 while( pSel->pPrior ) pSel = pSel->pPrior;
93575 selectAddColumnTypeAndCollation(pParse, pTab->nCol, pTab->aCol, pSel);
93579 return WRC_Continue;
93581 #endif
93585 ** This routine adds datatype and collating sequence information to
93586 ** the Table structures of all FROM-clause subqueries in a
93587 ** SELECT statement.
93589 ** Use this routine after name resolution.
93591 static void sqlite3SelectAddTypeInfo(Parse *pParse, Select *pSelect){
93592 #ifndef SQLITE_OMIT_SUBQUERY
93593 Walker w;
93594 w.xSelectCallback = selectAddSubqueryTypeInfo;
93595 w.xExprCallback = exprWalkNoop;
93596 w.pParse = pParse;
93597 sqlite3WalkSelect(&w, pSelect);
93598 #endif
93603 ** This routine sets of a SELECT statement for processing. The
93604 ** following is accomplished:
93606 ** * VDBE Cursor numbers are assigned to all FROM-clause terms.
93607 ** * Ephemeral Table objects are created for all FROM-clause subqueries.
93608 ** * ON and USING clauses are shifted into WHERE statements
93609 ** * Wildcards "*" and "TABLE.*" in result sets are expanded.
93610 ** * Identifiers in expression are matched to tables.
93612 ** This routine acts recursively on all subqueries within the SELECT.
93614 SQLITE_PRIVATE void sqlite3SelectPrep(
93615 Parse *pParse, /* The parser context */
93616 Select *p, /* The SELECT statement being coded. */
93617 NameContext *pOuterNC /* Name context for container */
93619 sqlite3 *db;
93620 if( NEVER(p==0) ) return;
93621 db = pParse->db;
93622 if( p->selFlags & SF_HasTypeInfo ) return;
93623 sqlite3SelectExpand(pParse, p);
93624 if( pParse->nErr || db->mallocFailed ) return;
93625 sqlite3ResolveSelectNames(pParse, p, pOuterNC);
93626 if( pParse->nErr || db->mallocFailed ) return;
93627 sqlite3SelectAddTypeInfo(pParse, p);
93631 ** Reset the aggregate accumulator.
93633 ** The aggregate accumulator is a set of memory cells that hold
93634 ** intermediate results while calculating an aggregate. This
93635 ** routine simply stores NULLs in all of those memory cells.
93637 static void resetAccumulator(Parse *pParse, AggInfo *pAggInfo){
93638 Vdbe *v = pParse->pVdbe;
93639 int i;
93640 struct AggInfo_func *pFunc;
93641 if( pAggInfo->nFunc+pAggInfo->nColumn==0 ){
93642 return;
93644 for(i=0; i<pAggInfo->nColumn; i++){
93645 sqlite3VdbeAddOp2(v, OP_Null, 0, pAggInfo->aCol[i].iMem);
93647 for(pFunc=pAggInfo->aFunc, i=0; i<pAggInfo->nFunc; i++, pFunc++){
93648 sqlite3VdbeAddOp2(v, OP_Null, 0, pFunc->iMem);
93649 if( pFunc->iDistinct>=0 ){
93650 Expr *pE = pFunc->pExpr;
93651 assert( !ExprHasProperty(pE, EP_xIsSelect) );
93652 if( pE->x.pList==0 || pE->x.pList->nExpr!=1 ){
93653 sqlite3ErrorMsg(pParse, "DISTINCT aggregates must have exactly one "
93654 "argument");
93655 pFunc->iDistinct = -1;
93656 }else{
93657 KeyInfo *pKeyInfo = keyInfoFromExprList(pParse, pE->x.pList);
93658 sqlite3VdbeAddOp4(v, OP_OpenEphemeral, pFunc->iDistinct, 0, 0,
93659 (char*)pKeyInfo, P4_KEYINFO_HANDOFF);
93666 ** Invoke the OP_AggFinalize opcode for every aggregate function
93667 ** in the AggInfo structure.
93669 static void finalizeAggFunctions(Parse *pParse, AggInfo *pAggInfo){
93670 Vdbe *v = pParse->pVdbe;
93671 int i;
93672 struct AggInfo_func *pF;
93673 for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){
93674 ExprList *pList = pF->pExpr->x.pList;
93675 assert( !ExprHasProperty(pF->pExpr, EP_xIsSelect) );
93676 sqlite3VdbeAddOp4(v, OP_AggFinal, pF->iMem, pList ? pList->nExpr : 0, 0,
93677 (void*)pF->pFunc, P4_FUNCDEF);
93682 ** Update the accumulator memory cells for an aggregate based on
93683 ** the current cursor position.
93685 static void updateAccumulator(Parse *pParse, AggInfo *pAggInfo){
93686 Vdbe *v = pParse->pVdbe;
93687 int i;
93688 struct AggInfo_func *pF;
93689 struct AggInfo_col *pC;
93691 pAggInfo->directMode = 1;
93692 sqlite3ExprCacheClear(pParse);
93693 for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){
93694 int nArg;
93695 int addrNext = 0;
93696 int regAgg;
93697 ExprList *pList = pF->pExpr->x.pList;
93698 assert( !ExprHasProperty(pF->pExpr, EP_xIsSelect) );
93699 if( pList ){
93700 nArg = pList->nExpr;
93701 regAgg = sqlite3GetTempRange(pParse, nArg);
93702 sqlite3ExprCodeExprList(pParse, pList, regAgg, 1);
93703 }else{
93704 nArg = 0;
93705 regAgg = 0;
93707 if( pF->iDistinct>=0 ){
93708 addrNext = sqlite3VdbeMakeLabel(v);
93709 assert( nArg==1 );
93710 codeDistinct(pParse, pF->iDistinct, addrNext, 1, regAgg);
93712 if( pF->pFunc->flags & SQLITE_FUNC_NEEDCOLL ){
93713 CollSeq *pColl = 0;
93714 struct ExprList_item *pItem;
93715 int j;
93716 assert( pList!=0 ); /* pList!=0 if pF->pFunc has NEEDCOLL */
93717 for(j=0, pItem=pList->a; !pColl && j<nArg; j++, pItem++){
93718 pColl = sqlite3ExprCollSeq(pParse, pItem->pExpr);
93720 if( !pColl ){
93721 pColl = pParse->db->pDfltColl;
93723 sqlite3VdbeAddOp4(v, OP_CollSeq, 0, 0, 0, (char *)pColl, P4_COLLSEQ);
93725 sqlite3VdbeAddOp4(v, OP_AggStep, 0, regAgg, pF->iMem,
93726 (void*)pF->pFunc, P4_FUNCDEF);
93727 sqlite3VdbeChangeP5(v, (u8)nArg);
93728 sqlite3ExprCacheAffinityChange(pParse, regAgg, nArg);
93729 sqlite3ReleaseTempRange(pParse, regAgg, nArg);
93730 if( addrNext ){
93731 sqlite3VdbeResolveLabel(v, addrNext);
93732 sqlite3ExprCacheClear(pParse);
93736 /* Before populating the accumulator registers, clear the column cache.
93737 ** Otherwise, if any of the required column values are already present
93738 ** in registers, sqlite3ExprCode() may use OP_SCopy to copy the value
93739 ** to pC->iMem. But by the time the value is used, the original register
93740 ** may have been used, invalidating the underlying buffer holding the
93741 ** text or blob value. See ticket [883034dcb5].
93743 ** Another solution would be to change the OP_SCopy used to copy cached
93744 ** values to an OP_Copy.
93746 sqlite3ExprCacheClear(pParse);
93747 for(i=0, pC=pAggInfo->aCol; i<pAggInfo->nAccumulator; i++, pC++){
93748 sqlite3ExprCode(pParse, pC->pExpr, pC->iMem);
93750 pAggInfo->directMode = 0;
93751 sqlite3ExprCacheClear(pParse);
93755 ** Add a single OP_Explain instruction to the VDBE to explain a simple
93756 ** count(*) query ("SELECT count(*) FROM pTab").
93758 #ifndef SQLITE_OMIT_EXPLAIN
93759 static void explainSimpleCount(
93760 Parse *pParse, /* Parse context */
93761 Table *pTab, /* Table being queried */
93762 Index *pIdx /* Index used to optimize scan, or NULL */
93764 if( pParse->explain==2 ){
93765 char *zEqp = sqlite3MPrintf(pParse->db, "SCAN TABLE %s %s%s(~%d rows)",
93766 pTab->zName,
93767 pIdx ? "USING COVERING INDEX " : "",
93768 pIdx ? pIdx->zName : "",
93769 pTab->nRowEst
93771 sqlite3VdbeAddOp4(
93772 pParse->pVdbe, OP_Explain, pParse->iSelectId, 0, 0, zEqp, P4_DYNAMIC
93776 #else
93777 # define explainSimpleCount(a,b,c)
93778 #endif
93781 ** Generate code for the SELECT statement given in the p argument.
93783 ** The results are distributed in various ways depending on the
93784 ** contents of the SelectDest structure pointed to by argument pDest
93785 ** as follows:
93787 ** pDest->eDest Result
93788 ** ------------ -------------------------------------------
93789 ** SRT_Output Generate a row of output (using the OP_ResultRow
93790 ** opcode) for each row in the result set.
93792 ** SRT_Mem Only valid if the result is a single column.
93793 ** Store the first column of the first result row
93794 ** in register pDest->iParm then abandon the rest
93795 ** of the query. This destination implies "LIMIT 1".
93797 ** SRT_Set The result must be a single column. Store each
93798 ** row of result as the key in table pDest->iParm.
93799 ** Apply the affinity pDest->affinity before storing
93800 ** results. Used to implement "IN (SELECT ...)".
93802 ** SRT_Union Store results as a key in a temporary table pDest->iParm.
93804 ** SRT_Except Remove results from the temporary table pDest->iParm.
93806 ** SRT_Table Store results in temporary table pDest->iParm.
93807 ** This is like SRT_EphemTab except that the table
93808 ** is assumed to already be open.
93810 ** SRT_EphemTab Create an temporary table pDest->iParm and store
93811 ** the result there. The cursor is left open after
93812 ** returning. This is like SRT_Table except that
93813 ** this destination uses OP_OpenEphemeral to create
93814 ** the table first.
93816 ** SRT_Coroutine Generate a co-routine that returns a new row of
93817 ** results each time it is invoked. The entry point
93818 ** of the co-routine is stored in register pDest->iParm.
93820 ** SRT_Exists Store a 1 in memory cell pDest->iParm if the result
93821 ** set is not empty.
93823 ** SRT_Discard Throw the results away. This is used by SELECT
93824 ** statements within triggers whose only purpose is
93825 ** the side-effects of functions.
93827 ** This routine returns the number of errors. If any errors are
93828 ** encountered, then an appropriate error message is left in
93829 ** pParse->zErrMsg.
93831 ** This routine does NOT free the Select structure passed in. The
93832 ** calling function needs to do that.
93834 SQLITE_PRIVATE int sqlite3Select(
93835 Parse *pParse, /* The parser context */
93836 Select *p, /* The SELECT statement being coded. */
93837 SelectDest *pDest /* What to do with the query results */
93839 int i, j; /* Loop counters */
93840 WhereInfo *pWInfo; /* Return from sqlite3WhereBegin() */
93841 Vdbe *v; /* The virtual machine under construction */
93842 int isAgg; /* True for select lists like "count(*)" */
93843 ExprList *pEList; /* List of columns to extract. */
93844 SrcList *pTabList; /* List of tables to select from */
93845 Expr *pWhere; /* The WHERE clause. May be NULL */
93846 ExprList *pOrderBy; /* The ORDER BY clause. May be NULL */
93847 ExprList *pGroupBy; /* The GROUP BY clause. May be NULL */
93848 Expr *pHaving; /* The HAVING clause. May be NULL */
93849 int isDistinct; /* True if the DISTINCT keyword is present */
93850 int distinct; /* Table to use for the distinct set */
93851 int rc = 1; /* Value to return from this function */
93852 int addrSortIndex; /* Address of an OP_OpenEphemeral instruction */
93853 AggInfo sAggInfo; /* Information used by aggregate queries */
93854 int iEnd; /* Address of the end of the query */
93855 sqlite3 *db; /* The database connection */
93857 #ifndef SQLITE_OMIT_EXPLAIN
93858 int iRestoreSelectId = pParse->iSelectId;
93859 pParse->iSelectId = pParse->iNextSelectId++;
93860 #endif
93862 db = pParse->db;
93863 if( p==0 || db->mallocFailed || pParse->nErr ){
93864 return 1;
93866 if( sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0) ) return 1;
93867 memset(&sAggInfo, 0, sizeof(sAggInfo));
93869 if( IgnorableOrderby(pDest) ){
93870 assert(pDest->eDest==SRT_Exists || pDest->eDest==SRT_Union ||
93871 pDest->eDest==SRT_Except || pDest->eDest==SRT_Discard);
93872 /* If ORDER BY makes no difference in the output then neither does
93873 ** DISTINCT so it can be removed too. */
93874 sqlite3ExprListDelete(db, p->pOrderBy);
93875 p->pOrderBy = 0;
93876 p->selFlags &= ~SF_Distinct;
93878 sqlite3SelectPrep(pParse, p, 0);
93879 pOrderBy = p->pOrderBy;
93880 pTabList = p->pSrc;
93881 pEList = p->pEList;
93882 if( pParse->nErr || db->mallocFailed ){
93883 goto select_end;
93885 isAgg = (p->selFlags & SF_Aggregate)!=0;
93886 assert( pEList!=0 );
93888 /* Begin generating code.
93890 v = sqlite3GetVdbe(pParse);
93891 if( v==0 ) goto select_end;
93893 /* If writing to memory or generating a set
93894 ** only a single column may be output.
93896 #ifndef SQLITE_OMIT_SUBQUERY
93897 if( checkForMultiColumnSelectError(pParse, pDest, pEList->nExpr) ){
93898 goto select_end;
93900 #endif
93902 /* Generate code for all sub-queries in the FROM clause
93904 #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
93905 for(i=0; !p->pPrior && i<pTabList->nSrc; i++){
93906 struct SrcList_item *pItem = &pTabList->a[i];
93907 SelectDest dest;
93908 Select *pSub = pItem->pSelect;
93909 int isAggSub;
93911 if( pSub==0 || pItem->isPopulated ) continue;
93913 /* Increment Parse.nHeight by the height of the largest expression
93914 ** tree refered to by this, the parent select. The child select
93915 ** may contain expression trees of at most
93916 ** (SQLITE_MAX_EXPR_DEPTH-Parse.nHeight) height. This is a bit
93917 ** more conservative than necessary, but much easier than enforcing
93918 ** an exact limit.
93920 pParse->nHeight += sqlite3SelectExprHeight(p);
93922 /* Check to see if the subquery can be absorbed into the parent. */
93923 isAggSub = (pSub->selFlags & SF_Aggregate)!=0;
93924 if( flattenSubquery(pParse, p, i, isAgg, isAggSub) ){
93925 if( isAggSub ){
93926 isAgg = 1;
93927 p->selFlags |= SF_Aggregate;
93929 i = -1;
93930 }else{
93931 sqlite3SelectDestInit(&dest, SRT_EphemTab, pItem->iCursor);
93932 assert( pItem->isPopulated==0 );
93933 explainSetInteger(pItem->iSelectId, (u8)pParse->iNextSelectId);
93934 sqlite3Select(pParse, pSub, &dest);
93935 pItem->isPopulated = 1;
93936 pItem->pTab->nRowEst = (unsigned)pSub->nSelectRow;
93938 if( /*pParse->nErr ||*/ db->mallocFailed ){
93939 goto select_end;
93941 pParse->nHeight -= sqlite3SelectExprHeight(p);
93942 pTabList = p->pSrc;
93943 if( !IgnorableOrderby(pDest) ){
93944 pOrderBy = p->pOrderBy;
93947 pEList = p->pEList;
93948 #endif
93949 pWhere = p->pWhere;
93950 pGroupBy = p->pGroupBy;
93951 pHaving = p->pHaving;
93952 isDistinct = (p->selFlags & SF_Distinct)!=0;
93954 #ifndef SQLITE_OMIT_COMPOUND_SELECT
93955 /* If there is are a sequence of queries, do the earlier ones first.
93957 if( p->pPrior ){
93958 if( p->pRightmost==0 ){
93959 Select *pLoop, *pRight = 0;
93960 int cnt = 0;
93961 int mxSelect;
93962 for(pLoop=p; pLoop; pLoop=pLoop->pPrior, cnt++){
93963 pLoop->pRightmost = p;
93964 pLoop->pNext = pRight;
93965 pRight = pLoop;
93967 mxSelect = db->aLimit[SQLITE_LIMIT_COMPOUND_SELECT];
93968 if( mxSelect && cnt>mxSelect ){
93969 sqlite3ErrorMsg(pParse, "too many terms in compound SELECT");
93970 goto select_end;
93973 rc = multiSelect(pParse, p, pDest);
93974 explainSetInteger(pParse->iSelectId, iRestoreSelectId);
93975 return rc;
93977 #endif
93979 /* If possible, rewrite the query to use GROUP BY instead of DISTINCT.
93980 ** GROUP BY might use an index, DISTINCT never does.
93982 assert( p->pGroupBy==0 || (p->selFlags & SF_Aggregate)!=0 );
93983 if( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct ){
93984 p->pGroupBy = sqlite3ExprListDup(db, p->pEList, 0);
93985 pGroupBy = p->pGroupBy;
93986 p->selFlags &= ~SF_Distinct;
93989 /* If there is both a GROUP BY and an ORDER BY clause and they are
93990 ** identical, then disable the ORDER BY clause since the GROUP BY
93991 ** will cause elements to come out in the correct order. This is
93992 ** an optimization - the correct answer should result regardless.
93993 ** Use the SQLITE_GroupByOrder flag with SQLITE_TESTCTRL_OPTIMIZER
93994 ** to disable this optimization for testing purposes.
93996 if( sqlite3ExprListCompare(p->pGroupBy, pOrderBy)==0
93997 && (db->flags & SQLITE_GroupByOrder)==0 ){
93998 pOrderBy = 0;
94001 /* If there is an ORDER BY clause, then this sorting
94002 ** index might end up being unused if the data can be
94003 ** extracted in pre-sorted order. If that is the case, then the
94004 ** OP_OpenEphemeral instruction will be changed to an OP_Noop once
94005 ** we figure out that the sorting index is not needed. The addrSortIndex
94006 ** variable is used to facilitate that change.
94008 if( pOrderBy ){
94009 KeyInfo *pKeyInfo;
94010 pKeyInfo = keyInfoFromExprList(pParse, pOrderBy);
94011 pOrderBy->iECursor = pParse->nTab++;
94012 p->addrOpenEphm[2] = addrSortIndex =
94013 sqlite3VdbeAddOp4(v, OP_OpenEphemeral,
94014 pOrderBy->iECursor, pOrderBy->nExpr+2, 0,
94015 (char*)pKeyInfo, P4_KEYINFO_HANDOFF);
94016 }else{
94017 addrSortIndex = -1;
94020 /* If the output is destined for a temporary table, open that table.
94022 if( pDest->eDest==SRT_EphemTab ){
94023 sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pDest->iParm, pEList->nExpr);
94026 /* Set the limiter.
94028 iEnd = sqlite3VdbeMakeLabel(v);
94029 p->nSelectRow = (double)LARGEST_INT64;
94030 computeLimitRegisters(pParse, p, iEnd);
94032 /* Open a virtual index to use for the distinct set.
94034 if( p->selFlags & SF_Distinct ){
94035 KeyInfo *pKeyInfo;
94036 assert( isAgg || pGroupBy );
94037 distinct = pParse->nTab++;
94038 pKeyInfo = keyInfoFromExprList(pParse, p->pEList);
94039 sqlite3VdbeAddOp4(v, OP_OpenEphemeral, distinct, 0, 0,
94040 (char*)pKeyInfo, P4_KEYINFO_HANDOFF);
94041 sqlite3VdbeChangeP5(v, BTREE_UNORDERED);
94042 }else{
94043 distinct = -1;
94046 /* Aggregate and non-aggregate queries are handled differently */
94047 if( !isAgg && pGroupBy==0 ){
94048 /* This case is for non-aggregate queries
94049 ** Begin the database scan
94051 pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, &pOrderBy, 0);
94052 if( pWInfo==0 ) goto select_end;
94053 if( pWInfo->nRowOut < p->nSelectRow ) p->nSelectRow = pWInfo->nRowOut;
94055 /* If sorting index that was created by a prior OP_OpenEphemeral
94056 ** instruction ended up not being needed, then change the OP_OpenEphemeral
94057 ** into an OP_Noop.
94059 if( addrSortIndex>=0 && pOrderBy==0 ){
94060 sqlite3VdbeChangeToNoop(v, addrSortIndex, 1);
94061 p->addrOpenEphm[2] = -1;
94064 /* Use the standard inner loop
94066 assert(!isDistinct);
94067 selectInnerLoop(pParse, p, pEList, 0, 0, pOrderBy, -1, pDest,
94068 pWInfo->iContinue, pWInfo->iBreak);
94070 /* End the database scan loop.
94072 sqlite3WhereEnd(pWInfo);
94073 }else{
94074 /* This is the processing for aggregate queries */
94075 NameContext sNC; /* Name context for processing aggregate information */
94076 int iAMem; /* First Mem address for storing current GROUP BY */
94077 int iBMem; /* First Mem address for previous GROUP BY */
94078 int iUseFlag; /* Mem address holding flag indicating that at least
94079 ** one row of the input to the aggregator has been
94080 ** processed */
94081 int iAbortFlag; /* Mem address which causes query abort if positive */
94082 int groupBySort; /* Rows come from source in GROUP BY order */
94083 int addrEnd; /* End of processing for this SELECT */
94085 /* Remove any and all aliases between the result set and the
94086 ** GROUP BY clause.
94088 if( pGroupBy ){
94089 int k; /* Loop counter */
94090 struct ExprList_item *pItem; /* For looping over expression in a list */
94092 for(k=p->pEList->nExpr, pItem=p->pEList->a; k>0; k--, pItem++){
94093 pItem->iAlias = 0;
94095 for(k=pGroupBy->nExpr, pItem=pGroupBy->a; k>0; k--, pItem++){
94096 pItem->iAlias = 0;
94098 if( p->nSelectRow>(double)100 ) p->nSelectRow = (double)100;
94099 }else{
94100 p->nSelectRow = (double)1;
94104 /* Create a label to jump to when we want to abort the query */
94105 addrEnd = sqlite3VdbeMakeLabel(v);
94107 /* Convert TK_COLUMN nodes into TK_AGG_COLUMN and make entries in
94108 ** sAggInfo for all TK_AGG_FUNCTION nodes in expressions of the
94109 ** SELECT statement.
94111 memset(&sNC, 0, sizeof(sNC));
94112 sNC.pParse = pParse;
94113 sNC.pSrcList = pTabList;
94114 sNC.pAggInfo = &sAggInfo;
94115 sAggInfo.nSortingColumn = pGroupBy ? pGroupBy->nExpr+1 : 0;
94116 sAggInfo.pGroupBy = pGroupBy;
94117 sqlite3ExprAnalyzeAggList(&sNC, pEList);
94118 sqlite3ExprAnalyzeAggList(&sNC, pOrderBy);
94119 if( pHaving ){
94120 sqlite3ExprAnalyzeAggregates(&sNC, pHaving);
94122 sAggInfo.nAccumulator = sAggInfo.nColumn;
94123 for(i=0; i<sAggInfo.nFunc; i++){
94124 assert( !ExprHasProperty(sAggInfo.aFunc[i].pExpr, EP_xIsSelect) );
94125 sqlite3ExprAnalyzeAggList(&sNC, sAggInfo.aFunc[i].pExpr->x.pList);
94127 if( db->mallocFailed ) goto select_end;
94129 /* Processing for aggregates with GROUP BY is very different and
94130 ** much more complex than aggregates without a GROUP BY.
94132 if( pGroupBy ){
94133 KeyInfo *pKeyInfo; /* Keying information for the group by clause */
94134 int j1; /* A-vs-B comparision jump */
94135 int addrOutputRow; /* Start of subroutine that outputs a result row */
94136 int regOutputRow; /* Return address register for output subroutine */
94137 int addrSetAbort; /* Set the abort flag and return */
94138 int addrTopOfLoop; /* Top of the input loop */
94139 int addrSortingIdx; /* The OP_OpenEphemeral for the sorting index */
94140 int addrReset; /* Subroutine for resetting the accumulator */
94141 int regReset; /* Return address register for reset subroutine */
94143 /* If there is a GROUP BY clause we might need a sorting index to
94144 ** implement it. Allocate that sorting index now. If it turns out
94145 ** that we do not need it after all, the OpenEphemeral instruction
94146 ** will be converted into a Noop.
94148 sAggInfo.sortingIdx = pParse->nTab++;
94149 pKeyInfo = keyInfoFromExprList(pParse, pGroupBy);
94150 addrSortingIdx = sqlite3VdbeAddOp4(v, OP_OpenEphemeral,
94151 sAggInfo.sortingIdx, sAggInfo.nSortingColumn,
94152 0, (char*)pKeyInfo, P4_KEYINFO_HANDOFF);
94154 /* Initialize memory locations used by GROUP BY aggregate processing
94156 iUseFlag = ++pParse->nMem;
94157 iAbortFlag = ++pParse->nMem;
94158 regOutputRow = ++pParse->nMem;
94159 addrOutputRow = sqlite3VdbeMakeLabel(v);
94160 regReset = ++pParse->nMem;
94161 addrReset = sqlite3VdbeMakeLabel(v);
94162 iAMem = pParse->nMem + 1;
94163 pParse->nMem += pGroupBy->nExpr;
94164 iBMem = pParse->nMem + 1;
94165 pParse->nMem += pGroupBy->nExpr;
94166 sqlite3VdbeAddOp2(v, OP_Integer, 0, iAbortFlag);
94167 VdbeComment((v, "clear abort flag"));
94168 sqlite3VdbeAddOp2(v, OP_Integer, 0, iUseFlag);
94169 VdbeComment((v, "indicate accumulator empty"));
94171 /* Begin a loop that will extract all source rows in GROUP BY order.
94172 ** This might involve two separate loops with an OP_Sort in between, or
94173 ** it might be a single loop that uses an index to extract information
94174 ** in the right order to begin with.
94176 sqlite3VdbeAddOp2(v, OP_Gosub, regReset, addrReset);
94177 pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, &pGroupBy, 0);
94178 if( pWInfo==0 ) goto select_end;
94179 if( pGroupBy==0 ){
94180 /* The optimizer is able to deliver rows in group by order so
94181 ** we do not have to sort. The OP_OpenEphemeral table will be
94182 ** cancelled later because we still need to use the pKeyInfo
94184 pGroupBy = p->pGroupBy;
94185 groupBySort = 0;
94186 }else{
94187 /* Rows are coming out in undetermined order. We have to push
94188 ** each row into a sorting index, terminate the first loop,
94189 ** then loop over the sorting index in order to get the output
94190 ** in sorted order
94192 int regBase;
94193 int regRecord;
94194 int nCol;
94195 int nGroupBy;
94197 explainTempTable(pParse,
94198 isDistinct && !(p->selFlags&SF_Distinct)?"DISTINCT":"GROUP BY");
94200 groupBySort = 1;
94201 nGroupBy = pGroupBy->nExpr;
94202 nCol = nGroupBy + 1;
94203 j = nGroupBy+1;
94204 for(i=0; i<sAggInfo.nColumn; i++){
94205 if( sAggInfo.aCol[i].iSorterColumn>=j ){
94206 nCol++;
94207 j++;
94210 regBase = sqlite3GetTempRange(pParse, nCol);
94211 sqlite3ExprCacheClear(pParse);
94212 sqlite3ExprCodeExprList(pParse, pGroupBy, regBase, 0);
94213 sqlite3VdbeAddOp2(v, OP_Sequence, sAggInfo.sortingIdx,regBase+nGroupBy);
94214 j = nGroupBy+1;
94215 for(i=0; i<sAggInfo.nColumn; i++){
94216 struct AggInfo_col *pCol = &sAggInfo.aCol[i];
94217 if( pCol->iSorterColumn>=j ){
94218 int r1 = j + regBase;
94219 int r2;
94221 r2 = sqlite3ExprCodeGetColumn(pParse,
94222 pCol->pTab, pCol->iColumn, pCol->iTable, r1);
94223 if( r1!=r2 ){
94224 sqlite3VdbeAddOp2(v, OP_SCopy, r2, r1);
94226 j++;
94229 regRecord = sqlite3GetTempReg(pParse);
94230 sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nCol, regRecord);
94231 sqlite3VdbeAddOp2(v, OP_IdxInsert, sAggInfo.sortingIdx, regRecord);
94232 sqlite3ReleaseTempReg(pParse, regRecord);
94233 sqlite3ReleaseTempRange(pParse, regBase, nCol);
94234 sqlite3WhereEnd(pWInfo);
94235 sqlite3VdbeAddOp2(v, OP_Sort, sAggInfo.sortingIdx, addrEnd);
94236 VdbeComment((v, "GROUP BY sort"));
94237 sAggInfo.useSortingIdx = 1;
94238 sqlite3ExprCacheClear(pParse);
94241 /* Evaluate the current GROUP BY terms and store in b0, b1, b2...
94242 ** (b0 is memory location iBMem+0, b1 is iBMem+1, and so forth)
94243 ** Then compare the current GROUP BY terms against the GROUP BY terms
94244 ** from the previous row currently stored in a0, a1, a2...
94246 addrTopOfLoop = sqlite3VdbeCurrentAddr(v);
94247 sqlite3ExprCacheClear(pParse);
94248 for(j=0; j<pGroupBy->nExpr; j++){
94249 if( groupBySort ){
94250 sqlite3VdbeAddOp3(v, OP_Column, sAggInfo.sortingIdx, j, iBMem+j);
94251 }else{
94252 sAggInfo.directMode = 1;
94253 sqlite3ExprCode(pParse, pGroupBy->a[j].pExpr, iBMem+j);
94256 sqlite3VdbeAddOp4(v, OP_Compare, iAMem, iBMem, pGroupBy->nExpr,
94257 (char*)pKeyInfo, P4_KEYINFO);
94258 j1 = sqlite3VdbeCurrentAddr(v);
94259 sqlite3VdbeAddOp3(v, OP_Jump, j1+1, 0, j1+1);
94261 /* Generate code that runs whenever the GROUP BY changes.
94262 ** Changes in the GROUP BY are detected by the previous code
94263 ** block. If there were no changes, this block is skipped.
94265 ** This code copies current group by terms in b0,b1,b2,...
94266 ** over to a0,a1,a2. It then calls the output subroutine
94267 ** and resets the aggregate accumulator registers in preparation
94268 ** for the next GROUP BY batch.
94270 sqlite3ExprCodeMove(pParse, iBMem, iAMem, pGroupBy->nExpr);
94271 sqlite3VdbeAddOp2(v, OP_Gosub, regOutputRow, addrOutputRow);
94272 VdbeComment((v, "output one row"));
94273 sqlite3VdbeAddOp2(v, OP_IfPos, iAbortFlag, addrEnd);
94274 VdbeComment((v, "check abort flag"));
94275 sqlite3VdbeAddOp2(v, OP_Gosub, regReset, addrReset);
94276 VdbeComment((v, "reset accumulator"));
94278 /* Update the aggregate accumulators based on the content of
94279 ** the current row
94281 sqlite3VdbeJumpHere(v, j1);
94282 updateAccumulator(pParse, &sAggInfo);
94283 sqlite3VdbeAddOp2(v, OP_Integer, 1, iUseFlag);
94284 VdbeComment((v, "indicate data in accumulator"));
94286 /* End of the loop
94288 if( groupBySort ){
94289 sqlite3VdbeAddOp2(v, OP_Next, sAggInfo.sortingIdx, addrTopOfLoop);
94290 }else{
94291 sqlite3WhereEnd(pWInfo);
94292 sqlite3VdbeChangeToNoop(v, addrSortingIdx, 1);
94295 /* Output the final row of result
94297 sqlite3VdbeAddOp2(v, OP_Gosub, regOutputRow, addrOutputRow);
94298 VdbeComment((v, "output final row"));
94300 /* Jump over the subroutines
94302 sqlite3VdbeAddOp2(v, OP_Goto, 0, addrEnd);
94304 /* Generate a subroutine that outputs a single row of the result
94305 ** set. This subroutine first looks at the iUseFlag. If iUseFlag
94306 ** is less than or equal to zero, the subroutine is a no-op. If
94307 ** the processing calls for the query to abort, this subroutine
94308 ** increments the iAbortFlag memory location before returning in
94309 ** order to signal the caller to abort.
94311 addrSetAbort = sqlite3VdbeCurrentAddr(v);
94312 sqlite3VdbeAddOp2(v, OP_Integer, 1, iAbortFlag);
94313 VdbeComment((v, "set abort flag"));
94314 sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
94315 sqlite3VdbeResolveLabel(v, addrOutputRow);
94316 addrOutputRow = sqlite3VdbeCurrentAddr(v);
94317 sqlite3VdbeAddOp2(v, OP_IfPos, iUseFlag, addrOutputRow+2);
94318 VdbeComment((v, "Groupby result generator entry point"));
94319 sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
94320 finalizeAggFunctions(pParse, &sAggInfo);
94321 sqlite3ExprIfFalse(pParse, pHaving, addrOutputRow+1, SQLITE_JUMPIFNULL);
94322 selectInnerLoop(pParse, p, p->pEList, 0, 0, pOrderBy,
94323 distinct, pDest,
94324 addrOutputRow+1, addrSetAbort);
94325 sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
94326 VdbeComment((v, "end groupby result generator"));
94328 /* Generate a subroutine that will reset the group-by accumulator
94330 sqlite3VdbeResolveLabel(v, addrReset);
94331 resetAccumulator(pParse, &sAggInfo);
94332 sqlite3VdbeAddOp1(v, OP_Return, regReset);
94334 } /* endif pGroupBy. Begin aggregate queries without GROUP BY: */
94335 else {
94336 ExprList *pDel = 0;
94337 #ifndef SQLITE_OMIT_BTREECOUNT
94338 Table *pTab;
94339 if( (pTab = isSimpleCount(p, &sAggInfo))!=0 ){
94340 /* If isSimpleCount() returns a pointer to a Table structure, then
94341 ** the SQL statement is of the form:
94343 ** SELECT count(*) FROM <tbl>
94345 ** where the Table structure returned represents table <tbl>.
94347 ** This statement is so common that it is optimized specially. The
94348 ** OP_Count instruction is executed either on the intkey table that
94349 ** contains the data for table <tbl> or on one of its indexes. It
94350 ** is better to execute the op on an index, as indexes are almost
94351 ** always spread across less pages than their corresponding tables.
94353 const int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
94354 const int iCsr = pParse->nTab++; /* Cursor to scan b-tree */
94355 Index *pIdx; /* Iterator variable */
94356 KeyInfo *pKeyInfo = 0; /* Keyinfo for scanned index */
94357 Index *pBest = 0; /* Best index found so far */
94358 int iRoot = pTab->tnum; /* Root page of scanned b-tree */
94360 sqlite3CodeVerifySchema(pParse, iDb);
94361 sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
94363 /* Search for the index that has the least amount of columns. If
94364 ** there is such an index, and it has less columns than the table
94365 ** does, then we can assume that it consumes less space on disk and
94366 ** will therefore be cheaper to scan to determine the query result.
94367 ** In this case set iRoot to the root page number of the index b-tree
94368 ** and pKeyInfo to the KeyInfo structure required to navigate the
94369 ** index.
94371 ** In practice the KeyInfo structure will not be used. It is only
94372 ** passed to keep OP_OpenRead happy.
94374 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
94375 if( !pBest || pIdx->nColumn<pBest->nColumn ){
94376 pBest = pIdx;
94379 if( pBest && pBest->nColumn<pTab->nCol ){
94380 iRoot = pBest->tnum;
94381 pKeyInfo = sqlite3IndexKeyinfo(pParse, pBest);
94384 /* Open a read-only cursor, execute the OP_Count, close the cursor. */
94385 sqlite3VdbeAddOp3(v, OP_OpenRead, iCsr, iRoot, iDb);
94386 if( pKeyInfo ){
94387 sqlite3VdbeChangeP4(v, -1, (char *)pKeyInfo, P4_KEYINFO_HANDOFF);
94389 sqlite3VdbeAddOp2(v, OP_Count, iCsr, sAggInfo.aFunc[0].iMem);
94390 sqlite3VdbeAddOp1(v, OP_Close, iCsr);
94391 explainSimpleCount(pParse, pTab, pBest);
94392 }else
94393 #endif /* SQLITE_OMIT_BTREECOUNT */
94395 /* Check if the query is of one of the following forms:
94397 ** SELECT min(x) FROM ...
94398 ** SELECT max(x) FROM ...
94400 ** If it is, then ask the code in where.c to attempt to sort results
94401 ** as if there was an "ORDER ON x" or "ORDER ON x DESC" clause.
94402 ** If where.c is able to produce results sorted in this order, then
94403 ** add vdbe code to break out of the processing loop after the
94404 ** first iteration (since the first iteration of the loop is
94405 ** guaranteed to operate on the row with the minimum or maximum
94406 ** value of x, the only row required).
94408 ** A special flag must be passed to sqlite3WhereBegin() to slightly
94409 ** modify behaviour as follows:
94411 ** + If the query is a "SELECT min(x)", then the loop coded by
94412 ** where.c should not iterate over any values with a NULL value
94413 ** for x.
94415 ** + The optimizer code in where.c (the thing that decides which
94416 ** index or indices to use) should place a different priority on
94417 ** satisfying the 'ORDER BY' clause than it does in other cases.
94418 ** Refer to code and comments in where.c for details.
94420 ExprList *pMinMax = 0;
94421 u8 flag = minMaxQuery(p);
94422 if( flag ){
94423 assert( !ExprHasProperty(p->pEList->a[0].pExpr, EP_xIsSelect) );
94424 pMinMax = sqlite3ExprListDup(db, p->pEList->a[0].pExpr->x.pList,0);
94425 pDel = pMinMax;
94426 if( pMinMax && !db->mallocFailed ){
94427 pMinMax->a[0].sortOrder = flag!=WHERE_ORDERBY_MIN ?1:0;
94428 pMinMax->a[0].pExpr->op = TK_COLUMN;
94432 /* This case runs if the aggregate has no GROUP BY clause. The
94433 ** processing is much simpler since there is only a single row
94434 ** of output.
94436 resetAccumulator(pParse, &sAggInfo);
94437 pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, &pMinMax, flag);
94438 if( pWInfo==0 ){
94439 sqlite3ExprListDelete(db, pDel);
94440 goto select_end;
94442 updateAccumulator(pParse, &sAggInfo);
94443 if( !pMinMax && flag ){
94444 sqlite3VdbeAddOp2(v, OP_Goto, 0, pWInfo->iBreak);
94445 VdbeComment((v, "%s() by index",
94446 (flag==WHERE_ORDERBY_MIN?"min":"max")));
94448 sqlite3WhereEnd(pWInfo);
94449 finalizeAggFunctions(pParse, &sAggInfo);
94452 pOrderBy = 0;
94453 sqlite3ExprIfFalse(pParse, pHaving, addrEnd, SQLITE_JUMPIFNULL);
94454 selectInnerLoop(pParse, p, p->pEList, 0, 0, 0, -1,
94455 pDest, addrEnd, addrEnd);
94456 sqlite3ExprListDelete(db, pDel);
94458 sqlite3VdbeResolveLabel(v, addrEnd);
94460 } /* endif aggregate query */
94462 if( distinct>=0 ){
94463 explainTempTable(pParse, "DISTINCT");
94466 /* If there is an ORDER BY clause, then we need to sort the results
94467 ** and send them to the callback one by one.
94469 if( pOrderBy ){
94470 explainTempTable(pParse, "ORDER BY");
94471 generateSortTail(pParse, p, v, pEList->nExpr, pDest);
94474 /* Jump here to skip this query
94476 sqlite3VdbeResolveLabel(v, iEnd);
94478 /* The SELECT was successfully coded. Set the return code to 0
94479 ** to indicate no errors.
94481 rc = 0;
94483 /* Control jumps to here if an error is encountered above, or upon
94484 ** successful coding of the SELECT.
94486 select_end:
94487 explainSetInteger(pParse->iSelectId, iRestoreSelectId);
94489 /* Identify column names if results of the SELECT are to be output.
94491 if( rc==SQLITE_OK && pDest->eDest==SRT_Output ){
94492 generateColumnNames(pParse, pTabList, pEList);
94495 sqlite3DbFree(db, sAggInfo.aCol);
94496 sqlite3DbFree(db, sAggInfo.aFunc);
94497 return rc;
94500 #if defined(SQLITE_DEBUG)
94502 *******************************************************************************
94503 ** The following code is used for testing and debugging only. The code
94504 ** that follows does not appear in normal builds.
94506 ** These routines are used to print out the content of all or part of a
94507 ** parse structures such as Select or Expr. Such printouts are useful
94508 ** for helping to understand what is happening inside the code generator
94509 ** during the execution of complex SELECT statements.
94511 ** These routine are not called anywhere from within the normal
94512 ** code base. Then are intended to be called from within the debugger
94513 ** or from temporary "printf" statements inserted for debugging.
94515 SQLITE_PRIVATE void sqlite3PrintExpr(Expr *p){
94516 if( !ExprHasProperty(p, EP_IntValue) && p->u.zToken ){
94517 sqlite3DebugPrintf("(%s", p->u.zToken);
94518 }else{
94519 sqlite3DebugPrintf("(%d", p->op);
94521 if( p->pLeft ){
94522 sqlite3DebugPrintf(" ");
94523 sqlite3PrintExpr(p->pLeft);
94525 if( p->pRight ){
94526 sqlite3DebugPrintf(" ");
94527 sqlite3PrintExpr(p->pRight);
94529 sqlite3DebugPrintf(")");
94531 SQLITE_PRIVATE void sqlite3PrintExprList(ExprList *pList){
94532 int i;
94533 for(i=0; i<pList->nExpr; i++){
94534 sqlite3PrintExpr(pList->a[i].pExpr);
94535 if( i<pList->nExpr-1 ){
94536 sqlite3DebugPrintf(", ");
94540 SQLITE_PRIVATE void sqlite3PrintSelect(Select *p, int indent){
94541 sqlite3DebugPrintf("%*sSELECT(%p) ", indent, "", p);
94542 sqlite3PrintExprList(p->pEList);
94543 sqlite3DebugPrintf("\n");
94544 if( p->pSrc ){
94545 char *zPrefix;
94546 int i;
94547 zPrefix = "FROM";
94548 for(i=0; i<p->pSrc->nSrc; i++){
94549 struct SrcList_item *pItem = &p->pSrc->a[i];
94550 sqlite3DebugPrintf("%*s ", indent+6, zPrefix);
94551 zPrefix = "";
94552 if( pItem->pSelect ){
94553 sqlite3DebugPrintf("(\n");
94554 sqlite3PrintSelect(pItem->pSelect, indent+10);
94555 sqlite3DebugPrintf("%*s)", indent+8, "");
94556 }else if( pItem->zName ){
94557 sqlite3DebugPrintf("%s", pItem->zName);
94559 if( pItem->pTab ){
94560 sqlite3DebugPrintf("(table: %s)", pItem->pTab->zName);
94562 if( pItem->zAlias ){
94563 sqlite3DebugPrintf(" AS %s", pItem->zAlias);
94565 if( i<p->pSrc->nSrc-1 ){
94566 sqlite3DebugPrintf(",");
94568 sqlite3DebugPrintf("\n");
94571 if( p->pWhere ){
94572 sqlite3DebugPrintf("%*s WHERE ", indent, "");
94573 sqlite3PrintExpr(p->pWhere);
94574 sqlite3DebugPrintf("\n");
94576 if( p->pGroupBy ){
94577 sqlite3DebugPrintf("%*s GROUP BY ", indent, "");
94578 sqlite3PrintExprList(p->pGroupBy);
94579 sqlite3DebugPrintf("\n");
94581 if( p->pHaving ){
94582 sqlite3DebugPrintf("%*s HAVING ", indent, "");
94583 sqlite3PrintExpr(p->pHaving);
94584 sqlite3DebugPrintf("\n");
94586 if( p->pOrderBy ){
94587 sqlite3DebugPrintf("%*s ORDER BY ", indent, "");
94588 sqlite3PrintExprList(p->pOrderBy);
94589 sqlite3DebugPrintf("\n");
94592 /* End of the structure debug printing code
94593 *****************************************************************************/
94594 #endif /* defined(SQLITE_TEST) || defined(SQLITE_DEBUG) */
94596 /************** End of select.c **********************************************/
94597 /************** Begin file table.c *******************************************/
94599 ** 2001 September 15
94601 ** The author disclaims copyright to this source code. In place of
94602 ** a legal notice, here is a blessing:
94604 ** May you do good and not evil.
94605 ** May you find forgiveness for yourself and forgive others.
94606 ** May you share freely, never taking more than you give.
94608 *************************************************************************
94609 ** This file contains the sqlite3_get_table() and sqlite3_free_table()
94610 ** interface routines. These are just wrappers around the main
94611 ** interface routine of sqlite3_exec().
94613 ** These routines are in a separate files so that they will not be linked
94614 ** if they are not used.
94617 #ifndef SQLITE_OMIT_GET_TABLE
94620 ** This structure is used to pass data from sqlite3_get_table() through
94621 ** to the callback function is uses to build the result.
94623 typedef struct TabResult {
94624 char **azResult; /* Accumulated output */
94625 char *zErrMsg; /* Error message text, if an error occurs */
94626 int nAlloc; /* Slots allocated for azResult[] */
94627 int nRow; /* Number of rows in the result */
94628 int nColumn; /* Number of columns in the result */
94629 int nData; /* Slots used in azResult[]. (nRow+1)*nColumn */
94630 int rc; /* Return code from sqlite3_exec() */
94631 } TabResult;
94634 ** This routine is called once for each row in the result table. Its job
94635 ** is to fill in the TabResult structure appropriately, allocating new
94636 ** memory as necessary.
94638 static int sqlite3_get_table_cb(void *pArg, int nCol, char **argv, char **colv){
94639 TabResult *p = (TabResult*)pArg; /* Result accumulator */
94640 int need; /* Slots needed in p->azResult[] */
94641 int i; /* Loop counter */
94642 char *z; /* A single column of result */
94644 /* Make sure there is enough space in p->azResult to hold everything
94645 ** we need to remember from this invocation of the callback.
94647 if( p->nRow==0 && argv!=0 ){
94648 need = nCol*2;
94649 }else{
94650 need = nCol;
94652 if( p->nData + need > p->nAlloc ){
94653 char **azNew;
94654 p->nAlloc = p->nAlloc*2 + need;
94655 azNew = sqlite3_realloc( p->azResult, sizeof(char*)*p->nAlloc );
94656 if( azNew==0 ) goto malloc_failed;
94657 p->azResult = azNew;
94660 /* If this is the first row, then generate an extra row containing
94661 ** the names of all columns.
94663 if( p->nRow==0 ){
94664 p->nColumn = nCol;
94665 for(i=0; i<nCol; i++){
94666 z = sqlite3_mprintf("%s", colv[i]);
94667 if( z==0 ) goto malloc_failed;
94668 p->azResult[p->nData++] = z;
94670 }else if( p->nColumn!=nCol ){
94671 sqlite3_free(p->zErrMsg);
94672 p->zErrMsg = sqlite3_mprintf(
94673 "sqlite3_get_table() called with two or more incompatible queries"
94675 p->rc = SQLITE_ERROR;
94676 return 1;
94679 /* Copy over the row data
94681 if( argv!=0 ){
94682 for(i=0; i<nCol; i++){
94683 if( argv[i]==0 ){
94684 z = 0;
94685 }else{
94686 int n = sqlite3Strlen30(argv[i])+1;
94687 z = sqlite3_malloc( n );
94688 if( z==0 ) goto malloc_failed;
94689 memcpy(z, argv[i], n);
94691 p->azResult[p->nData++] = z;
94693 p->nRow++;
94695 return 0;
94697 malloc_failed:
94698 p->rc = SQLITE_NOMEM;
94699 return 1;
94703 ** Query the database. But instead of invoking a callback for each row,
94704 ** malloc() for space to hold the result and return the entire results
94705 ** at the conclusion of the call.
94707 ** The result that is written to ***pazResult is held in memory obtained
94708 ** from malloc(). But the caller cannot free this memory directly.
94709 ** Instead, the entire table should be passed to sqlite3_free_table() when
94710 ** the calling procedure is finished using it.
94712 SQLITE_API int sqlite3_get_table(
94713 sqlite3 *db, /* The database on which the SQL executes */
94714 const char *zSql, /* The SQL to be executed */
94715 char ***pazResult, /* Write the result table here */
94716 int *pnRow, /* Write the number of rows in the result here */
94717 int *pnColumn, /* Write the number of columns of result here */
94718 char **pzErrMsg /* Write error messages here */
94720 int rc;
94721 TabResult res;
94723 *pazResult = 0;
94724 if( pnColumn ) *pnColumn = 0;
94725 if( pnRow ) *pnRow = 0;
94726 if( pzErrMsg ) *pzErrMsg = 0;
94727 res.zErrMsg = 0;
94728 res.nRow = 0;
94729 res.nColumn = 0;
94730 res.nData = 1;
94731 res.nAlloc = 20;
94732 res.rc = SQLITE_OK;
94733 res.azResult = sqlite3_malloc(sizeof(char*)*res.nAlloc );
94734 if( res.azResult==0 ){
94735 db->errCode = SQLITE_NOMEM;
94736 return SQLITE_NOMEM;
94738 res.azResult[0] = 0;
94739 rc = sqlite3_exec(db, zSql, sqlite3_get_table_cb, &res, pzErrMsg);
94740 assert( sizeof(res.azResult[0])>= sizeof(res.nData) );
94741 res.azResult[0] = SQLITE_INT_TO_PTR(res.nData);
94742 if( (rc&0xff)==SQLITE_ABORT ){
94743 sqlite3_free_table(&res.azResult[1]);
94744 if( res.zErrMsg ){
94745 if( pzErrMsg ){
94746 sqlite3_free(*pzErrMsg);
94747 *pzErrMsg = sqlite3_mprintf("%s",res.zErrMsg);
94749 sqlite3_free(res.zErrMsg);
94751 db->errCode = res.rc; /* Assume 32-bit assignment is atomic */
94752 return res.rc;
94754 sqlite3_free(res.zErrMsg);
94755 if( rc!=SQLITE_OK ){
94756 sqlite3_free_table(&res.azResult[1]);
94757 return rc;
94759 if( res.nAlloc>res.nData ){
94760 char **azNew;
94761 azNew = sqlite3_realloc( res.azResult, sizeof(char*)*res.nData );
94762 if( azNew==0 ){
94763 sqlite3_free_table(&res.azResult[1]);
94764 db->errCode = SQLITE_NOMEM;
94765 return SQLITE_NOMEM;
94767 res.azResult = azNew;
94769 *pazResult = &res.azResult[1];
94770 if( pnColumn ) *pnColumn = res.nColumn;
94771 if( pnRow ) *pnRow = res.nRow;
94772 return rc;
94776 ** This routine frees the space the sqlite3_get_table() malloced.
94778 SQLITE_API void sqlite3_free_table(
94779 char **azResult /* Result returned from from sqlite3_get_table() */
94781 if( azResult ){
94782 int i, n;
94783 azResult--;
94784 assert( azResult!=0 );
94785 n = SQLITE_PTR_TO_INT(azResult[0]);
94786 for(i=1; i<n; i++){ if( azResult[i] ) sqlite3_free(azResult[i]); }
94787 sqlite3_free(azResult);
94791 #endif /* SQLITE_OMIT_GET_TABLE */
94793 /************** End of table.c ***********************************************/
94794 /************** Begin file trigger.c *****************************************/
94797 ** The author disclaims copyright to this source code. In place of
94798 ** a legal notice, here is a blessing:
94800 ** May you do good and not evil.
94801 ** May you find forgiveness for yourself and forgive others.
94802 ** May you share freely, never taking more than you give.
94804 *************************************************************************
94805 ** This file contains the implementation for TRIGGERs
94808 #ifndef SQLITE_OMIT_TRIGGER
94810 ** Delete a linked list of TriggerStep structures.
94812 SQLITE_PRIVATE void sqlite3DeleteTriggerStep(sqlite3 *db, TriggerStep *pTriggerStep){
94813 while( pTriggerStep ){
94814 TriggerStep * pTmp = pTriggerStep;
94815 pTriggerStep = pTriggerStep->pNext;
94817 sqlite3ExprDelete(db, pTmp->pWhere);
94818 sqlite3ExprListDelete(db, pTmp->pExprList);
94819 sqlite3SelectDelete(db, pTmp->pSelect);
94820 sqlite3IdListDelete(db, pTmp->pIdList);
94822 sqlite3DbFree(db, pTmp);
94827 ** Given table pTab, return a list of all the triggers attached to
94828 ** the table. The list is connected by Trigger.pNext pointers.
94830 ** All of the triggers on pTab that are in the same database as pTab
94831 ** are already attached to pTab->pTrigger. But there might be additional
94832 ** triggers on pTab in the TEMP schema. This routine prepends all
94833 ** TEMP triggers on pTab to the beginning of the pTab->pTrigger list
94834 ** and returns the combined list.
94836 ** To state it another way: This routine returns a list of all triggers
94837 ** that fire off of pTab. The list will include any TEMP triggers on
94838 ** pTab as well as the triggers lised in pTab->pTrigger.
94840 SQLITE_PRIVATE Trigger *sqlite3TriggerList(Parse *pParse, Table *pTab){
94841 Schema * const pTmpSchema = pParse->db->aDb[1].pSchema;
94842 Trigger *pList = 0; /* List of triggers to return */
94844 if( pParse->disableTriggers ){
94845 return 0;
94848 if( pTmpSchema!=pTab->pSchema ){
94849 HashElem *p;
94850 assert( sqlite3SchemaMutexHeld(pParse->db, 0, pTmpSchema) );
94851 for(p=sqliteHashFirst(&pTmpSchema->trigHash); p; p=sqliteHashNext(p)){
94852 Trigger *pTrig = (Trigger *)sqliteHashData(p);
94853 if( pTrig->pTabSchema==pTab->pSchema
94854 && 0==sqlite3StrICmp(pTrig->table, pTab->zName)
94856 pTrig->pNext = (pList ? pList : pTab->pTrigger);
94857 pList = pTrig;
94862 return (pList ? pList : pTab->pTrigger);
94866 ** This is called by the parser when it sees a CREATE TRIGGER statement
94867 ** up to the point of the BEGIN before the trigger actions. A Trigger
94868 ** structure is generated based on the information available and stored
94869 ** in pParse->pNewTrigger. After the trigger actions have been parsed, the
94870 ** sqlite3FinishTrigger() function is called to complete the trigger
94871 ** construction process.
94873 SQLITE_PRIVATE void sqlite3BeginTrigger(
94874 Parse *pParse, /* The parse context of the CREATE TRIGGER statement */
94875 Token *pName1, /* The name of the trigger */
94876 Token *pName2, /* The name of the trigger */
94877 int tr_tm, /* One of TK_BEFORE, TK_AFTER, TK_INSTEAD */
94878 int op, /* One of TK_INSERT, TK_UPDATE, TK_DELETE */
94879 IdList *pColumns, /* column list if this is an UPDATE OF trigger */
94880 SrcList *pTableName,/* The name of the table/view the trigger applies to */
94881 Expr *pWhen, /* WHEN clause */
94882 int isTemp, /* True if the TEMPORARY keyword is present */
94883 int noErr /* Suppress errors if the trigger already exists */
94885 Trigger *pTrigger = 0; /* The new trigger */
94886 Table *pTab; /* Table that the trigger fires off of */
94887 char *zName = 0; /* Name of the trigger */
94888 sqlite3 *db = pParse->db; /* The database connection */
94889 int iDb; /* The database to store the trigger in */
94890 Token *pName; /* The unqualified db name */
94891 DbFixer sFix; /* State vector for the DB fixer */
94892 int iTabDb; /* Index of the database holding pTab */
94894 assert( pName1!=0 ); /* pName1->z might be NULL, but not pName1 itself */
94895 assert( pName2!=0 );
94896 assert( op==TK_INSERT || op==TK_UPDATE || op==TK_DELETE );
94897 assert( op>0 && op<0xff );
94898 if( isTemp ){
94899 /* If TEMP was specified, then the trigger name may not be qualified. */
94900 if( pName2->n>0 ){
94901 sqlite3ErrorMsg(pParse, "temporary trigger may not have qualified name");
94902 goto trigger_cleanup;
94904 iDb = 1;
94905 pName = pName1;
94906 }else{
94907 /* Figure out the db that the the trigger will be created in */
94908 iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
94909 if( iDb<0 ){
94910 goto trigger_cleanup;
94914 /* If the trigger name was unqualified, and the table is a temp table,
94915 ** then set iDb to 1 to create the trigger in the temporary database.
94916 ** If sqlite3SrcListLookup() returns 0, indicating the table does not
94917 ** exist, the error is caught by the block below.
94919 if( !pTableName || db->mallocFailed ){
94920 goto trigger_cleanup;
94922 pTab = sqlite3SrcListLookup(pParse, pTableName);
94923 if( db->init.busy==0 && pName2->n==0 && pTab
94924 && pTab->pSchema==db->aDb[1].pSchema ){
94925 iDb = 1;
94928 /* Ensure the table name matches database name and that the table exists */
94929 if( db->mallocFailed ) goto trigger_cleanup;
94930 assert( pTableName->nSrc==1 );
94931 if( sqlite3FixInit(&sFix, pParse, iDb, "trigger", pName) &&
94932 sqlite3FixSrcList(&sFix, pTableName) ){
94933 goto trigger_cleanup;
94935 pTab = sqlite3SrcListLookup(pParse, pTableName);
94936 if( !pTab ){
94937 /* The table does not exist. */
94938 if( db->init.iDb==1 ){
94939 /* Ticket #3810.
94940 ** Normally, whenever a table is dropped, all associated triggers are
94941 ** dropped too. But if a TEMP trigger is created on a non-TEMP table
94942 ** and the table is dropped by a different database connection, the
94943 ** trigger is not visible to the database connection that does the
94944 ** drop so the trigger cannot be dropped. This results in an
94945 ** "orphaned trigger" - a trigger whose associated table is missing.
94947 db->init.orphanTrigger = 1;
94949 goto trigger_cleanup;
94951 if( IsVirtual(pTab) ){
94952 sqlite3ErrorMsg(pParse, "cannot create triggers on virtual tables");
94953 goto trigger_cleanup;
94956 /* Check that the trigger name is not reserved and that no trigger of the
94957 ** specified name exists */
94958 zName = sqlite3NameFromToken(db, pName);
94959 if( !zName || SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
94960 goto trigger_cleanup;
94962 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
94963 if( sqlite3HashFind(&(db->aDb[iDb].pSchema->trigHash),
94964 zName, sqlite3Strlen30(zName)) ){
94965 if( !noErr ){
94966 sqlite3ErrorMsg(pParse, "trigger %T already exists", pName);
94967 }else{
94968 assert( !db->init.busy );
94969 sqlite3CodeVerifySchema(pParse, iDb);
94971 goto trigger_cleanup;
94974 /* Do not create a trigger on a system table */
94975 if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0 ){
94976 sqlite3ErrorMsg(pParse, "cannot create trigger on system table");
94977 pParse->nErr++;
94978 goto trigger_cleanup;
94981 /* INSTEAD of triggers are only for views and views only support INSTEAD
94982 ** of triggers.
94984 if( pTab->pSelect && tr_tm!=TK_INSTEAD ){
94985 sqlite3ErrorMsg(pParse, "cannot create %s trigger on view: %S",
94986 (tr_tm == TK_BEFORE)?"BEFORE":"AFTER", pTableName, 0);
94987 goto trigger_cleanup;
94989 if( !pTab->pSelect && tr_tm==TK_INSTEAD ){
94990 sqlite3ErrorMsg(pParse, "cannot create INSTEAD OF"
94991 " trigger on table: %S", pTableName, 0);
94992 goto trigger_cleanup;
94994 iTabDb = sqlite3SchemaToIndex(db, pTab->pSchema);
94996 #ifndef SQLITE_OMIT_AUTHORIZATION
94998 int code = SQLITE_CREATE_TRIGGER;
94999 const char *zDb = db->aDb[iTabDb].zName;
95000 const char *zDbTrig = isTemp ? db->aDb[1].zName : zDb;
95001 if( iTabDb==1 || isTemp ) code = SQLITE_CREATE_TEMP_TRIGGER;
95002 if( sqlite3AuthCheck(pParse, code, zName, pTab->zName, zDbTrig) ){
95003 goto trigger_cleanup;
95005 if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(iTabDb),0,zDb)){
95006 goto trigger_cleanup;
95009 #endif
95011 /* INSTEAD OF triggers can only appear on views and BEFORE triggers
95012 ** cannot appear on views. So we might as well translate every
95013 ** INSTEAD OF trigger into a BEFORE trigger. It simplifies code
95014 ** elsewhere.
95016 if (tr_tm == TK_INSTEAD){
95017 tr_tm = TK_BEFORE;
95020 /* Build the Trigger object */
95021 pTrigger = (Trigger*)sqlite3DbMallocZero(db, sizeof(Trigger));
95022 if( pTrigger==0 ) goto trigger_cleanup;
95023 pTrigger->zName = zName;
95024 zName = 0;
95025 pTrigger->table = sqlite3DbStrDup(db, pTableName->a[0].zName);
95026 pTrigger->pSchema = db->aDb[iDb].pSchema;
95027 pTrigger->pTabSchema = pTab->pSchema;
95028 pTrigger->op = (u8)op;
95029 pTrigger->tr_tm = tr_tm==TK_BEFORE ? TRIGGER_BEFORE : TRIGGER_AFTER;
95030 pTrigger->pWhen = sqlite3ExprDup(db, pWhen, EXPRDUP_REDUCE);
95031 pTrigger->pColumns = sqlite3IdListDup(db, pColumns);
95032 assert( pParse->pNewTrigger==0 );
95033 pParse->pNewTrigger = pTrigger;
95035 trigger_cleanup:
95036 sqlite3DbFree(db, zName);
95037 sqlite3SrcListDelete(db, pTableName);
95038 sqlite3IdListDelete(db, pColumns);
95039 sqlite3ExprDelete(db, pWhen);
95040 if( !pParse->pNewTrigger ){
95041 sqlite3DeleteTrigger(db, pTrigger);
95042 }else{
95043 assert( pParse->pNewTrigger==pTrigger );
95048 ** This routine is called after all of the trigger actions have been parsed
95049 ** in order to complete the process of building the trigger.
95051 SQLITE_PRIVATE void sqlite3FinishTrigger(
95052 Parse *pParse, /* Parser context */
95053 TriggerStep *pStepList, /* The triggered program */
95054 Token *pAll /* Token that describes the complete CREATE TRIGGER */
95056 Trigger *pTrig = pParse->pNewTrigger; /* Trigger being finished */
95057 char *zName; /* Name of trigger */
95058 sqlite3 *db = pParse->db; /* The database */
95059 DbFixer sFix; /* Fixer object */
95060 int iDb; /* Database containing the trigger */
95061 Token nameToken; /* Trigger name for error reporting */
95063 pParse->pNewTrigger = 0;
95064 if( NEVER(pParse->nErr) || !pTrig ) goto triggerfinish_cleanup;
95065 zName = pTrig->zName;
95066 iDb = sqlite3SchemaToIndex(pParse->db, pTrig->pSchema);
95067 pTrig->step_list = pStepList;
95068 while( pStepList ){
95069 pStepList->pTrig = pTrig;
95070 pStepList = pStepList->pNext;
95072 nameToken.z = pTrig->zName;
95073 nameToken.n = sqlite3Strlen30(nameToken.z);
95074 if( sqlite3FixInit(&sFix, pParse, iDb, "trigger", &nameToken)
95075 && sqlite3FixTriggerStep(&sFix, pTrig->step_list) ){
95076 goto triggerfinish_cleanup;
95079 /* if we are not initializing,
95080 ** build the sqlite_master entry
95082 if( !db->init.busy ){
95083 Vdbe *v;
95084 char *z;
95086 /* Make an entry in the sqlite_master table */
95087 v = sqlite3GetVdbe(pParse);
95088 if( v==0 ) goto triggerfinish_cleanup;
95089 sqlite3BeginWriteOperation(pParse, 0, iDb);
95090 z = sqlite3DbStrNDup(db, (char*)pAll->z, pAll->n);
95091 sqlite3NestedParse(pParse,
95092 "INSERT INTO %Q.%s VALUES('trigger',%Q,%Q,0,'CREATE TRIGGER %q')",
95093 db->aDb[iDb].zName, SCHEMA_TABLE(iDb), zName,
95094 pTrig->table, z);
95095 sqlite3DbFree(db, z);
95096 sqlite3ChangeCookie(pParse, iDb);
95097 sqlite3VdbeAddOp4(v, OP_ParseSchema, iDb, 0, 0, sqlite3MPrintf(
95098 db, "type='trigger' AND name='%q'", zName), P4_DYNAMIC
95102 if( db->init.busy ){
95103 Trigger *pLink = pTrig;
95104 Hash *pHash = &db->aDb[iDb].pSchema->trigHash;
95105 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
95106 pTrig = sqlite3HashInsert(pHash, zName, sqlite3Strlen30(zName), pTrig);
95107 if( pTrig ){
95108 db->mallocFailed = 1;
95109 }else if( pLink->pSchema==pLink->pTabSchema ){
95110 Table *pTab;
95111 int n = sqlite3Strlen30(pLink->table);
95112 pTab = sqlite3HashFind(&pLink->pTabSchema->tblHash, pLink->table, n);
95113 assert( pTab!=0 );
95114 pLink->pNext = pTab->pTrigger;
95115 pTab->pTrigger = pLink;
95119 triggerfinish_cleanup:
95120 sqlite3DeleteTrigger(db, pTrig);
95121 assert( !pParse->pNewTrigger );
95122 sqlite3DeleteTriggerStep(db, pStepList);
95126 ** Turn a SELECT statement (that the pSelect parameter points to) into
95127 ** a trigger step. Return a pointer to a TriggerStep structure.
95129 ** The parser calls this routine when it finds a SELECT statement in
95130 ** body of a TRIGGER.
95132 SQLITE_PRIVATE TriggerStep *sqlite3TriggerSelectStep(sqlite3 *db, Select *pSelect){
95133 TriggerStep *pTriggerStep = sqlite3DbMallocZero(db, sizeof(TriggerStep));
95134 if( pTriggerStep==0 ) {
95135 sqlite3SelectDelete(db, pSelect);
95136 return 0;
95138 pTriggerStep->op = TK_SELECT;
95139 pTriggerStep->pSelect = pSelect;
95140 pTriggerStep->orconf = OE_Default;
95141 return pTriggerStep;
95145 ** Allocate space to hold a new trigger step. The allocated space
95146 ** holds both the TriggerStep object and the TriggerStep.target.z string.
95148 ** If an OOM error occurs, NULL is returned and db->mallocFailed is set.
95150 static TriggerStep *triggerStepAllocate(
95151 sqlite3 *db, /* Database connection */
95152 u8 op, /* Trigger opcode */
95153 Token *pName /* The target name */
95155 TriggerStep *pTriggerStep;
95157 pTriggerStep = sqlite3DbMallocZero(db, sizeof(TriggerStep) + pName->n);
95158 if( pTriggerStep ){
95159 char *z = (char*)&pTriggerStep[1];
95160 memcpy(z, pName->z, pName->n);
95161 pTriggerStep->target.z = z;
95162 pTriggerStep->target.n = pName->n;
95163 pTriggerStep->op = op;
95165 return pTriggerStep;
95169 ** Build a trigger step out of an INSERT statement. Return a pointer
95170 ** to the new trigger step.
95172 ** The parser calls this routine when it sees an INSERT inside the
95173 ** body of a trigger.
95175 SQLITE_PRIVATE TriggerStep *sqlite3TriggerInsertStep(
95176 sqlite3 *db, /* The database connection */
95177 Token *pTableName, /* Name of the table into which we insert */
95178 IdList *pColumn, /* List of columns in pTableName to insert into */
95179 ExprList *pEList, /* The VALUE clause: a list of values to be inserted */
95180 Select *pSelect, /* A SELECT statement that supplies values */
95181 u8 orconf /* The conflict algorithm (OE_Abort, OE_Replace, etc.) */
95183 TriggerStep *pTriggerStep;
95185 assert(pEList == 0 || pSelect == 0);
95186 assert(pEList != 0 || pSelect != 0 || db->mallocFailed);
95188 pTriggerStep = triggerStepAllocate(db, TK_INSERT, pTableName);
95189 if( pTriggerStep ){
95190 pTriggerStep->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
95191 pTriggerStep->pIdList = pColumn;
95192 pTriggerStep->pExprList = sqlite3ExprListDup(db, pEList, EXPRDUP_REDUCE);
95193 pTriggerStep->orconf = orconf;
95194 }else{
95195 sqlite3IdListDelete(db, pColumn);
95197 sqlite3ExprListDelete(db, pEList);
95198 sqlite3SelectDelete(db, pSelect);
95200 return pTriggerStep;
95204 ** Construct a trigger step that implements an UPDATE statement and return
95205 ** a pointer to that trigger step. The parser calls this routine when it
95206 ** sees an UPDATE statement inside the body of a CREATE TRIGGER.
95208 SQLITE_PRIVATE TriggerStep *sqlite3TriggerUpdateStep(
95209 sqlite3 *db, /* The database connection */
95210 Token *pTableName, /* Name of the table to be updated */
95211 ExprList *pEList, /* The SET clause: list of column and new values */
95212 Expr *pWhere, /* The WHERE clause */
95213 u8 orconf /* The conflict algorithm. (OE_Abort, OE_Ignore, etc) */
95215 TriggerStep *pTriggerStep;
95217 pTriggerStep = triggerStepAllocate(db, TK_UPDATE, pTableName);
95218 if( pTriggerStep ){
95219 pTriggerStep->pExprList = sqlite3ExprListDup(db, pEList, EXPRDUP_REDUCE);
95220 pTriggerStep->pWhere = sqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE);
95221 pTriggerStep->orconf = orconf;
95223 sqlite3ExprListDelete(db, pEList);
95224 sqlite3ExprDelete(db, pWhere);
95225 return pTriggerStep;
95229 ** Construct a trigger step that implements a DELETE statement and return
95230 ** a pointer to that trigger step. The parser calls this routine when it
95231 ** sees a DELETE statement inside the body of a CREATE TRIGGER.
95233 SQLITE_PRIVATE TriggerStep *sqlite3TriggerDeleteStep(
95234 sqlite3 *db, /* Database connection */
95235 Token *pTableName, /* The table from which rows are deleted */
95236 Expr *pWhere /* The WHERE clause */
95238 TriggerStep *pTriggerStep;
95240 pTriggerStep = triggerStepAllocate(db, TK_DELETE, pTableName);
95241 if( pTriggerStep ){
95242 pTriggerStep->pWhere = sqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE);
95243 pTriggerStep->orconf = OE_Default;
95245 sqlite3ExprDelete(db, pWhere);
95246 return pTriggerStep;
95250 ** Recursively delete a Trigger structure
95252 SQLITE_PRIVATE void sqlite3DeleteTrigger(sqlite3 *db, Trigger *pTrigger){
95253 if( pTrigger==0 ) return;
95254 sqlite3DeleteTriggerStep(db, pTrigger->step_list);
95255 sqlite3DbFree(db, pTrigger->zName);
95256 sqlite3DbFree(db, pTrigger->table);
95257 sqlite3ExprDelete(db, pTrigger->pWhen);
95258 sqlite3IdListDelete(db, pTrigger->pColumns);
95259 sqlite3DbFree(db, pTrigger);
95263 ** This function is called to drop a trigger from the database schema.
95265 ** This may be called directly from the parser and therefore identifies
95266 ** the trigger by name. The sqlite3DropTriggerPtr() routine does the
95267 ** same job as this routine except it takes a pointer to the trigger
95268 ** instead of the trigger name.
95270 SQLITE_PRIVATE void sqlite3DropTrigger(Parse *pParse, SrcList *pName, int noErr){
95271 Trigger *pTrigger = 0;
95272 int i;
95273 const char *zDb;
95274 const char *zName;
95275 int nName;
95276 sqlite3 *db = pParse->db;
95278 if( db->mallocFailed ) goto drop_trigger_cleanup;
95279 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
95280 goto drop_trigger_cleanup;
95283 assert( pName->nSrc==1 );
95284 zDb = pName->a[0].zDatabase;
95285 zName = pName->a[0].zName;
95286 nName = sqlite3Strlen30(zName);
95287 assert( zDb!=0 || sqlite3BtreeHoldsAllMutexes(db) );
95288 for(i=OMIT_TEMPDB; i<db->nDb; i++){
95289 int j = (i<2) ? i^1 : i; /* Search TEMP before MAIN */
95290 if( zDb && sqlite3StrICmp(db->aDb[j].zName, zDb) ) continue;
95291 assert( sqlite3SchemaMutexHeld(db, j, 0) );
95292 pTrigger = sqlite3HashFind(&(db->aDb[j].pSchema->trigHash), zName, nName);
95293 if( pTrigger ) break;
95295 if( !pTrigger ){
95296 if( !noErr ){
95297 sqlite3ErrorMsg(pParse, "no such trigger: %S", pName, 0);
95298 }else{
95299 sqlite3CodeVerifyNamedSchema(pParse, zDb);
95301 pParse->checkSchema = 1;
95302 goto drop_trigger_cleanup;
95304 sqlite3DropTriggerPtr(pParse, pTrigger);
95306 drop_trigger_cleanup:
95307 sqlite3SrcListDelete(db, pName);
95311 ** Return a pointer to the Table structure for the table that a trigger
95312 ** is set on.
95314 static Table *tableOfTrigger(Trigger *pTrigger){
95315 int n = sqlite3Strlen30(pTrigger->table);
95316 return sqlite3HashFind(&pTrigger->pTabSchema->tblHash, pTrigger->table, n);
95321 ** Drop a trigger given a pointer to that trigger.
95323 SQLITE_PRIVATE void sqlite3DropTriggerPtr(Parse *pParse, Trigger *pTrigger){
95324 Table *pTable;
95325 Vdbe *v;
95326 sqlite3 *db = pParse->db;
95327 int iDb;
95329 iDb = sqlite3SchemaToIndex(pParse->db, pTrigger->pSchema);
95330 assert( iDb>=0 && iDb<db->nDb );
95331 pTable = tableOfTrigger(pTrigger);
95332 assert( pTable );
95333 assert( pTable->pSchema==pTrigger->pSchema || iDb==1 );
95334 #ifndef SQLITE_OMIT_AUTHORIZATION
95336 int code = SQLITE_DROP_TRIGGER;
95337 const char *zDb = db->aDb[iDb].zName;
95338 const char *zTab = SCHEMA_TABLE(iDb);
95339 if( iDb==1 ) code = SQLITE_DROP_TEMP_TRIGGER;
95340 if( sqlite3AuthCheck(pParse, code, pTrigger->zName, pTable->zName, zDb) ||
95341 sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb) ){
95342 return;
95345 #endif
95347 /* Generate code to destroy the database record of the trigger.
95349 assert( pTable!=0 );
95350 if( (v = sqlite3GetVdbe(pParse))!=0 ){
95351 int base;
95352 static const VdbeOpList dropTrigger[] = {
95353 { OP_Rewind, 0, ADDR(9), 0},
95354 { OP_String8, 0, 1, 0}, /* 1 */
95355 { OP_Column, 0, 1, 2},
95356 { OP_Ne, 2, ADDR(8), 1},
95357 { OP_String8, 0, 1, 0}, /* 4: "trigger" */
95358 { OP_Column, 0, 0, 2},
95359 { OP_Ne, 2, ADDR(8), 1},
95360 { OP_Delete, 0, 0, 0},
95361 { OP_Next, 0, ADDR(1), 0}, /* 8 */
95364 sqlite3BeginWriteOperation(pParse, 0, iDb);
95365 sqlite3OpenMasterTable(pParse, iDb);
95366 base = sqlite3VdbeAddOpList(v, ArraySize(dropTrigger), dropTrigger);
95367 sqlite3VdbeChangeP4(v, base+1, pTrigger->zName, P4_TRANSIENT);
95368 sqlite3VdbeChangeP4(v, base+4, "trigger", P4_STATIC);
95369 sqlite3ChangeCookie(pParse, iDb);
95370 sqlite3VdbeAddOp2(v, OP_Close, 0, 0);
95371 sqlite3VdbeAddOp4(v, OP_DropTrigger, iDb, 0, 0, pTrigger->zName, 0);
95372 if( pParse->nMem<3 ){
95373 pParse->nMem = 3;
95379 ** Remove a trigger from the hash tables of the sqlite* pointer.
95381 SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTrigger(sqlite3 *db, int iDb, const char *zName){
95382 Trigger *pTrigger;
95383 Hash *pHash;
95385 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
95386 pHash = &(db->aDb[iDb].pSchema->trigHash);
95387 pTrigger = sqlite3HashInsert(pHash, zName, sqlite3Strlen30(zName), 0);
95388 if( ALWAYS(pTrigger) ){
95389 if( pTrigger->pSchema==pTrigger->pTabSchema ){
95390 Table *pTab = tableOfTrigger(pTrigger);
95391 Trigger **pp;
95392 for(pp=&pTab->pTrigger; *pp!=pTrigger; pp=&((*pp)->pNext));
95393 *pp = (*pp)->pNext;
95395 sqlite3DeleteTrigger(db, pTrigger);
95396 db->flags |= SQLITE_InternChanges;
95401 ** pEList is the SET clause of an UPDATE statement. Each entry
95402 ** in pEList is of the format <id>=<expr>. If any of the entries
95403 ** in pEList have an <id> which matches an identifier in pIdList,
95404 ** then return TRUE. If pIdList==NULL, then it is considered a
95405 ** wildcard that matches anything. Likewise if pEList==NULL then
95406 ** it matches anything so always return true. Return false only
95407 ** if there is no match.
95409 static int checkColumnOverlap(IdList *pIdList, ExprList *pEList){
95410 int e;
95411 if( pIdList==0 || NEVER(pEList==0) ) return 1;
95412 for(e=0; e<pEList->nExpr; e++){
95413 if( sqlite3IdListIndex(pIdList, pEList->a[e].zName)>=0 ) return 1;
95415 return 0;
95419 ** Return a list of all triggers on table pTab if there exists at least
95420 ** one trigger that must be fired when an operation of type 'op' is
95421 ** performed on the table, and, if that operation is an UPDATE, if at
95422 ** least one of the columns in pChanges is being modified.
95424 SQLITE_PRIVATE Trigger *sqlite3TriggersExist(
95425 Parse *pParse, /* Parse context */
95426 Table *pTab, /* The table the contains the triggers */
95427 int op, /* one of TK_DELETE, TK_INSERT, TK_UPDATE */
95428 ExprList *pChanges, /* Columns that change in an UPDATE statement */
95429 int *pMask /* OUT: Mask of TRIGGER_BEFORE|TRIGGER_AFTER */
95431 int mask = 0;
95432 Trigger *pList = 0;
95433 Trigger *p;
95435 if( (pParse->db->flags & SQLITE_EnableTrigger)!=0 ){
95436 pList = sqlite3TriggerList(pParse, pTab);
95438 assert( pList==0 || IsVirtual(pTab)==0 );
95439 for(p=pList; p; p=p->pNext){
95440 if( p->op==op && checkColumnOverlap(p->pColumns, pChanges) ){
95441 mask |= p->tr_tm;
95444 if( pMask ){
95445 *pMask = mask;
95447 return (mask ? pList : 0);
95451 ** Convert the pStep->target token into a SrcList and return a pointer
95452 ** to that SrcList.
95454 ** This routine adds a specific database name, if needed, to the target when
95455 ** forming the SrcList. This prevents a trigger in one database from
95456 ** referring to a target in another database. An exception is when the
95457 ** trigger is in TEMP in which case it can refer to any other database it
95458 ** wants.
95460 static SrcList *targetSrcList(
95461 Parse *pParse, /* The parsing context */
95462 TriggerStep *pStep /* The trigger containing the target token */
95464 int iDb; /* Index of the database to use */
95465 SrcList *pSrc; /* SrcList to be returned */
95467 pSrc = sqlite3SrcListAppend(pParse->db, 0, &pStep->target, 0);
95468 if( pSrc ){
95469 assert( pSrc->nSrc>0 );
95470 assert( pSrc->a!=0 );
95471 iDb = sqlite3SchemaToIndex(pParse->db, pStep->pTrig->pSchema);
95472 if( iDb==0 || iDb>=2 ){
95473 sqlite3 *db = pParse->db;
95474 assert( iDb<pParse->db->nDb );
95475 pSrc->a[pSrc->nSrc-1].zDatabase = sqlite3DbStrDup(db, db->aDb[iDb].zName);
95478 return pSrc;
95482 ** Generate VDBE code for the statements inside the body of a single
95483 ** trigger.
95485 static int codeTriggerProgram(
95486 Parse *pParse, /* The parser context */
95487 TriggerStep *pStepList, /* List of statements inside the trigger body */
95488 int orconf /* Conflict algorithm. (OE_Abort, etc) */
95490 TriggerStep *pStep;
95491 Vdbe *v = pParse->pVdbe;
95492 sqlite3 *db = pParse->db;
95494 assert( pParse->pTriggerTab && pParse->pToplevel );
95495 assert( pStepList );
95496 assert( v!=0 );
95497 for(pStep=pStepList; pStep; pStep=pStep->pNext){
95498 /* Figure out the ON CONFLICT policy that will be used for this step
95499 ** of the trigger program. If the statement that caused this trigger
95500 ** to fire had an explicit ON CONFLICT, then use it. Otherwise, use
95501 ** the ON CONFLICT policy that was specified as part of the trigger
95502 ** step statement. Example:
95504 ** CREATE TRIGGER AFTER INSERT ON t1 BEGIN;
95505 ** INSERT OR REPLACE INTO t2 VALUES(new.a, new.b);
95506 ** END;
95508 ** INSERT INTO t1 ... ; -- insert into t2 uses REPLACE policy
95509 ** INSERT OR IGNORE INTO t1 ... ; -- insert into t2 uses IGNORE policy
95511 pParse->eOrconf = (orconf==OE_Default)?pStep->orconf:(u8)orconf;
95513 switch( pStep->op ){
95514 case TK_UPDATE: {
95515 sqlite3Update(pParse,
95516 targetSrcList(pParse, pStep),
95517 sqlite3ExprListDup(db, pStep->pExprList, 0),
95518 sqlite3ExprDup(db, pStep->pWhere, 0),
95519 pParse->eOrconf
95521 break;
95523 case TK_INSERT: {
95524 sqlite3Insert(pParse,
95525 targetSrcList(pParse, pStep),
95526 sqlite3ExprListDup(db, pStep->pExprList, 0),
95527 sqlite3SelectDup(db, pStep->pSelect, 0),
95528 sqlite3IdListDup(db, pStep->pIdList),
95529 pParse->eOrconf
95531 break;
95533 case TK_DELETE: {
95534 sqlite3DeleteFrom(pParse,
95535 targetSrcList(pParse, pStep),
95536 sqlite3ExprDup(db, pStep->pWhere, 0)
95538 break;
95540 default: assert( pStep->op==TK_SELECT ); {
95541 SelectDest sDest;
95542 Select *pSelect = sqlite3SelectDup(db, pStep->pSelect, 0);
95543 sqlite3SelectDestInit(&sDest, SRT_Discard, 0);
95544 sqlite3Select(pParse, pSelect, &sDest);
95545 sqlite3SelectDelete(db, pSelect);
95546 break;
95549 if( pStep->op!=TK_SELECT ){
95550 sqlite3VdbeAddOp0(v, OP_ResetCount);
95554 return 0;
95557 #ifdef SQLITE_DEBUG
95559 ** This function is used to add VdbeComment() annotations to a VDBE
95560 ** program. It is not used in production code, only for debugging.
95562 static const char *onErrorText(int onError){
95563 switch( onError ){
95564 case OE_Abort: return "abort";
95565 case OE_Rollback: return "rollback";
95566 case OE_Fail: return "fail";
95567 case OE_Replace: return "replace";
95568 case OE_Ignore: return "ignore";
95569 case OE_Default: return "default";
95571 return "n/a";
95573 #endif
95576 ** Parse context structure pFrom has just been used to create a sub-vdbe
95577 ** (trigger program). If an error has occurred, transfer error information
95578 ** from pFrom to pTo.
95580 static void transferParseError(Parse *pTo, Parse *pFrom){
95581 assert( pFrom->zErrMsg==0 || pFrom->nErr );
95582 assert( pTo->zErrMsg==0 || pTo->nErr );
95583 if( pTo->nErr==0 ){
95584 pTo->zErrMsg = pFrom->zErrMsg;
95585 pTo->nErr = pFrom->nErr;
95586 }else{
95587 sqlite3DbFree(pFrom->db, pFrom->zErrMsg);
95592 ** Create and populate a new TriggerPrg object with a sub-program
95593 ** implementing trigger pTrigger with ON CONFLICT policy orconf.
95595 static TriggerPrg *codeRowTrigger(
95596 Parse *pParse, /* Current parse context */
95597 Trigger *pTrigger, /* Trigger to code */
95598 Table *pTab, /* The table pTrigger is attached to */
95599 int orconf /* ON CONFLICT policy to code trigger program with */
95601 Parse *pTop = sqlite3ParseToplevel(pParse);
95602 sqlite3 *db = pParse->db; /* Database handle */
95603 TriggerPrg *pPrg; /* Value to return */
95604 Expr *pWhen = 0; /* Duplicate of trigger WHEN expression */
95605 Vdbe *v; /* Temporary VM */
95606 NameContext sNC; /* Name context for sub-vdbe */
95607 SubProgram *pProgram = 0; /* Sub-vdbe for trigger program */
95608 Parse *pSubParse; /* Parse context for sub-vdbe */
95609 int iEndTrigger = 0; /* Label to jump to if WHEN is false */
95611 assert( pTrigger->zName==0 || pTab==tableOfTrigger(pTrigger) );
95612 assert( pTop->pVdbe );
95614 /* Allocate the TriggerPrg and SubProgram objects. To ensure that they
95615 ** are freed if an error occurs, link them into the Parse.pTriggerPrg
95616 ** list of the top-level Parse object sooner rather than later. */
95617 pPrg = sqlite3DbMallocZero(db, sizeof(TriggerPrg));
95618 if( !pPrg ) return 0;
95619 pPrg->pNext = pTop->pTriggerPrg;
95620 pTop->pTriggerPrg = pPrg;
95621 pPrg->pProgram = pProgram = sqlite3DbMallocZero(db, sizeof(SubProgram));
95622 if( !pProgram ) return 0;
95623 sqlite3VdbeLinkSubProgram(pTop->pVdbe, pProgram);
95624 pPrg->pTrigger = pTrigger;
95625 pPrg->orconf = orconf;
95626 pPrg->aColmask[0] = 0xffffffff;
95627 pPrg->aColmask[1] = 0xffffffff;
95629 /* Allocate and populate a new Parse context to use for coding the
95630 ** trigger sub-program. */
95631 pSubParse = sqlite3StackAllocZero(db, sizeof(Parse));
95632 if( !pSubParse ) return 0;
95633 memset(&sNC, 0, sizeof(sNC));
95634 sNC.pParse = pSubParse;
95635 pSubParse->db = db;
95636 pSubParse->pTriggerTab = pTab;
95637 pSubParse->pToplevel = pTop;
95638 pSubParse->zAuthContext = pTrigger->zName;
95639 pSubParse->eTriggerOp = pTrigger->op;
95640 pSubParse->nQueryLoop = pParse->nQueryLoop;
95642 v = sqlite3GetVdbe(pSubParse);
95643 if( v ){
95644 VdbeComment((v, "Start: %s.%s (%s %s%s%s ON %s)",
95645 pTrigger->zName, onErrorText(orconf),
95646 (pTrigger->tr_tm==TRIGGER_BEFORE ? "BEFORE" : "AFTER"),
95647 (pTrigger->op==TK_UPDATE ? "UPDATE" : ""),
95648 (pTrigger->op==TK_INSERT ? "INSERT" : ""),
95649 (pTrigger->op==TK_DELETE ? "DELETE" : ""),
95650 pTab->zName
95652 #ifndef SQLITE_OMIT_TRACE
95653 sqlite3VdbeChangeP4(v, -1,
95654 sqlite3MPrintf(db, "-- TRIGGER %s", pTrigger->zName), P4_DYNAMIC
95656 #endif
95658 /* If one was specified, code the WHEN clause. If it evaluates to false
95659 ** (or NULL) the sub-vdbe is immediately halted by jumping to the
95660 ** OP_Halt inserted at the end of the program. */
95661 if( pTrigger->pWhen ){
95662 pWhen = sqlite3ExprDup(db, pTrigger->pWhen, 0);
95663 if( SQLITE_OK==sqlite3ResolveExprNames(&sNC, pWhen)
95664 && db->mallocFailed==0
95666 iEndTrigger = sqlite3VdbeMakeLabel(v);
95667 sqlite3ExprIfFalse(pSubParse, pWhen, iEndTrigger, SQLITE_JUMPIFNULL);
95669 sqlite3ExprDelete(db, pWhen);
95672 /* Code the trigger program into the sub-vdbe. */
95673 codeTriggerProgram(pSubParse, pTrigger->step_list, orconf);
95675 /* Insert an OP_Halt at the end of the sub-program. */
95676 if( iEndTrigger ){
95677 sqlite3VdbeResolveLabel(v, iEndTrigger);
95679 sqlite3VdbeAddOp0(v, OP_Halt);
95680 VdbeComment((v, "End: %s.%s", pTrigger->zName, onErrorText(orconf)));
95682 transferParseError(pParse, pSubParse);
95683 if( db->mallocFailed==0 ){
95684 pProgram->aOp = sqlite3VdbeTakeOpArray(v, &pProgram->nOp, &pTop->nMaxArg);
95686 pProgram->nMem = pSubParse->nMem;
95687 pProgram->nCsr = pSubParse->nTab;
95688 pProgram->token = (void *)pTrigger;
95689 pPrg->aColmask[0] = pSubParse->oldmask;
95690 pPrg->aColmask[1] = pSubParse->newmask;
95691 sqlite3VdbeDelete(v);
95694 assert( !pSubParse->pAinc && !pSubParse->pZombieTab );
95695 assert( !pSubParse->pTriggerPrg && !pSubParse->nMaxArg );
95696 sqlite3StackFree(db, pSubParse);
95698 return pPrg;
95702 ** Return a pointer to a TriggerPrg object containing the sub-program for
95703 ** trigger pTrigger with default ON CONFLICT algorithm orconf. If no such
95704 ** TriggerPrg object exists, a new object is allocated and populated before
95705 ** being returned.
95707 static TriggerPrg *getRowTrigger(
95708 Parse *pParse, /* Current parse context */
95709 Trigger *pTrigger, /* Trigger to code */
95710 Table *pTab, /* The table trigger pTrigger is attached to */
95711 int orconf /* ON CONFLICT algorithm. */
95713 Parse *pRoot = sqlite3ParseToplevel(pParse);
95714 TriggerPrg *pPrg;
95716 assert( pTrigger->zName==0 || pTab==tableOfTrigger(pTrigger) );
95718 /* It may be that this trigger has already been coded (or is in the
95719 ** process of being coded). If this is the case, then an entry with
95720 ** a matching TriggerPrg.pTrigger field will be present somewhere
95721 ** in the Parse.pTriggerPrg list. Search for such an entry. */
95722 for(pPrg=pRoot->pTriggerPrg;
95723 pPrg && (pPrg->pTrigger!=pTrigger || pPrg->orconf!=orconf);
95724 pPrg=pPrg->pNext
95727 /* If an existing TriggerPrg could not be located, create a new one. */
95728 if( !pPrg ){
95729 pPrg = codeRowTrigger(pParse, pTrigger, pTab, orconf);
95732 return pPrg;
95736 ** Generate code for the trigger program associated with trigger p on
95737 ** table pTab. The reg, orconf and ignoreJump parameters passed to this
95738 ** function are the same as those described in the header function for
95739 ** sqlite3CodeRowTrigger()
95741 SQLITE_PRIVATE void sqlite3CodeRowTriggerDirect(
95742 Parse *pParse, /* Parse context */
95743 Trigger *p, /* Trigger to code */
95744 Table *pTab, /* The table to code triggers from */
95745 int reg, /* Reg array containing OLD.* and NEW.* values */
95746 int orconf, /* ON CONFLICT policy */
95747 int ignoreJump /* Instruction to jump to for RAISE(IGNORE) */
95749 Vdbe *v = sqlite3GetVdbe(pParse); /* Main VM */
95750 TriggerPrg *pPrg;
95751 pPrg = getRowTrigger(pParse, p, pTab, orconf);
95752 assert( pPrg || pParse->nErr || pParse->db->mallocFailed );
95754 /* Code the OP_Program opcode in the parent VDBE. P4 of the OP_Program
95755 ** is a pointer to the sub-vdbe containing the trigger program. */
95756 if( pPrg ){
95757 int bRecursive = (p->zName && 0==(pParse->db->flags&SQLITE_RecTriggers));
95759 sqlite3VdbeAddOp3(v, OP_Program, reg, ignoreJump, ++pParse->nMem);
95760 sqlite3VdbeChangeP4(v, -1, (const char *)pPrg->pProgram, P4_SUBPROGRAM);
95761 VdbeComment(
95762 (v, "Call: %s.%s", (p->zName?p->zName:"fkey"), onErrorText(orconf)));
95764 /* Set the P5 operand of the OP_Program instruction to non-zero if
95765 ** recursive invocation of this trigger program is disallowed. Recursive
95766 ** invocation is disallowed if (a) the sub-program is really a trigger,
95767 ** not a foreign key action, and (b) the flag to enable recursive triggers
95768 ** is clear. */
95769 sqlite3VdbeChangeP5(v, (u8)bRecursive);
95774 ** This is called to code the required FOR EACH ROW triggers for an operation
95775 ** on table pTab. The operation to code triggers for (INSERT, UPDATE or DELETE)
95776 ** is given by the op paramater. The tr_tm parameter determines whether the
95777 ** BEFORE or AFTER triggers are coded. If the operation is an UPDATE, then
95778 ** parameter pChanges is passed the list of columns being modified.
95780 ** If there are no triggers that fire at the specified time for the specified
95781 ** operation on pTab, this function is a no-op.
95783 ** The reg argument is the address of the first in an array of registers
95784 ** that contain the values substituted for the new.* and old.* references
95785 ** in the trigger program. If N is the number of columns in table pTab
95786 ** (a copy of pTab->nCol), then registers are populated as follows:
95788 ** Register Contains
95789 ** ------------------------------------------------------
95790 ** reg+0 OLD.rowid
95791 ** reg+1 OLD.* value of left-most column of pTab
95792 ** ... ...
95793 ** reg+N OLD.* value of right-most column of pTab
95794 ** reg+N+1 NEW.rowid
95795 ** reg+N+2 OLD.* value of left-most column of pTab
95796 ** ... ...
95797 ** reg+N+N+1 NEW.* value of right-most column of pTab
95799 ** For ON DELETE triggers, the registers containing the NEW.* values will
95800 ** never be accessed by the trigger program, so they are not allocated or
95801 ** populated by the caller (there is no data to populate them with anyway).
95802 ** Similarly, for ON INSERT triggers the values stored in the OLD.* registers
95803 ** are never accessed, and so are not allocated by the caller. So, for an
95804 ** ON INSERT trigger, the value passed to this function as parameter reg
95805 ** is not a readable register, although registers (reg+N) through
95806 ** (reg+N+N+1) are.
95808 ** Parameter orconf is the default conflict resolution algorithm for the
95809 ** trigger program to use (REPLACE, IGNORE etc.). Parameter ignoreJump
95810 ** is the instruction that control should jump to if a trigger program
95811 ** raises an IGNORE exception.
95813 SQLITE_PRIVATE void sqlite3CodeRowTrigger(
95814 Parse *pParse, /* Parse context */
95815 Trigger *pTrigger, /* List of triggers on table pTab */
95816 int op, /* One of TK_UPDATE, TK_INSERT, TK_DELETE */
95817 ExprList *pChanges, /* Changes list for any UPDATE OF triggers */
95818 int tr_tm, /* One of TRIGGER_BEFORE, TRIGGER_AFTER */
95819 Table *pTab, /* The table to code triggers from */
95820 int reg, /* The first in an array of registers (see above) */
95821 int orconf, /* ON CONFLICT policy */
95822 int ignoreJump /* Instruction to jump to for RAISE(IGNORE) */
95824 Trigger *p; /* Used to iterate through pTrigger list */
95826 assert( op==TK_UPDATE || op==TK_INSERT || op==TK_DELETE );
95827 assert( tr_tm==TRIGGER_BEFORE || tr_tm==TRIGGER_AFTER );
95828 assert( (op==TK_UPDATE)==(pChanges!=0) );
95830 for(p=pTrigger; p; p=p->pNext){
95832 /* Sanity checking: The schema for the trigger and for the table are
95833 ** always defined. The trigger must be in the same schema as the table
95834 ** or else it must be a TEMP trigger. */
95835 assert( p->pSchema!=0 );
95836 assert( p->pTabSchema!=0 );
95837 assert( p->pSchema==p->pTabSchema
95838 || p->pSchema==pParse->db->aDb[1].pSchema );
95840 /* Determine whether we should code this trigger */
95841 if( p->op==op
95842 && p->tr_tm==tr_tm
95843 && checkColumnOverlap(p->pColumns, pChanges)
95845 sqlite3CodeRowTriggerDirect(pParse, p, pTab, reg, orconf, ignoreJump);
95851 ** Triggers may access values stored in the old.* or new.* pseudo-table.
95852 ** This function returns a 32-bit bitmask indicating which columns of the
95853 ** old.* or new.* tables actually are used by triggers. This information
95854 ** may be used by the caller, for example, to avoid having to load the entire
95855 ** old.* record into memory when executing an UPDATE or DELETE command.
95857 ** Bit 0 of the returned mask is set if the left-most column of the
95858 ** table may be accessed using an [old|new].<col> reference. Bit 1 is set if
95859 ** the second leftmost column value is required, and so on. If there
95860 ** are more than 32 columns in the table, and at least one of the columns
95861 ** with an index greater than 32 may be accessed, 0xffffffff is returned.
95863 ** It is not possible to determine if the old.rowid or new.rowid column is
95864 ** accessed by triggers. The caller must always assume that it is.
95866 ** Parameter isNew must be either 1 or 0. If it is 0, then the mask returned
95867 ** applies to the old.* table. If 1, the new.* table.
95869 ** Parameter tr_tm must be a mask with one or both of the TRIGGER_BEFORE
95870 ** and TRIGGER_AFTER bits set. Values accessed by BEFORE triggers are only
95871 ** included in the returned mask if the TRIGGER_BEFORE bit is set in the
95872 ** tr_tm parameter. Similarly, values accessed by AFTER triggers are only
95873 ** included in the returned mask if the TRIGGER_AFTER bit is set in tr_tm.
95875 SQLITE_PRIVATE u32 sqlite3TriggerColmask(
95876 Parse *pParse, /* Parse context */
95877 Trigger *pTrigger, /* List of triggers on table pTab */
95878 ExprList *pChanges, /* Changes list for any UPDATE OF triggers */
95879 int isNew, /* 1 for new.* ref mask, 0 for old.* ref mask */
95880 int tr_tm, /* Mask of TRIGGER_BEFORE|TRIGGER_AFTER */
95881 Table *pTab, /* The table to code triggers from */
95882 int orconf /* Default ON CONFLICT policy for trigger steps */
95884 const int op = pChanges ? TK_UPDATE : TK_DELETE;
95885 u32 mask = 0;
95886 Trigger *p;
95888 assert( isNew==1 || isNew==0 );
95889 for(p=pTrigger; p; p=p->pNext){
95890 if( p->op==op && (tr_tm&p->tr_tm)
95891 && checkColumnOverlap(p->pColumns,pChanges)
95893 TriggerPrg *pPrg;
95894 pPrg = getRowTrigger(pParse, p, pTab, orconf);
95895 if( pPrg ){
95896 mask |= pPrg->aColmask[isNew];
95901 return mask;
95904 #endif /* !defined(SQLITE_OMIT_TRIGGER) */
95906 /************** End of trigger.c *********************************************/
95907 /************** Begin file update.c ******************************************/
95909 ** 2001 September 15
95911 ** The author disclaims copyright to this source code. In place of
95912 ** a legal notice, here is a blessing:
95914 ** May you do good and not evil.
95915 ** May you find forgiveness for yourself and forgive others.
95916 ** May you share freely, never taking more than you give.
95918 *************************************************************************
95919 ** This file contains C code routines that are called by the parser
95920 ** to handle UPDATE statements.
95923 #ifndef SQLITE_OMIT_VIRTUALTABLE
95924 /* Forward declaration */
95925 static void updateVirtualTable(
95926 Parse *pParse, /* The parsing context */
95927 SrcList *pSrc, /* The virtual table to be modified */
95928 Table *pTab, /* The virtual table */
95929 ExprList *pChanges, /* The columns to change in the UPDATE statement */
95930 Expr *pRowidExpr, /* Expression used to recompute the rowid */
95931 int *aXRef, /* Mapping from columns of pTab to entries in pChanges */
95932 Expr *pWhere /* WHERE clause of the UPDATE statement */
95934 #endif /* SQLITE_OMIT_VIRTUALTABLE */
95937 ** The most recently coded instruction was an OP_Column to retrieve the
95938 ** i-th column of table pTab. This routine sets the P4 parameter of the
95939 ** OP_Column to the default value, if any.
95941 ** The default value of a column is specified by a DEFAULT clause in the
95942 ** column definition. This was either supplied by the user when the table
95943 ** was created, or added later to the table definition by an ALTER TABLE
95944 ** command. If the latter, then the row-records in the table btree on disk
95945 ** may not contain a value for the column and the default value, taken
95946 ** from the P4 parameter of the OP_Column instruction, is returned instead.
95947 ** If the former, then all row-records are guaranteed to include a value
95948 ** for the column and the P4 value is not required.
95950 ** Column definitions created by an ALTER TABLE command may only have
95951 ** literal default values specified: a number, null or a string. (If a more
95952 ** complicated default expression value was provided, it is evaluated
95953 ** when the ALTER TABLE is executed and one of the literal values written
95954 ** into the sqlite_master table.)
95956 ** Therefore, the P4 parameter is only required if the default value for
95957 ** the column is a literal number, string or null. The sqlite3ValueFromExpr()
95958 ** function is capable of transforming these types of expressions into
95959 ** sqlite3_value objects.
95961 ** If parameter iReg is not negative, code an OP_RealAffinity instruction
95962 ** on register iReg. This is used when an equivalent integer value is
95963 ** stored in place of an 8-byte floating point value in order to save
95964 ** space.
95966 SQLITE_PRIVATE void sqlite3ColumnDefault(Vdbe *v, Table *pTab, int i, int iReg){
95967 assert( pTab!=0 );
95968 if( !pTab->pSelect ){
95969 sqlite3_value *pValue;
95970 u8 enc = ENC(sqlite3VdbeDb(v));
95971 Column *pCol = &pTab->aCol[i];
95972 VdbeComment((v, "%s.%s", pTab->zName, pCol->zName));
95973 assert( i<pTab->nCol );
95974 sqlite3ValueFromExpr(sqlite3VdbeDb(v), pCol->pDflt, enc,
95975 pCol->affinity, &pValue);
95976 if( pValue ){
95977 sqlite3VdbeChangeP4(v, -1, (const char *)pValue, P4_MEM);
95979 #ifndef SQLITE_OMIT_FLOATING_POINT
95980 if( iReg>=0 && pTab->aCol[i].affinity==SQLITE_AFF_REAL ){
95981 sqlite3VdbeAddOp1(v, OP_RealAffinity, iReg);
95983 #endif
95988 ** Process an UPDATE statement.
95990 ** UPDATE OR IGNORE table_wxyz SET a=b, c=d WHERE e<5 AND f NOT NULL;
95991 ** \_______/ \________/ \______/ \________________/
95992 * onError pTabList pChanges pWhere
95994 SQLITE_PRIVATE void sqlite3Update(
95995 Parse *pParse, /* The parser context */
95996 SrcList *pTabList, /* The table in which we should change things */
95997 ExprList *pChanges, /* Things to be changed */
95998 Expr *pWhere, /* The WHERE clause. May be null */
95999 int onError /* How to handle constraint errors */
96001 int i, j; /* Loop counters */
96002 Table *pTab; /* The table to be updated */
96003 int addr = 0; /* VDBE instruction address of the start of the loop */
96004 WhereInfo *pWInfo; /* Information about the WHERE clause */
96005 Vdbe *v; /* The virtual database engine */
96006 Index *pIdx; /* For looping over indices */
96007 int nIdx; /* Number of indices that need updating */
96008 int iCur; /* VDBE Cursor number of pTab */
96009 sqlite3 *db; /* The database structure */
96010 int *aRegIdx = 0; /* One register assigned to each index to be updated */
96011 int *aXRef = 0; /* aXRef[i] is the index in pChanges->a[] of the
96012 ** an expression for the i-th column of the table.
96013 ** aXRef[i]==-1 if the i-th column is not changed. */
96014 int chngRowid; /* True if the record number is being changed */
96015 Expr *pRowidExpr = 0; /* Expression defining the new record number */
96016 int openAll = 0; /* True if all indices need to be opened */
96017 AuthContext sContext; /* The authorization context */
96018 NameContext sNC; /* The name-context to resolve expressions in */
96019 int iDb; /* Database containing the table being updated */
96020 int okOnePass; /* True for one-pass algorithm without the FIFO */
96021 int hasFK; /* True if foreign key processing is required */
96023 #ifndef SQLITE_OMIT_TRIGGER
96024 int isView; /* True when updating a view (INSTEAD OF trigger) */
96025 Trigger *pTrigger; /* List of triggers on pTab, if required */
96026 int tmask; /* Mask of TRIGGER_BEFORE|TRIGGER_AFTER */
96027 #endif
96028 int newmask; /* Mask of NEW.* columns accessed by BEFORE triggers */
96030 /* Register Allocations */
96031 int regRowCount = 0; /* A count of rows changed */
96032 int regOldRowid; /* The old rowid */
96033 int regNewRowid; /* The new rowid */
96034 int regNew;
96035 int regOld = 0;
96036 int regRowSet = 0; /* Rowset of rows to be updated */
96038 memset(&sContext, 0, sizeof(sContext));
96039 db = pParse->db;
96040 if( pParse->nErr || db->mallocFailed ){
96041 goto update_cleanup;
96043 assert( pTabList->nSrc==1 );
96045 /* Locate the table which we want to update.
96047 pTab = sqlite3SrcListLookup(pParse, pTabList);
96048 if( pTab==0 ) goto update_cleanup;
96049 iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
96051 /* Figure out if we have any triggers and if the table being
96052 ** updated is a view.
96054 #ifndef SQLITE_OMIT_TRIGGER
96055 pTrigger = sqlite3TriggersExist(pParse, pTab, TK_UPDATE, pChanges, &tmask);
96056 isView = pTab->pSelect!=0;
96057 assert( pTrigger || tmask==0 );
96058 #else
96059 # define pTrigger 0
96060 # define isView 0
96061 # define tmask 0
96062 #endif
96063 #ifdef SQLITE_OMIT_VIEW
96064 # undef isView
96065 # define isView 0
96066 #endif
96068 if( sqlite3ViewGetColumnNames(pParse, pTab) ){
96069 goto update_cleanup;
96071 if( sqlite3IsReadOnly(pParse, pTab, tmask) ){
96072 goto update_cleanup;
96074 aXRef = sqlite3DbMallocRaw(db, sizeof(int) * pTab->nCol );
96075 if( aXRef==0 ) goto update_cleanup;
96076 for(i=0; i<pTab->nCol; i++) aXRef[i] = -1;
96078 /* Allocate a cursors for the main database table and for all indices.
96079 ** The index cursors might not be used, but if they are used they
96080 ** need to occur right after the database cursor. So go ahead and
96081 ** allocate enough space, just in case.
96083 pTabList->a[0].iCursor = iCur = pParse->nTab++;
96084 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
96085 pParse->nTab++;
96088 /* Initialize the name-context */
96089 memset(&sNC, 0, sizeof(sNC));
96090 sNC.pParse = pParse;
96091 sNC.pSrcList = pTabList;
96093 /* Resolve the column names in all the expressions of the
96094 ** of the UPDATE statement. Also find the column index
96095 ** for each column to be updated in the pChanges array. For each
96096 ** column to be updated, make sure we have authorization to change
96097 ** that column.
96099 chngRowid = 0;
96100 for(i=0; i<pChanges->nExpr; i++){
96101 if( sqlite3ResolveExprNames(&sNC, pChanges->a[i].pExpr) ){
96102 goto update_cleanup;
96104 for(j=0; j<pTab->nCol; j++){
96105 if( sqlite3StrICmp(pTab->aCol[j].zName, pChanges->a[i].zName)==0 ){
96106 if( j==pTab->iPKey ){
96107 chngRowid = 1;
96108 pRowidExpr = pChanges->a[i].pExpr;
96110 aXRef[j] = i;
96111 break;
96114 if( j>=pTab->nCol ){
96115 if( sqlite3IsRowid(pChanges->a[i].zName) ){
96116 chngRowid = 1;
96117 pRowidExpr = pChanges->a[i].pExpr;
96118 }else{
96119 sqlite3ErrorMsg(pParse, "no such column: %s", pChanges->a[i].zName);
96120 pParse->checkSchema = 1;
96121 goto update_cleanup;
96124 #ifndef SQLITE_OMIT_AUTHORIZATION
96126 int rc;
96127 rc = sqlite3AuthCheck(pParse, SQLITE_UPDATE, pTab->zName,
96128 pTab->aCol[j].zName, db->aDb[iDb].zName);
96129 if( rc==SQLITE_DENY ){
96130 goto update_cleanup;
96131 }else if( rc==SQLITE_IGNORE ){
96132 aXRef[j] = -1;
96135 #endif
96138 hasFK = sqlite3FkRequired(pParse, pTab, aXRef, chngRowid);
96140 /* Allocate memory for the array aRegIdx[]. There is one entry in the
96141 ** array for each index associated with table being updated. Fill in
96142 ** the value with a register number for indices that are to be used
96143 ** and with zero for unused indices.
96145 for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){}
96146 if( nIdx>0 ){
96147 aRegIdx = sqlite3DbMallocRaw(db, sizeof(Index*) * nIdx );
96148 if( aRegIdx==0 ) goto update_cleanup;
96150 for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
96151 int reg;
96152 if( chngRowid ){
96153 reg = ++pParse->nMem;
96154 }else{
96155 reg = 0;
96156 for(i=0; i<pIdx->nColumn; i++){
96157 if( aXRef[pIdx->aiColumn[i]]>=0 ){
96158 reg = ++pParse->nMem;
96159 break;
96163 aRegIdx[j] = reg;
96166 /* Begin generating code. */
96167 v = sqlite3GetVdbe(pParse);
96168 if( v==0 ) goto update_cleanup;
96169 if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
96170 sqlite3BeginWriteOperation(pParse, 1, iDb);
96172 #ifndef SQLITE_OMIT_VIRTUALTABLE
96173 /* Virtual tables must be handled separately */
96174 if( IsVirtual(pTab) ){
96175 updateVirtualTable(pParse, pTabList, pTab, pChanges, pRowidExpr, aXRef,
96176 pWhere);
96177 pWhere = 0;
96178 pTabList = 0;
96179 goto update_cleanup;
96181 #endif
96183 /* Allocate required registers. */
96184 regOldRowid = regNewRowid = ++pParse->nMem;
96185 if( pTrigger || hasFK ){
96186 regOld = pParse->nMem + 1;
96187 pParse->nMem += pTab->nCol;
96189 if( chngRowid || pTrigger || hasFK ){
96190 regNewRowid = ++pParse->nMem;
96192 regNew = pParse->nMem + 1;
96193 pParse->nMem += pTab->nCol;
96195 /* Start the view context. */
96196 if( isView ){
96197 sqlite3AuthContextPush(pParse, &sContext, pTab->zName);
96200 /* If we are trying to update a view, realize that view into
96201 ** a ephemeral table.
96203 #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
96204 if( isView ){
96205 sqlite3MaterializeView(pParse, pTab, pWhere, iCur);
96207 #endif
96209 /* Resolve the column names in all the expressions in the
96210 ** WHERE clause.
96212 if( sqlite3ResolveExprNames(&sNC, pWhere) ){
96213 goto update_cleanup;
96216 /* Begin the database scan
96218 sqlite3VdbeAddOp2(v, OP_Null, 0, regOldRowid);
96219 pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere,0, WHERE_ONEPASS_DESIRED);
96220 if( pWInfo==0 ) goto update_cleanup;
96221 okOnePass = pWInfo->okOnePass;
96223 /* Remember the rowid of every item to be updated.
96225 sqlite3VdbeAddOp2(v, OP_Rowid, iCur, regOldRowid);
96226 if( !okOnePass ){
96227 regRowSet = ++pParse->nMem;
96228 sqlite3VdbeAddOp2(v, OP_RowSetAdd, regRowSet, regOldRowid);
96231 /* End the database scan loop.
96233 sqlite3WhereEnd(pWInfo);
96235 /* Initialize the count of updated rows
96237 if( (db->flags & SQLITE_CountRows) && !pParse->pTriggerTab ){
96238 regRowCount = ++pParse->nMem;
96239 sqlite3VdbeAddOp2(v, OP_Integer, 0, regRowCount);
96242 if( !isView ){
96244 ** Open every index that needs updating. Note that if any
96245 ** index could potentially invoke a REPLACE conflict resolution
96246 ** action, then we need to open all indices because we might need
96247 ** to be deleting some records.
96249 if( !okOnePass ) sqlite3OpenTable(pParse, iCur, iDb, pTab, OP_OpenWrite);
96250 if( onError==OE_Replace ){
96251 openAll = 1;
96252 }else{
96253 openAll = 0;
96254 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
96255 if( pIdx->onError==OE_Replace ){
96256 openAll = 1;
96257 break;
96261 for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
96262 if( openAll || aRegIdx[i]>0 ){
96263 KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIdx);
96264 sqlite3VdbeAddOp4(v, OP_OpenWrite, iCur+i+1, pIdx->tnum, iDb,
96265 (char*)pKey, P4_KEYINFO_HANDOFF);
96266 assert( pParse->nTab>iCur+i+1 );
96271 /* Top of the update loop */
96272 if( okOnePass ){
96273 int a1 = sqlite3VdbeAddOp1(v, OP_NotNull, regOldRowid);
96274 addr = sqlite3VdbeAddOp0(v, OP_Goto);
96275 sqlite3VdbeJumpHere(v, a1);
96276 }else{
96277 addr = sqlite3VdbeAddOp3(v, OP_RowSetRead, regRowSet, 0, regOldRowid);
96280 /* Make cursor iCur point to the record that is being updated. If
96281 ** this record does not exist for some reason (deleted by a trigger,
96282 ** for example, then jump to the next iteration of the RowSet loop. */
96283 sqlite3VdbeAddOp3(v, OP_NotExists, iCur, addr, regOldRowid);
96285 /* If the record number will change, set register regNewRowid to
96286 ** contain the new value. If the record number is not being modified,
96287 ** then regNewRowid is the same register as regOldRowid, which is
96288 ** already populated. */
96289 assert( chngRowid || pTrigger || hasFK || regOldRowid==regNewRowid );
96290 if( chngRowid ){
96291 sqlite3ExprCode(pParse, pRowidExpr, regNewRowid);
96292 sqlite3VdbeAddOp1(v, OP_MustBeInt, regNewRowid);
96295 /* If there are triggers on this table, populate an array of registers
96296 ** with the required old.* column data. */
96297 if( hasFK || pTrigger ){
96298 u32 oldmask = (hasFK ? sqlite3FkOldmask(pParse, pTab) : 0);
96299 oldmask |= sqlite3TriggerColmask(pParse,
96300 pTrigger, pChanges, 0, TRIGGER_BEFORE|TRIGGER_AFTER, pTab, onError
96302 for(i=0; i<pTab->nCol; i++){
96303 if( aXRef[i]<0 || oldmask==0xffffffff || (i<32 && (oldmask & (1<<i))) ){
96304 sqlite3ExprCodeGetColumnOfTable(v, pTab, iCur, i, regOld+i);
96305 }else{
96306 sqlite3VdbeAddOp2(v, OP_Null, 0, regOld+i);
96309 if( chngRowid==0 ){
96310 sqlite3VdbeAddOp2(v, OP_Copy, regOldRowid, regNewRowid);
96314 /* Populate the array of registers beginning at regNew with the new
96315 ** row data. This array is used to check constaints, create the new
96316 ** table and index records, and as the values for any new.* references
96317 ** made by triggers.
96319 ** If there are one or more BEFORE triggers, then do not populate the
96320 ** registers associated with columns that are (a) not modified by
96321 ** this UPDATE statement and (b) not accessed by new.* references. The
96322 ** values for registers not modified by the UPDATE must be reloaded from
96323 ** the database after the BEFORE triggers are fired anyway (as the trigger
96324 ** may have modified them). So not loading those that are not going to
96325 ** be used eliminates some redundant opcodes.
96327 newmask = sqlite3TriggerColmask(
96328 pParse, pTrigger, pChanges, 1, TRIGGER_BEFORE, pTab, onError
96330 for(i=0; i<pTab->nCol; i++){
96331 if( i==pTab->iPKey ){
96332 sqlite3VdbeAddOp2(v, OP_Null, 0, regNew+i);
96333 }else{
96334 j = aXRef[i];
96335 if( j>=0 ){
96336 sqlite3ExprCode(pParse, pChanges->a[j].pExpr, regNew+i);
96337 }else if( 0==(tmask&TRIGGER_BEFORE) || i>31 || (newmask&(1<<i)) ){
96338 /* This branch loads the value of a column that will not be changed
96339 ** into a register. This is done if there are no BEFORE triggers, or
96340 ** if there are one or more BEFORE triggers that use this value via
96341 ** a new.* reference in a trigger program.
96343 testcase( i==31 );
96344 testcase( i==32 );
96345 sqlite3VdbeAddOp3(v, OP_Column, iCur, i, regNew+i);
96346 sqlite3ColumnDefault(v, pTab, i, regNew+i);
96351 /* Fire any BEFORE UPDATE triggers. This happens before constraints are
96352 ** verified. One could argue that this is wrong.
96354 if( tmask&TRIGGER_BEFORE ){
96355 sqlite3VdbeAddOp2(v, OP_Affinity, regNew, pTab->nCol);
96356 sqlite3TableAffinityStr(v, pTab);
96357 sqlite3CodeRowTrigger(pParse, pTrigger, TK_UPDATE, pChanges,
96358 TRIGGER_BEFORE, pTab, regOldRowid, onError, addr);
96360 /* The row-trigger may have deleted the row being updated. In this
96361 ** case, jump to the next row. No updates or AFTER triggers are
96362 ** required. This behaviour - what happens when the row being updated
96363 ** is deleted or renamed by a BEFORE trigger - is left undefined in the
96364 ** documentation.
96366 sqlite3VdbeAddOp3(v, OP_NotExists, iCur, addr, regOldRowid);
96368 /* If it did not delete it, the row-trigger may still have modified
96369 ** some of the columns of the row being updated. Load the values for
96370 ** all columns not modified by the update statement into their
96371 ** registers in case this has happened.
96373 for(i=0; i<pTab->nCol; i++){
96374 if( aXRef[i]<0 && i!=pTab->iPKey ){
96375 sqlite3VdbeAddOp3(v, OP_Column, iCur, i, regNew+i);
96376 sqlite3ColumnDefault(v, pTab, i, regNew+i);
96381 if( !isView ){
96382 int j1; /* Address of jump instruction */
96384 /* Do constraint checks. */
96385 sqlite3GenerateConstraintChecks(pParse, pTab, iCur, regNewRowid,
96386 aRegIdx, (chngRowid?regOldRowid:0), 1, onError, addr, 0);
96388 /* Do FK constraint checks. */
96389 if( hasFK ){
96390 sqlite3FkCheck(pParse, pTab, regOldRowid, 0);
96393 /* Delete the index entries associated with the current record. */
96394 j1 = sqlite3VdbeAddOp3(v, OP_NotExists, iCur, 0, regOldRowid);
96395 sqlite3GenerateRowIndexDelete(pParse, pTab, iCur, aRegIdx);
96397 /* If changing the record number, delete the old record. */
96398 if( hasFK || chngRowid ){
96399 sqlite3VdbeAddOp2(v, OP_Delete, iCur, 0);
96401 sqlite3VdbeJumpHere(v, j1);
96403 if( hasFK ){
96404 sqlite3FkCheck(pParse, pTab, 0, regNewRowid);
96407 /* Insert the new index entries and the new record. */
96408 sqlite3CompleteInsertion(pParse, pTab, iCur, regNewRowid, aRegIdx, 1, 0, 0);
96410 /* Do any ON CASCADE, SET NULL or SET DEFAULT operations required to
96411 ** handle rows (possibly in other tables) that refer via a foreign key
96412 ** to the row just updated. */
96413 if( hasFK ){
96414 sqlite3FkActions(pParse, pTab, pChanges, regOldRowid);
96418 /* Increment the row counter
96420 if( (db->flags & SQLITE_CountRows) && !pParse->pTriggerTab){
96421 sqlite3VdbeAddOp2(v, OP_AddImm, regRowCount, 1);
96424 sqlite3CodeRowTrigger(pParse, pTrigger, TK_UPDATE, pChanges,
96425 TRIGGER_AFTER, pTab, regOldRowid, onError, addr);
96427 /* Repeat the above with the next record to be updated, until
96428 ** all record selected by the WHERE clause have been updated.
96430 sqlite3VdbeAddOp2(v, OP_Goto, 0, addr);
96431 sqlite3VdbeJumpHere(v, addr);
96433 /* Close all tables */
96434 for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
96435 if( openAll || aRegIdx[i]>0 ){
96436 sqlite3VdbeAddOp2(v, OP_Close, iCur+i+1, 0);
96439 sqlite3VdbeAddOp2(v, OP_Close, iCur, 0);
96441 /* Update the sqlite_sequence table by storing the content of the
96442 ** maximum rowid counter values recorded while inserting into
96443 ** autoincrement tables.
96445 if( pParse->nested==0 && pParse->pTriggerTab==0 ){
96446 sqlite3AutoincrementEnd(pParse);
96450 ** Return the number of rows that were changed. If this routine is
96451 ** generating code because of a call to sqlite3NestedParse(), do not
96452 ** invoke the callback function.
96454 if( (db->flags&SQLITE_CountRows) && !pParse->pTriggerTab && !pParse->nested ){
96455 sqlite3VdbeAddOp2(v, OP_ResultRow, regRowCount, 1);
96456 sqlite3VdbeSetNumCols(v, 1);
96457 sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows updated", SQLITE_STATIC);
96460 update_cleanup:
96461 sqlite3AuthContextPop(&sContext);
96462 sqlite3DbFree(db, aRegIdx);
96463 sqlite3DbFree(db, aXRef);
96464 sqlite3SrcListDelete(db, pTabList);
96465 sqlite3ExprListDelete(db, pChanges);
96466 sqlite3ExprDelete(db, pWhere);
96467 return;
96469 /* Make sure "isView" and other macros defined above are undefined. Otherwise
96470 ** thely may interfere with compilation of other functions in this file
96471 ** (or in another file, if this file becomes part of the amalgamation). */
96472 #ifdef isView
96473 #undef isView
96474 #endif
96475 #ifdef pTrigger
96476 #undef pTrigger
96477 #endif
96479 #ifndef SQLITE_OMIT_VIRTUALTABLE
96481 ** Generate code for an UPDATE of a virtual table.
96483 ** The strategy is that we create an ephemerial table that contains
96484 ** for each row to be changed:
96486 ** (A) The original rowid of that row.
96487 ** (B) The revised rowid for the row. (note1)
96488 ** (C) The content of every column in the row.
96490 ** Then we loop over this ephemeral table and for each row in
96491 ** the ephermeral table call VUpdate.
96493 ** When finished, drop the ephemeral table.
96495 ** (note1) Actually, if we know in advance that (A) is always the same
96496 ** as (B) we only store (A), then duplicate (A) when pulling
96497 ** it out of the ephemeral table before calling VUpdate.
96499 static void updateVirtualTable(
96500 Parse *pParse, /* The parsing context */
96501 SrcList *pSrc, /* The virtual table to be modified */
96502 Table *pTab, /* The virtual table */
96503 ExprList *pChanges, /* The columns to change in the UPDATE statement */
96504 Expr *pRowid, /* Expression used to recompute the rowid */
96505 int *aXRef, /* Mapping from columns of pTab to entries in pChanges */
96506 Expr *pWhere /* WHERE clause of the UPDATE statement */
96508 Vdbe *v = pParse->pVdbe; /* Virtual machine under construction */
96509 ExprList *pEList = 0; /* The result set of the SELECT statement */
96510 Select *pSelect = 0; /* The SELECT statement */
96511 Expr *pExpr; /* Temporary expression */
96512 int ephemTab; /* Table holding the result of the SELECT */
96513 int i; /* Loop counter */
96514 int addr; /* Address of top of loop */
96515 int iReg; /* First register in set passed to OP_VUpdate */
96516 sqlite3 *db = pParse->db; /* Database connection */
96517 const char *pVTab = (const char*)sqlite3GetVTable(db, pTab);
96518 SelectDest dest;
96520 /* Construct the SELECT statement that will find the new values for
96521 ** all updated rows.
96523 pEList = sqlite3ExprListAppend(pParse, 0, sqlite3Expr(db, TK_ID, "_rowid_"));
96524 if( pRowid ){
96525 pEList = sqlite3ExprListAppend(pParse, pEList,
96526 sqlite3ExprDup(db, pRowid, 0));
96528 assert( pTab->iPKey<0 );
96529 for(i=0; i<pTab->nCol; i++){
96530 if( aXRef[i]>=0 ){
96531 pExpr = sqlite3ExprDup(db, pChanges->a[aXRef[i]].pExpr, 0);
96532 }else{
96533 pExpr = sqlite3Expr(db, TK_ID, pTab->aCol[i].zName);
96535 pEList = sqlite3ExprListAppend(pParse, pEList, pExpr);
96537 pSelect = sqlite3SelectNew(pParse, pEList, pSrc, pWhere, 0, 0, 0, 0, 0, 0);
96539 /* Create the ephemeral table into which the update results will
96540 ** be stored.
96542 assert( v );
96543 ephemTab = pParse->nTab++;
96544 sqlite3VdbeAddOp2(v, OP_OpenEphemeral, ephemTab, pTab->nCol+1+(pRowid!=0));
96545 sqlite3VdbeChangeP5(v, BTREE_UNORDERED);
96547 /* fill the ephemeral table
96549 sqlite3SelectDestInit(&dest, SRT_Table, ephemTab);
96550 sqlite3Select(pParse, pSelect, &dest);
96552 /* Generate code to scan the ephemeral table and call VUpdate. */
96553 iReg = ++pParse->nMem;
96554 pParse->nMem += pTab->nCol+1;
96555 addr = sqlite3VdbeAddOp2(v, OP_Rewind, ephemTab, 0);
96556 sqlite3VdbeAddOp3(v, OP_Column, ephemTab, 0, iReg);
96557 sqlite3VdbeAddOp3(v, OP_Column, ephemTab, (pRowid?1:0), iReg+1);
96558 for(i=0; i<pTab->nCol; i++){
96559 sqlite3VdbeAddOp3(v, OP_Column, ephemTab, i+1+(pRowid!=0), iReg+2+i);
96561 sqlite3VtabMakeWritable(pParse, pTab);
96562 sqlite3VdbeAddOp4(v, OP_VUpdate, 0, pTab->nCol+2, iReg, pVTab, P4_VTAB);
96563 sqlite3MayAbort(pParse);
96564 sqlite3VdbeAddOp2(v, OP_Next, ephemTab, addr+1);
96565 sqlite3VdbeJumpHere(v, addr);
96566 sqlite3VdbeAddOp2(v, OP_Close, ephemTab, 0);
96568 /* Cleanup */
96569 sqlite3SelectDelete(db, pSelect);
96571 #endif /* SQLITE_OMIT_VIRTUALTABLE */
96573 /************** End of update.c **********************************************/
96574 /************** Begin file vacuum.c ******************************************/
96576 ** 2003 April 6
96578 ** The author disclaims copyright to this source code. In place of
96579 ** a legal notice, here is a blessing:
96581 ** May you do good and not evil.
96582 ** May you find forgiveness for yourself and forgive others.
96583 ** May you share freely, never taking more than you give.
96585 *************************************************************************
96586 ** This file contains code used to implement the VACUUM command.
96588 ** Most of the code in this file may be omitted by defining the
96589 ** SQLITE_OMIT_VACUUM macro.
96592 #if !defined(SQLITE_OMIT_VACUUM) && !defined(SQLITE_OMIT_ATTACH)
96594 ** Finalize a prepared statement. If there was an error, store the
96595 ** text of the error message in *pzErrMsg. Return the result code.
96597 static int vacuumFinalize(sqlite3 *db, sqlite3_stmt *pStmt, char **pzErrMsg){
96598 int rc;
96599 rc = sqlite3VdbeFinalize((Vdbe*)pStmt);
96600 if( rc ){
96601 sqlite3SetString(pzErrMsg, db, sqlite3_errmsg(db));
96603 return rc;
96607 ** Execute zSql on database db. Return an error code.
96609 static int execSql(sqlite3 *db, char **pzErrMsg, const char *zSql){
96610 sqlite3_stmt *pStmt;
96611 VVA_ONLY( int rc; )
96612 if( !zSql ){
96613 return SQLITE_NOMEM;
96615 if( SQLITE_OK!=sqlite3_prepare(db, zSql, -1, &pStmt, 0) ){
96616 sqlite3SetString(pzErrMsg, db, sqlite3_errmsg(db));
96617 return sqlite3_errcode(db);
96619 VVA_ONLY( rc = ) sqlite3_step(pStmt);
96620 assert( rc!=SQLITE_ROW );
96621 return vacuumFinalize(db, pStmt, pzErrMsg);
96625 ** Execute zSql on database db. The statement returns exactly
96626 ** one column. Execute this as SQL on the same database.
96628 static int execExecSql(sqlite3 *db, char **pzErrMsg, const char *zSql){
96629 sqlite3_stmt *pStmt;
96630 int rc;
96632 rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
96633 if( rc!=SQLITE_OK ) return rc;
96635 while( SQLITE_ROW==sqlite3_step(pStmt) ){
96636 rc = execSql(db, pzErrMsg, (char*)sqlite3_column_text(pStmt, 0));
96637 if( rc!=SQLITE_OK ){
96638 vacuumFinalize(db, pStmt, pzErrMsg);
96639 return rc;
96643 return vacuumFinalize(db, pStmt, pzErrMsg);
96647 ** The non-standard VACUUM command is used to clean up the database,
96648 ** collapse free space, etc. It is modelled after the VACUUM command
96649 ** in PostgreSQL.
96651 ** In version 1.0.x of SQLite, the VACUUM command would call
96652 ** gdbm_reorganize() on all the database tables. But beginning
96653 ** with 2.0.0, SQLite no longer uses GDBM so this command has
96654 ** become a no-op.
96656 SQLITE_PRIVATE void sqlite3Vacuum(Parse *pParse){
96657 Vdbe *v = sqlite3GetVdbe(pParse);
96658 if( v ){
96659 sqlite3VdbeAddOp2(v, OP_Vacuum, 0, 0);
96661 return;
96665 ** This routine implements the OP_Vacuum opcode of the VDBE.
96667 SQLITE_PRIVATE int sqlite3RunVacuum(char **pzErrMsg, sqlite3 *db){
96668 int rc = SQLITE_OK; /* Return code from service routines */
96669 Btree *pMain; /* The database being vacuumed */
96670 Btree *pTemp; /* The temporary database we vacuum into */
96671 char *zSql = 0; /* SQL statements */
96672 int saved_flags; /* Saved value of the db->flags */
96673 int saved_nChange; /* Saved value of db->nChange */
96674 int saved_nTotalChange; /* Saved value of db->nTotalChange */
96675 void (*saved_xTrace)(void*,const char*); /* Saved db->xTrace */
96676 Db *pDb = 0; /* Database to detach at end of vacuum */
96677 int isMemDb; /* True if vacuuming a :memory: database */
96678 int nRes; /* Bytes of reserved space at the end of each page */
96679 int nDb; /* Number of attached databases */
96681 if( !db->autoCommit ){
96682 sqlite3SetString(pzErrMsg, db, "cannot VACUUM from within a transaction");
96683 return SQLITE_ERROR;
96685 if( db->activeVdbeCnt>1 ){
96686 sqlite3SetString(pzErrMsg, db,"cannot VACUUM - SQL statements in progress");
96687 return SQLITE_ERROR;
96690 /* Save the current value of the database flags so that it can be
96691 ** restored before returning. Then set the writable-schema flag, and
96692 ** disable CHECK and foreign key constraints. */
96693 saved_flags = db->flags;
96694 saved_nChange = db->nChange;
96695 saved_nTotalChange = db->nTotalChange;
96696 saved_xTrace = db->xTrace;
96697 db->flags |= SQLITE_WriteSchema | SQLITE_IgnoreChecks | SQLITE_PreferBuiltin;
96698 db->flags &= ~(SQLITE_ForeignKeys | SQLITE_ReverseOrder);
96699 db->xTrace = 0;
96701 pMain = db->aDb[0].pBt;
96702 isMemDb = sqlite3PagerIsMemdb(sqlite3BtreePager(pMain));
96704 /* Attach the temporary database as 'vacuum_db'. The synchronous pragma
96705 ** can be set to 'off' for this file, as it is not recovered if a crash
96706 ** occurs anyway. The integrity of the database is maintained by a
96707 ** (possibly synchronous) transaction opened on the main database before
96708 ** sqlite3BtreeCopyFile() is called.
96710 ** An optimisation would be to use a non-journaled pager.
96711 ** (Later:) I tried setting "PRAGMA vacuum_db.journal_mode=OFF" but
96712 ** that actually made the VACUUM run slower. Very little journalling
96713 ** actually occurs when doing a vacuum since the vacuum_db is initially
96714 ** empty. Only the journal header is written. Apparently it takes more
96715 ** time to parse and run the PRAGMA to turn journalling off than it does
96716 ** to write the journal header file.
96718 nDb = db->nDb;
96719 if( sqlite3TempInMemory(db) ){
96720 zSql = "ATTACH ':memory:' AS vacuum_db;";
96721 }else{
96722 zSql = "ATTACH '' AS vacuum_db;";
96724 rc = execSql(db, pzErrMsg, zSql);
96725 if( db->nDb>nDb ){
96726 pDb = &db->aDb[db->nDb-1];
96727 assert( strcmp(pDb->zName,"vacuum_db")==0 );
96729 if( rc!=SQLITE_OK ) goto end_of_vacuum;
96730 pTemp = db->aDb[db->nDb-1].pBt;
96732 /* The call to execSql() to attach the temp database has left the file
96733 ** locked (as there was more than one active statement when the transaction
96734 ** to read the schema was concluded. Unlock it here so that this doesn't
96735 ** cause problems for the call to BtreeSetPageSize() below. */
96736 sqlite3BtreeCommit(pTemp);
96738 nRes = sqlite3BtreeGetReserve(pMain);
96740 /* A VACUUM cannot change the pagesize of an encrypted database. */
96741 #ifdef SQLITE_HAS_CODEC
96742 if( db->nextPagesize ){
96743 extern void sqlite3CodecGetKey(sqlite3*, int, void**, int*);
96744 int nKey;
96745 char *zKey;
96746 sqlite3CodecGetKey(db, 0, (void**)&zKey, &nKey);
96747 if( nKey ) db->nextPagesize = 0;
96749 #endif
96751 /* Do not attempt to change the page size for a WAL database */
96752 if( sqlite3PagerGetJournalMode(sqlite3BtreePager(pMain))
96753 ==PAGER_JOURNALMODE_WAL ){
96754 db->nextPagesize = 0;
96757 if( sqlite3BtreeSetPageSize(pTemp, sqlite3BtreeGetPageSize(pMain), nRes, 0)
96758 || (!isMemDb && sqlite3BtreeSetPageSize(pTemp, db->nextPagesize, nRes, 0))
96759 || NEVER(db->mallocFailed)
96761 rc = SQLITE_NOMEM;
96762 goto end_of_vacuum;
96764 rc = execSql(db, pzErrMsg, "PRAGMA vacuum_db.synchronous=OFF");
96765 if( rc!=SQLITE_OK ){
96766 goto end_of_vacuum;
96769 #ifndef SQLITE_OMIT_AUTOVACUUM
96770 sqlite3BtreeSetAutoVacuum(pTemp, db->nextAutovac>=0 ? db->nextAutovac :
96771 sqlite3BtreeGetAutoVacuum(pMain));
96772 #endif
96774 /* Begin a transaction */
96775 rc = execSql(db, pzErrMsg, "BEGIN EXCLUSIVE;");
96776 if( rc!=SQLITE_OK ) goto end_of_vacuum;
96778 /* Query the schema of the main database. Create a mirror schema
96779 ** in the temporary database.
96781 rc = execExecSql(db, pzErrMsg,
96782 "SELECT 'CREATE TABLE vacuum_db.' || substr(sql,14) "
96783 " FROM sqlite_master WHERE type='table' AND name!='sqlite_sequence'"
96784 " AND rootpage>0"
96786 if( rc!=SQLITE_OK ) goto end_of_vacuum;
96787 rc = execExecSql(db, pzErrMsg,
96788 "SELECT 'CREATE INDEX vacuum_db.' || substr(sql,14)"
96789 " FROM sqlite_master WHERE sql LIKE 'CREATE INDEX %' ");
96790 if( rc!=SQLITE_OK ) goto end_of_vacuum;
96791 rc = execExecSql(db, pzErrMsg,
96792 "SELECT 'CREATE UNIQUE INDEX vacuum_db.' || substr(sql,21) "
96793 " FROM sqlite_master WHERE sql LIKE 'CREATE UNIQUE INDEX %'");
96794 if( rc!=SQLITE_OK ) goto end_of_vacuum;
96796 /* Loop through the tables in the main database. For each, do
96797 ** an "INSERT INTO vacuum_db.xxx SELECT * FROM main.xxx;" to copy
96798 ** the contents to the temporary database.
96800 rc = execExecSql(db, pzErrMsg,
96801 "SELECT 'INSERT INTO vacuum_db.' || quote(name) "
96802 "|| ' SELECT * FROM main.' || quote(name) || ';'"
96803 "FROM main.sqlite_master "
96804 "WHERE type = 'table' AND name!='sqlite_sequence' "
96805 " AND rootpage>0"
96807 if( rc!=SQLITE_OK ) goto end_of_vacuum;
96809 /* Copy over the sequence table
96811 rc = execExecSql(db, pzErrMsg,
96812 "SELECT 'DELETE FROM vacuum_db.' || quote(name) || ';' "
96813 "FROM vacuum_db.sqlite_master WHERE name='sqlite_sequence' "
96815 if( rc!=SQLITE_OK ) goto end_of_vacuum;
96816 rc = execExecSql(db, pzErrMsg,
96817 "SELECT 'INSERT INTO vacuum_db.' || quote(name) "
96818 "|| ' SELECT * FROM main.' || quote(name) || ';' "
96819 "FROM vacuum_db.sqlite_master WHERE name=='sqlite_sequence';"
96821 if( rc!=SQLITE_OK ) goto end_of_vacuum;
96824 /* Copy the triggers, views, and virtual tables from the main database
96825 ** over to the temporary database. None of these objects has any
96826 ** associated storage, so all we have to do is copy their entries
96827 ** from the SQLITE_MASTER table.
96829 rc = execSql(db, pzErrMsg,
96830 "INSERT INTO vacuum_db.sqlite_master "
96831 " SELECT type, name, tbl_name, rootpage, sql"
96832 " FROM main.sqlite_master"
96833 " WHERE type='view' OR type='trigger'"
96834 " OR (type='table' AND rootpage=0)"
96836 if( rc ) goto end_of_vacuum;
96838 /* At this point, unless the main db was completely empty, there is now a
96839 ** transaction open on the vacuum database, but not on the main database.
96840 ** Open a btree level transaction on the main database. This allows a
96841 ** call to sqlite3BtreeCopyFile(). The main database btree level
96842 ** transaction is then committed, so the SQL level never knows it was
96843 ** opened for writing. This way, the SQL transaction used to create the
96844 ** temporary database never needs to be committed.
96847 u32 meta;
96848 int i;
96850 /* This array determines which meta meta values are preserved in the
96851 ** vacuum. Even entries are the meta value number and odd entries
96852 ** are an increment to apply to the meta value after the vacuum.
96853 ** The increment is used to increase the schema cookie so that other
96854 ** connections to the same database will know to reread the schema.
96856 static const unsigned char aCopy[] = {
96857 BTREE_SCHEMA_VERSION, 1, /* Add one to the old schema cookie */
96858 BTREE_DEFAULT_CACHE_SIZE, 0, /* Preserve the default page cache size */
96859 BTREE_TEXT_ENCODING, 0, /* Preserve the text encoding */
96860 BTREE_USER_VERSION, 0, /* Preserve the user version */
96863 assert( 1==sqlite3BtreeIsInTrans(pTemp) );
96864 assert( 1==sqlite3BtreeIsInTrans(pMain) );
96866 /* Copy Btree meta values */
96867 for(i=0; i<ArraySize(aCopy); i+=2){
96868 /* GetMeta() and UpdateMeta() cannot fail in this context because
96869 ** we already have page 1 loaded into cache and marked dirty. */
96870 sqlite3BtreeGetMeta(pMain, aCopy[i], &meta);
96871 rc = sqlite3BtreeUpdateMeta(pTemp, aCopy[i], meta+aCopy[i+1]);
96872 if( NEVER(rc!=SQLITE_OK) ) goto end_of_vacuum;
96875 rc = sqlite3BtreeCopyFile(pMain, pTemp);
96876 if( rc!=SQLITE_OK ) goto end_of_vacuum;
96877 rc = sqlite3BtreeCommit(pTemp);
96878 if( rc!=SQLITE_OK ) goto end_of_vacuum;
96879 #ifndef SQLITE_OMIT_AUTOVACUUM
96880 sqlite3BtreeSetAutoVacuum(pMain, sqlite3BtreeGetAutoVacuum(pTemp));
96881 #endif
96884 assert( rc==SQLITE_OK );
96885 rc = sqlite3BtreeSetPageSize(pMain, sqlite3BtreeGetPageSize(pTemp), nRes,1);
96887 end_of_vacuum:
96888 /* Restore the original value of db->flags */
96889 db->flags = saved_flags;
96890 db->nChange = saved_nChange;
96891 db->nTotalChange = saved_nTotalChange;
96892 db->xTrace = saved_xTrace;
96893 sqlite3BtreeSetPageSize(pMain, -1, -1, 1);
96895 /* Currently there is an SQL level transaction open on the vacuum
96896 ** database. No locks are held on any other files (since the main file
96897 ** was committed at the btree level). So it safe to end the transaction
96898 ** by manually setting the autoCommit flag to true and detaching the
96899 ** vacuum database. The vacuum_db journal file is deleted when the pager
96900 ** is closed by the DETACH.
96902 db->autoCommit = 1;
96904 if( pDb ){
96905 sqlite3BtreeClose(pDb->pBt);
96906 pDb->pBt = 0;
96907 pDb->pSchema = 0;
96910 /* This both clears the schemas and reduces the size of the db->aDb[]
96911 ** array. */
96912 sqlite3ResetInternalSchema(db, -1);
96914 return rc;
96917 #endif /* SQLITE_OMIT_VACUUM && SQLITE_OMIT_ATTACH */
96919 /************** End of vacuum.c **********************************************/
96920 /************** Begin file vtab.c ********************************************/
96922 ** 2006 June 10
96924 ** The author disclaims copyright to this source code. In place of
96925 ** a legal notice, here is a blessing:
96927 ** May you do good and not evil.
96928 ** May you find forgiveness for yourself and forgive others.
96929 ** May you share freely, never taking more than you give.
96931 *************************************************************************
96932 ** This file contains code used to help implement virtual tables.
96934 #ifndef SQLITE_OMIT_VIRTUALTABLE
96937 ** The actual function that does the work of creating a new module.
96938 ** This function implements the sqlite3_create_module() and
96939 ** sqlite3_create_module_v2() interfaces.
96941 static int createModule(
96942 sqlite3 *db, /* Database in which module is registered */
96943 const char *zName, /* Name assigned to this module */
96944 const sqlite3_module *pModule, /* The definition of the module */
96945 void *pAux, /* Context pointer for xCreate/xConnect */
96946 void (*xDestroy)(void *) /* Module destructor function */
96948 int rc, nName;
96949 Module *pMod;
96951 sqlite3_mutex_enter(db->mutex);
96952 nName = sqlite3Strlen30(zName);
96953 pMod = (Module *)sqlite3DbMallocRaw(db, sizeof(Module) + nName + 1);
96954 if( pMod ){
96955 Module *pDel;
96956 char *zCopy = (char *)(&pMod[1]);
96957 memcpy(zCopy, zName, nName+1);
96958 pMod->zName = zCopy;
96959 pMod->pModule = pModule;
96960 pMod->pAux = pAux;
96961 pMod->xDestroy = xDestroy;
96962 pDel = (Module *)sqlite3HashInsert(&db->aModule, zCopy, nName, (void*)pMod);
96963 if( pDel && pDel->xDestroy ){
96964 pDel->xDestroy(pDel->pAux);
96966 sqlite3DbFree(db, pDel);
96967 if( pDel==pMod ){
96968 db->mallocFailed = 1;
96970 sqlite3ResetInternalSchema(db, -1);
96971 }else if( xDestroy ){
96972 xDestroy(pAux);
96974 rc = sqlite3ApiExit(db, SQLITE_OK);
96975 sqlite3_mutex_leave(db->mutex);
96976 return rc;
96981 ** External API function used to create a new virtual-table module.
96983 SQLITE_API int sqlite3_create_module(
96984 sqlite3 *db, /* Database in which module is registered */
96985 const char *zName, /* Name assigned to this module */
96986 const sqlite3_module *pModule, /* The definition of the module */
96987 void *pAux /* Context pointer for xCreate/xConnect */
96989 return createModule(db, zName, pModule, pAux, 0);
96993 ** External API function used to create a new virtual-table module.
96995 SQLITE_API int sqlite3_create_module_v2(
96996 sqlite3 *db, /* Database in which module is registered */
96997 const char *zName, /* Name assigned to this module */
96998 const sqlite3_module *pModule, /* The definition of the module */
96999 void *pAux, /* Context pointer for xCreate/xConnect */
97000 void (*xDestroy)(void *) /* Module destructor function */
97002 return createModule(db, zName, pModule, pAux, xDestroy);
97006 ** Lock the virtual table so that it cannot be disconnected.
97007 ** Locks nest. Every lock should have a corresponding unlock.
97008 ** If an unlock is omitted, resources leaks will occur.
97010 ** If a disconnect is attempted while a virtual table is locked,
97011 ** the disconnect is deferred until all locks have been removed.
97013 SQLITE_PRIVATE void sqlite3VtabLock(VTable *pVTab){
97014 pVTab->nRef++;
97019 ** pTab is a pointer to a Table structure representing a virtual-table.
97020 ** Return a pointer to the VTable object used by connection db to access
97021 ** this virtual-table, if one has been created, or NULL otherwise.
97023 SQLITE_PRIVATE VTable *sqlite3GetVTable(sqlite3 *db, Table *pTab){
97024 VTable *pVtab;
97025 assert( IsVirtual(pTab) );
97026 for(pVtab=pTab->pVTable; pVtab && pVtab->db!=db; pVtab=pVtab->pNext);
97027 return pVtab;
97031 ** Decrement the ref-count on a virtual table object. When the ref-count
97032 ** reaches zero, call the xDisconnect() method to delete the object.
97034 SQLITE_PRIVATE void sqlite3VtabUnlock(VTable *pVTab){
97035 sqlite3 *db = pVTab->db;
97037 assert( db );
97038 assert( pVTab->nRef>0 );
97039 assert( sqlite3SafetyCheckOk(db) );
97041 pVTab->nRef--;
97042 if( pVTab->nRef==0 ){
97043 sqlite3_vtab *p = pVTab->pVtab;
97044 if( p ){
97045 p->pModule->xDisconnect(p);
97047 sqlite3DbFree(db, pVTab);
97052 ** Table p is a virtual table. This function moves all elements in the
97053 ** p->pVTable list to the sqlite3.pDisconnect lists of their associated
97054 ** database connections to be disconnected at the next opportunity.
97055 ** Except, if argument db is not NULL, then the entry associated with
97056 ** connection db is left in the p->pVTable list.
97058 static VTable *vtabDisconnectAll(sqlite3 *db, Table *p){
97059 VTable *pRet = 0;
97060 VTable *pVTable = p->pVTable;
97061 p->pVTable = 0;
97063 /* Assert that the mutex (if any) associated with the BtShared database
97064 ** that contains table p is held by the caller. See header comments
97065 ** above function sqlite3VtabUnlockList() for an explanation of why
97066 ** this makes it safe to access the sqlite3.pDisconnect list of any
97067 ** database connection that may have an entry in the p->pVTable list.
97069 assert( db==0 || sqlite3SchemaMutexHeld(db, 0, p->pSchema) );
97071 while( pVTable ){
97072 sqlite3 *db2 = pVTable->db;
97073 VTable *pNext = pVTable->pNext;
97074 assert( db2 );
97075 if( db2==db ){
97076 pRet = pVTable;
97077 p->pVTable = pRet;
97078 pRet->pNext = 0;
97079 }else{
97080 pVTable->pNext = db2->pDisconnect;
97081 db2->pDisconnect = pVTable;
97083 pVTable = pNext;
97086 assert( !db || pRet );
97087 return pRet;
97092 ** Disconnect all the virtual table objects in the sqlite3.pDisconnect list.
97094 ** This function may only be called when the mutexes associated with all
97095 ** shared b-tree databases opened using connection db are held by the
97096 ** caller. This is done to protect the sqlite3.pDisconnect list. The
97097 ** sqlite3.pDisconnect list is accessed only as follows:
97099 ** 1) By this function. In this case, all BtShared mutexes and the mutex
97100 ** associated with the database handle itself must be held.
97102 ** 2) By function vtabDisconnectAll(), when it adds a VTable entry to
97103 ** the sqlite3.pDisconnect list. In this case either the BtShared mutex
97104 ** associated with the database the virtual table is stored in is held
97105 ** or, if the virtual table is stored in a non-sharable database, then
97106 ** the database handle mutex is held.
97108 ** As a result, a sqlite3.pDisconnect cannot be accessed simultaneously
97109 ** by multiple threads. It is thread-safe.
97111 SQLITE_PRIVATE void sqlite3VtabUnlockList(sqlite3 *db){
97112 VTable *p = db->pDisconnect;
97113 db->pDisconnect = 0;
97115 assert( sqlite3BtreeHoldsAllMutexes(db) );
97116 assert( sqlite3_mutex_held(db->mutex) );
97118 if( p ){
97119 sqlite3ExpirePreparedStatements(db);
97120 do {
97121 VTable *pNext = p->pNext;
97122 sqlite3VtabUnlock(p);
97123 p = pNext;
97124 }while( p );
97129 ** Clear any and all virtual-table information from the Table record.
97130 ** This routine is called, for example, just before deleting the Table
97131 ** record.
97133 ** Since it is a virtual-table, the Table structure contains a pointer
97134 ** to the head of a linked list of VTable structures. Each VTable
97135 ** structure is associated with a single sqlite3* user of the schema.
97136 ** The reference count of the VTable structure associated with database
97137 ** connection db is decremented immediately (which may lead to the
97138 ** structure being xDisconnected and free). Any other VTable structures
97139 ** in the list are moved to the sqlite3.pDisconnect list of the associated
97140 ** database connection.
97142 SQLITE_PRIVATE void sqlite3VtabClear(sqlite3 *db, Table *p){
97143 if( !db || db->pnBytesFreed==0 ) vtabDisconnectAll(0, p);
97144 if( p->azModuleArg ){
97145 int i;
97146 for(i=0; i<p->nModuleArg; i++){
97147 sqlite3DbFree(db, p->azModuleArg[i]);
97149 sqlite3DbFree(db, p->azModuleArg);
97154 ** Add a new module argument to pTable->azModuleArg[].
97155 ** The string is not copied - the pointer is stored. The
97156 ** string will be freed automatically when the table is
97157 ** deleted.
97159 static void addModuleArgument(sqlite3 *db, Table *pTable, char *zArg){
97160 int i = pTable->nModuleArg++;
97161 int nBytes = sizeof(char *)*(1+pTable->nModuleArg);
97162 char **azModuleArg;
97163 azModuleArg = sqlite3DbRealloc(db, pTable->azModuleArg, nBytes);
97164 if( azModuleArg==0 ){
97165 int j;
97166 for(j=0; j<i; j++){
97167 sqlite3DbFree(db, pTable->azModuleArg[j]);
97169 sqlite3DbFree(db, zArg);
97170 sqlite3DbFree(db, pTable->azModuleArg);
97171 pTable->nModuleArg = 0;
97172 }else{
97173 azModuleArg[i] = zArg;
97174 azModuleArg[i+1] = 0;
97176 pTable->azModuleArg = azModuleArg;
97180 ** The parser calls this routine when it first sees a CREATE VIRTUAL TABLE
97181 ** statement. The module name has been parsed, but the optional list
97182 ** of parameters that follow the module name are still pending.
97184 SQLITE_PRIVATE void sqlite3VtabBeginParse(
97185 Parse *pParse, /* Parsing context */
97186 Token *pName1, /* Name of new table, or database name */
97187 Token *pName2, /* Name of new table or NULL */
97188 Token *pModuleName /* Name of the module for the virtual table */
97190 int iDb; /* The database the table is being created in */
97191 Table *pTable; /* The new virtual table */
97192 sqlite3 *db; /* Database connection */
97194 sqlite3StartTable(pParse, pName1, pName2, 0, 0, 1, 0);
97195 pTable = pParse->pNewTable;
97196 if( pTable==0 ) return;
97197 assert( 0==pTable->pIndex );
97199 db = pParse->db;
97200 iDb = sqlite3SchemaToIndex(db, pTable->pSchema);
97201 assert( iDb>=0 );
97203 pTable->tabFlags |= TF_Virtual;
97204 pTable->nModuleArg = 0;
97205 addModuleArgument(db, pTable, sqlite3NameFromToken(db, pModuleName));
97206 addModuleArgument(db, pTable, sqlite3DbStrDup(db, db->aDb[iDb].zName));
97207 addModuleArgument(db, pTable, sqlite3DbStrDup(db, pTable->zName));
97208 pParse->sNameToken.n = (int)(&pModuleName->z[pModuleName->n] - pName1->z);
97210 #ifndef SQLITE_OMIT_AUTHORIZATION
97211 /* Creating a virtual table invokes the authorization callback twice.
97212 ** The first invocation, to obtain permission to INSERT a row into the
97213 ** sqlite_master table, has already been made by sqlite3StartTable().
97214 ** The second call, to obtain permission to create the table, is made now.
97216 if( pTable->azModuleArg ){
97217 sqlite3AuthCheck(pParse, SQLITE_CREATE_VTABLE, pTable->zName,
97218 pTable->azModuleArg[0], pParse->db->aDb[iDb].zName);
97220 #endif
97224 ** This routine takes the module argument that has been accumulating
97225 ** in pParse->zArg[] and appends it to the list of arguments on the
97226 ** virtual table currently under construction in pParse->pTable.
97228 static void addArgumentToVtab(Parse *pParse){
97229 if( pParse->sArg.z && ALWAYS(pParse->pNewTable) ){
97230 const char *z = (const char*)pParse->sArg.z;
97231 int n = pParse->sArg.n;
97232 sqlite3 *db = pParse->db;
97233 addModuleArgument(db, pParse->pNewTable, sqlite3DbStrNDup(db, z, n));
97238 ** The parser calls this routine after the CREATE VIRTUAL TABLE statement
97239 ** has been completely parsed.
97241 SQLITE_PRIVATE void sqlite3VtabFinishParse(Parse *pParse, Token *pEnd){
97242 Table *pTab = pParse->pNewTable; /* The table being constructed */
97243 sqlite3 *db = pParse->db; /* The database connection */
97245 if( pTab==0 ) return;
97246 addArgumentToVtab(pParse);
97247 pParse->sArg.z = 0;
97248 if( pTab->nModuleArg<1 ) return;
97250 /* If the CREATE VIRTUAL TABLE statement is being entered for the
97251 ** first time (in other words if the virtual table is actually being
97252 ** created now instead of just being read out of sqlite_master) then
97253 ** do additional initialization work and store the statement text
97254 ** in the sqlite_master table.
97256 if( !db->init.busy ){
97257 char *zStmt;
97258 char *zWhere;
97259 int iDb;
97260 Vdbe *v;
97262 /* Compute the complete text of the CREATE VIRTUAL TABLE statement */
97263 if( pEnd ){
97264 pParse->sNameToken.n = (int)(pEnd->z - pParse->sNameToken.z) + pEnd->n;
97266 zStmt = sqlite3MPrintf(db, "CREATE VIRTUAL TABLE %T", &pParse->sNameToken);
97268 /* A slot for the record has already been allocated in the
97269 ** SQLITE_MASTER table. We just need to update that slot with all
97270 ** the information we've collected.
97272 ** The VM register number pParse->regRowid holds the rowid of an
97273 ** entry in the sqlite_master table tht was created for this vtab
97274 ** by sqlite3StartTable().
97276 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
97277 sqlite3NestedParse(pParse,
97278 "UPDATE %Q.%s "
97279 "SET type='table', name=%Q, tbl_name=%Q, rootpage=0, sql=%Q "
97280 "WHERE rowid=#%d",
97281 db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
97282 pTab->zName,
97283 pTab->zName,
97284 zStmt,
97285 pParse->regRowid
97287 sqlite3DbFree(db, zStmt);
97288 v = sqlite3GetVdbe(pParse);
97289 sqlite3ChangeCookie(pParse, iDb);
97291 sqlite3VdbeAddOp2(v, OP_Expire, 0, 0);
97292 zWhere = sqlite3MPrintf(db, "name='%q' AND type='table'", pTab->zName);
97293 sqlite3VdbeAddOp4(v, OP_ParseSchema, iDb, 0, 0, zWhere, P4_DYNAMIC);
97294 sqlite3VdbeAddOp4(v, OP_VCreate, iDb, 0, 0,
97295 pTab->zName, sqlite3Strlen30(pTab->zName) + 1);
97298 /* If we are rereading the sqlite_master table create the in-memory
97299 ** record of the table. The xConnect() method is not called until
97300 ** the first time the virtual table is used in an SQL statement. This
97301 ** allows a schema that contains virtual tables to be loaded before
97302 ** the required virtual table implementations are registered. */
97303 else {
97304 Table *pOld;
97305 Schema *pSchema = pTab->pSchema;
97306 const char *zName = pTab->zName;
97307 int nName = sqlite3Strlen30(zName);
97308 assert( sqlite3SchemaMutexHeld(db, 0, pSchema) );
97309 pOld = sqlite3HashInsert(&pSchema->tblHash, zName, nName, pTab);
97310 if( pOld ){
97311 db->mallocFailed = 1;
97312 assert( pTab==pOld ); /* Malloc must have failed inside HashInsert() */
97313 return;
97315 pParse->pNewTable = 0;
97320 ** The parser calls this routine when it sees the first token
97321 ** of an argument to the module name in a CREATE VIRTUAL TABLE statement.
97323 SQLITE_PRIVATE void sqlite3VtabArgInit(Parse *pParse){
97324 addArgumentToVtab(pParse);
97325 pParse->sArg.z = 0;
97326 pParse->sArg.n = 0;
97330 ** The parser calls this routine for each token after the first token
97331 ** in an argument to the module name in a CREATE VIRTUAL TABLE statement.
97333 SQLITE_PRIVATE void sqlite3VtabArgExtend(Parse *pParse, Token *p){
97334 Token *pArg = &pParse->sArg;
97335 if( pArg->z==0 ){
97336 pArg->z = p->z;
97337 pArg->n = p->n;
97338 }else{
97339 assert(pArg->z < p->z);
97340 pArg->n = (int)(&p->z[p->n] - pArg->z);
97345 ** Invoke a virtual table constructor (either xCreate or xConnect). The
97346 ** pointer to the function to invoke is passed as the fourth parameter
97347 ** to this procedure.
97349 static int vtabCallConstructor(
97350 sqlite3 *db,
97351 Table *pTab,
97352 Module *pMod,
97353 int (*xConstruct)(sqlite3*,void*,int,const char*const*,sqlite3_vtab**,char**),
97354 char **pzErr
97356 VTable *pVTable;
97357 int rc;
97358 const char *const*azArg = (const char *const*)pTab->azModuleArg;
97359 int nArg = pTab->nModuleArg;
97360 char *zErr = 0;
97361 char *zModuleName = sqlite3MPrintf(db, "%s", pTab->zName);
97363 if( !zModuleName ){
97364 return SQLITE_NOMEM;
97367 pVTable = sqlite3DbMallocZero(db, sizeof(VTable));
97368 if( !pVTable ){
97369 sqlite3DbFree(db, zModuleName);
97370 return SQLITE_NOMEM;
97372 pVTable->db = db;
97373 pVTable->pMod = pMod;
97375 assert( !db->pVTab );
97376 assert( xConstruct );
97377 db->pVTab = pTab;
97379 /* Invoke the virtual table constructor */
97380 rc = xConstruct(db, pMod->pAux, nArg, azArg, &pVTable->pVtab, &zErr);
97381 if( rc==SQLITE_NOMEM ) db->mallocFailed = 1;
97383 if( SQLITE_OK!=rc ){
97384 if( zErr==0 ){
97385 *pzErr = sqlite3MPrintf(db, "vtable constructor failed: %s", zModuleName);
97386 }else {
97387 *pzErr = sqlite3MPrintf(db, "%s", zErr);
97388 sqlite3_free(zErr);
97390 sqlite3DbFree(db, pVTable);
97391 }else if( ALWAYS(pVTable->pVtab) ){
97392 /* Justification of ALWAYS(): A correct vtab constructor must allocate
97393 ** the sqlite3_vtab object if successful. */
97394 pVTable->pVtab->pModule = pMod->pModule;
97395 pVTable->nRef = 1;
97396 if( db->pVTab ){
97397 const char *zFormat = "vtable constructor did not declare schema: %s";
97398 *pzErr = sqlite3MPrintf(db, zFormat, pTab->zName);
97399 sqlite3VtabUnlock(pVTable);
97400 rc = SQLITE_ERROR;
97401 }else{
97402 int iCol;
97403 /* If everything went according to plan, link the new VTable structure
97404 ** into the linked list headed by pTab->pVTable. Then loop through the
97405 ** columns of the table to see if any of them contain the token "hidden".
97406 ** If so, set the Column.isHidden flag and remove the token from
97407 ** the type string. */
97408 pVTable->pNext = pTab->pVTable;
97409 pTab->pVTable = pVTable;
97411 for(iCol=0; iCol<pTab->nCol; iCol++){
97412 char *zType = pTab->aCol[iCol].zType;
97413 int nType;
97414 int i = 0;
97415 if( !zType ) continue;
97416 nType = sqlite3Strlen30(zType);
97417 if( sqlite3StrNICmp("hidden", zType, 6)||(zType[6] && zType[6]!=' ') ){
97418 for(i=0; i<nType; i++){
97419 if( (0==sqlite3StrNICmp(" hidden", &zType[i], 7))
97420 && (zType[i+7]=='\0' || zType[i+7]==' ')
97422 i++;
97423 break;
97427 if( i<nType ){
97428 int j;
97429 int nDel = 6 + (zType[i+6] ? 1 : 0);
97430 for(j=i; (j+nDel)<=nType; j++){
97431 zType[j] = zType[j+nDel];
97433 if( zType[i]=='\0' && i>0 ){
97434 assert(zType[i-1]==' ');
97435 zType[i-1] = '\0';
97437 pTab->aCol[iCol].isHidden = 1;
97443 sqlite3DbFree(db, zModuleName);
97444 db->pVTab = 0;
97445 return rc;
97449 ** This function is invoked by the parser to call the xConnect() method
97450 ** of the virtual table pTab. If an error occurs, an error code is returned
97451 ** and an error left in pParse.
97453 ** This call is a no-op if table pTab is not a virtual table.
97455 SQLITE_PRIVATE int sqlite3VtabCallConnect(Parse *pParse, Table *pTab){
97456 sqlite3 *db = pParse->db;
97457 const char *zMod;
97458 Module *pMod;
97459 int rc;
97461 assert( pTab );
97462 if( (pTab->tabFlags & TF_Virtual)==0 || sqlite3GetVTable(db, pTab) ){
97463 return SQLITE_OK;
97466 /* Locate the required virtual table module */
97467 zMod = pTab->azModuleArg[0];
97468 pMod = (Module*)sqlite3HashFind(&db->aModule, zMod, sqlite3Strlen30(zMod));
97470 if( !pMod ){
97471 const char *zModule = pTab->azModuleArg[0];
97472 sqlite3ErrorMsg(pParse, "no such module: %s", zModule);
97473 rc = SQLITE_ERROR;
97474 }else{
97475 char *zErr = 0;
97476 rc = vtabCallConstructor(db, pTab, pMod, pMod->pModule->xConnect, &zErr);
97477 if( rc!=SQLITE_OK ){
97478 sqlite3ErrorMsg(pParse, "%s", zErr);
97480 sqlite3DbFree(db, zErr);
97483 return rc;
97487 ** Add the virtual table pVTab to the array sqlite3.aVTrans[].
97489 static int addToVTrans(sqlite3 *db, VTable *pVTab){
97490 const int ARRAY_INCR = 5;
97492 /* Grow the sqlite3.aVTrans array if required */
97493 if( (db->nVTrans%ARRAY_INCR)==0 ){
97494 VTable **aVTrans;
97495 int nBytes = sizeof(sqlite3_vtab *) * (db->nVTrans + ARRAY_INCR);
97496 aVTrans = sqlite3DbRealloc(db, (void *)db->aVTrans, nBytes);
97497 if( !aVTrans ){
97498 return SQLITE_NOMEM;
97500 memset(&aVTrans[db->nVTrans], 0, sizeof(sqlite3_vtab *)*ARRAY_INCR);
97501 db->aVTrans = aVTrans;
97504 /* Add pVtab to the end of sqlite3.aVTrans */
97505 db->aVTrans[db->nVTrans++] = pVTab;
97506 sqlite3VtabLock(pVTab);
97507 return SQLITE_OK;
97511 ** This function is invoked by the vdbe to call the xCreate method
97512 ** of the virtual table named zTab in database iDb.
97514 ** If an error occurs, *pzErr is set to point an an English language
97515 ** description of the error and an SQLITE_XXX error code is returned.
97516 ** In this case the caller must call sqlite3DbFree(db, ) on *pzErr.
97518 SQLITE_PRIVATE int sqlite3VtabCallCreate(sqlite3 *db, int iDb, const char *zTab, char **pzErr){
97519 int rc = SQLITE_OK;
97520 Table *pTab;
97521 Module *pMod;
97522 const char *zMod;
97524 pTab = sqlite3FindTable(db, zTab, db->aDb[iDb].zName);
97525 assert( pTab && (pTab->tabFlags & TF_Virtual)!=0 && !pTab->pVTable );
97527 /* Locate the required virtual table module */
97528 zMod = pTab->azModuleArg[0];
97529 pMod = (Module*)sqlite3HashFind(&db->aModule, zMod, sqlite3Strlen30(zMod));
97531 /* If the module has been registered and includes a Create method,
97532 ** invoke it now. If the module has not been registered, return an
97533 ** error. Otherwise, do nothing.
97535 if( !pMod ){
97536 *pzErr = sqlite3MPrintf(db, "no such module: %s", zMod);
97537 rc = SQLITE_ERROR;
97538 }else{
97539 rc = vtabCallConstructor(db, pTab, pMod, pMod->pModule->xCreate, pzErr);
97542 /* Justification of ALWAYS(): The xConstructor method is required to
97543 ** create a valid sqlite3_vtab if it returns SQLITE_OK. */
97544 if( rc==SQLITE_OK && ALWAYS(sqlite3GetVTable(db, pTab)) ){
97545 rc = addToVTrans(db, sqlite3GetVTable(db, pTab));
97548 return rc;
97552 ** This function is used to set the schema of a virtual table. It is only
97553 ** valid to call this function from within the xCreate() or xConnect() of a
97554 ** virtual table module.
97556 SQLITE_API int sqlite3_declare_vtab(sqlite3 *db, const char *zCreateTable){
97557 Parse *pParse;
97559 int rc = SQLITE_OK;
97560 Table *pTab;
97561 char *zErr = 0;
97563 sqlite3_mutex_enter(db->mutex);
97564 pTab = db->pVTab;
97565 if( !pTab ){
97566 sqlite3Error(db, SQLITE_MISUSE, 0);
97567 sqlite3_mutex_leave(db->mutex);
97568 return SQLITE_MISUSE_BKPT;
97570 assert( (pTab->tabFlags & TF_Virtual)!=0 );
97572 pParse = sqlite3StackAllocZero(db, sizeof(*pParse));
97573 if( pParse==0 ){
97574 rc = SQLITE_NOMEM;
97575 }else{
97576 pParse->declareVtab = 1;
97577 pParse->db = db;
97578 pParse->nQueryLoop = 1;
97580 if( SQLITE_OK==sqlite3RunParser(pParse, zCreateTable, &zErr)
97581 && pParse->pNewTable
97582 && !db->mallocFailed
97583 && !pParse->pNewTable->pSelect
97584 && (pParse->pNewTable->tabFlags & TF_Virtual)==0
97586 if( !pTab->aCol ){
97587 pTab->aCol = pParse->pNewTable->aCol;
97588 pTab->nCol = pParse->pNewTable->nCol;
97589 pParse->pNewTable->nCol = 0;
97590 pParse->pNewTable->aCol = 0;
97592 db->pVTab = 0;
97593 }else{
97594 sqlite3Error(db, SQLITE_ERROR, (zErr ? "%s" : 0), zErr);
97595 sqlite3DbFree(db, zErr);
97596 rc = SQLITE_ERROR;
97598 pParse->declareVtab = 0;
97600 if( pParse->pVdbe ){
97601 sqlite3VdbeFinalize(pParse->pVdbe);
97603 sqlite3DeleteTable(db, pParse->pNewTable);
97604 sqlite3StackFree(db, pParse);
97607 assert( (rc&0xff)==rc );
97608 rc = sqlite3ApiExit(db, rc);
97609 sqlite3_mutex_leave(db->mutex);
97610 return rc;
97614 ** This function is invoked by the vdbe to call the xDestroy method
97615 ** of the virtual table named zTab in database iDb. This occurs
97616 ** when a DROP TABLE is mentioned.
97618 ** This call is a no-op if zTab is not a virtual table.
97620 SQLITE_PRIVATE int sqlite3VtabCallDestroy(sqlite3 *db, int iDb, const char *zTab){
97621 int rc = SQLITE_OK;
97622 Table *pTab;
97624 pTab = sqlite3FindTable(db, zTab, db->aDb[iDb].zName);
97625 if( ALWAYS(pTab!=0 && pTab->pVTable!=0) ){
97626 VTable *p = vtabDisconnectAll(db, pTab);
97628 assert( rc==SQLITE_OK );
97629 rc = p->pMod->pModule->xDestroy(p->pVtab);
97631 /* Remove the sqlite3_vtab* from the aVTrans[] array, if applicable */
97632 if( rc==SQLITE_OK ){
97633 assert( pTab->pVTable==p && p->pNext==0 );
97634 p->pVtab = 0;
97635 pTab->pVTable = 0;
97636 sqlite3VtabUnlock(p);
97640 return rc;
97644 ** This function invokes either the xRollback or xCommit method
97645 ** of each of the virtual tables in the sqlite3.aVTrans array. The method
97646 ** called is identified by the second argument, "offset", which is
97647 ** the offset of the method to call in the sqlite3_module structure.
97649 ** The array is cleared after invoking the callbacks.
97651 static void callFinaliser(sqlite3 *db, int offset){
97652 int i;
97653 if( db->aVTrans ){
97654 for(i=0; i<db->nVTrans; i++){
97655 VTable *pVTab = db->aVTrans[i];
97656 sqlite3_vtab *p = pVTab->pVtab;
97657 if( p ){
97658 int (*x)(sqlite3_vtab *);
97659 x = *(int (**)(sqlite3_vtab *))((char *)p->pModule + offset);
97660 if( x ) x(p);
97662 sqlite3VtabUnlock(pVTab);
97664 sqlite3DbFree(db, db->aVTrans);
97665 db->nVTrans = 0;
97666 db->aVTrans = 0;
97671 ** Invoke the xSync method of all virtual tables in the sqlite3.aVTrans
97672 ** array. Return the error code for the first error that occurs, or
97673 ** SQLITE_OK if all xSync operations are successful.
97675 ** Set *pzErrmsg to point to a buffer that should be released using
97676 ** sqlite3DbFree() containing an error message, if one is available.
97678 SQLITE_PRIVATE int sqlite3VtabSync(sqlite3 *db, char **pzErrmsg){
97679 int i;
97680 int rc = SQLITE_OK;
97681 VTable **aVTrans = db->aVTrans;
97683 db->aVTrans = 0;
97684 for(i=0; rc==SQLITE_OK && i<db->nVTrans; i++){
97685 int (*x)(sqlite3_vtab *);
97686 sqlite3_vtab *pVtab = aVTrans[i]->pVtab;
97687 if( pVtab && (x = pVtab->pModule->xSync)!=0 ){
97688 rc = x(pVtab);
97689 sqlite3DbFree(db, *pzErrmsg);
97690 *pzErrmsg = sqlite3DbStrDup(db, pVtab->zErrMsg);
97691 sqlite3_free(pVtab->zErrMsg);
97694 db->aVTrans = aVTrans;
97695 return rc;
97699 ** Invoke the xRollback method of all virtual tables in the
97700 ** sqlite3.aVTrans array. Then clear the array itself.
97702 SQLITE_PRIVATE int sqlite3VtabRollback(sqlite3 *db){
97703 callFinaliser(db, offsetof(sqlite3_module,xRollback));
97704 return SQLITE_OK;
97708 ** Invoke the xCommit method of all virtual tables in the
97709 ** sqlite3.aVTrans array. Then clear the array itself.
97711 SQLITE_PRIVATE int sqlite3VtabCommit(sqlite3 *db){
97712 callFinaliser(db, offsetof(sqlite3_module,xCommit));
97713 return SQLITE_OK;
97717 ** If the virtual table pVtab supports the transaction interface
97718 ** (xBegin/xRollback/xCommit and optionally xSync) and a transaction is
97719 ** not currently open, invoke the xBegin method now.
97721 ** If the xBegin call is successful, place the sqlite3_vtab pointer
97722 ** in the sqlite3.aVTrans array.
97724 SQLITE_PRIVATE int sqlite3VtabBegin(sqlite3 *db, VTable *pVTab){
97725 int rc = SQLITE_OK;
97726 const sqlite3_module *pModule;
97728 /* Special case: If db->aVTrans is NULL and db->nVTrans is greater
97729 ** than zero, then this function is being called from within a
97730 ** virtual module xSync() callback. It is illegal to write to
97731 ** virtual module tables in this case, so return SQLITE_LOCKED.
97733 if( sqlite3VtabInSync(db) ){
97734 return SQLITE_LOCKED;
97736 if( !pVTab ){
97737 return SQLITE_OK;
97739 pModule = pVTab->pVtab->pModule;
97741 if( pModule->xBegin ){
97742 int i;
97745 /* If pVtab is already in the aVTrans array, return early */
97746 for(i=0; i<db->nVTrans; i++){
97747 if( db->aVTrans[i]==pVTab ){
97748 return SQLITE_OK;
97752 /* Invoke the xBegin method */
97753 rc = pModule->xBegin(pVTab->pVtab);
97754 if( rc==SQLITE_OK ){
97755 rc = addToVTrans(db, pVTab);
97758 return rc;
97762 ** The first parameter (pDef) is a function implementation. The
97763 ** second parameter (pExpr) is the first argument to this function.
97764 ** If pExpr is a column in a virtual table, then let the virtual
97765 ** table implementation have an opportunity to overload the function.
97767 ** This routine is used to allow virtual table implementations to
97768 ** overload MATCH, LIKE, GLOB, and REGEXP operators.
97770 ** Return either the pDef argument (indicating no change) or a
97771 ** new FuncDef structure that is marked as ephemeral using the
97772 ** SQLITE_FUNC_EPHEM flag.
97774 SQLITE_PRIVATE FuncDef *sqlite3VtabOverloadFunction(
97775 sqlite3 *db, /* Database connection for reporting malloc problems */
97776 FuncDef *pDef, /* Function to possibly overload */
97777 int nArg, /* Number of arguments to the function */
97778 Expr *pExpr /* First argument to the function */
97780 Table *pTab;
97781 sqlite3_vtab *pVtab;
97782 sqlite3_module *pMod;
97783 void (*xFunc)(sqlite3_context*,int,sqlite3_value**) = 0;
97784 void *pArg = 0;
97785 FuncDef *pNew;
97786 int rc = 0;
97787 char *zLowerName;
97788 unsigned char *z;
97791 /* Check to see the left operand is a column in a virtual table */
97792 if( NEVER(pExpr==0) ) return pDef;
97793 if( pExpr->op!=TK_COLUMN ) return pDef;
97794 pTab = pExpr->pTab;
97795 if( NEVER(pTab==0) ) return pDef;
97796 if( (pTab->tabFlags & TF_Virtual)==0 ) return pDef;
97797 pVtab = sqlite3GetVTable(db, pTab)->pVtab;
97798 assert( pVtab!=0 );
97799 assert( pVtab->pModule!=0 );
97800 pMod = (sqlite3_module *)pVtab->pModule;
97801 if( pMod->xFindFunction==0 ) return pDef;
97803 /* Call the xFindFunction method on the virtual table implementation
97804 ** to see if the implementation wants to overload this function
97806 zLowerName = sqlite3DbStrDup(db, pDef->zName);
97807 if( zLowerName ){
97808 for(z=(unsigned char*)zLowerName; *z; z++){
97809 *z = sqlite3UpperToLower[*z];
97811 rc = pMod->xFindFunction(pVtab, nArg, zLowerName, &xFunc, &pArg);
97812 sqlite3DbFree(db, zLowerName);
97814 if( rc==0 ){
97815 return pDef;
97818 /* Create a new ephemeral function definition for the overloaded
97819 ** function */
97820 pNew = sqlite3DbMallocZero(db, sizeof(*pNew)
97821 + sqlite3Strlen30(pDef->zName) + 1);
97822 if( pNew==0 ){
97823 return pDef;
97825 *pNew = *pDef;
97826 pNew->zName = (char *)&pNew[1];
97827 memcpy(pNew->zName, pDef->zName, sqlite3Strlen30(pDef->zName)+1);
97828 pNew->xFunc = xFunc;
97829 pNew->pUserData = pArg;
97830 pNew->flags |= SQLITE_FUNC_EPHEM;
97831 return pNew;
97835 ** Make sure virtual table pTab is contained in the pParse->apVirtualLock[]
97836 ** array so that an OP_VBegin will get generated for it. Add pTab to the
97837 ** array if it is missing. If pTab is already in the array, this routine
97838 ** is a no-op.
97840 SQLITE_PRIVATE void sqlite3VtabMakeWritable(Parse *pParse, Table *pTab){
97841 Parse *pToplevel = sqlite3ParseToplevel(pParse);
97842 int i, n;
97843 Table **apVtabLock;
97845 assert( IsVirtual(pTab) );
97846 for(i=0; i<pToplevel->nVtabLock; i++){
97847 if( pTab==pToplevel->apVtabLock[i] ) return;
97849 n = (pToplevel->nVtabLock+1)*sizeof(pToplevel->apVtabLock[0]);
97850 apVtabLock = sqlite3_realloc(pToplevel->apVtabLock, n);
97851 if( apVtabLock ){
97852 pToplevel->apVtabLock = apVtabLock;
97853 pToplevel->apVtabLock[pToplevel->nVtabLock++] = pTab;
97854 }else{
97855 pToplevel->db->mallocFailed = 1;
97859 #endif /* SQLITE_OMIT_VIRTUALTABLE */
97861 /************** End of vtab.c ************************************************/
97862 /************** Begin file where.c *******************************************/
97864 ** 2001 September 15
97866 ** The author disclaims copyright to this source code. In place of
97867 ** a legal notice, here is a blessing:
97869 ** May you do good and not evil.
97870 ** May you find forgiveness for yourself and forgive others.
97871 ** May you share freely, never taking more than you give.
97873 *************************************************************************
97874 ** This module contains C code that generates VDBE code used to process
97875 ** the WHERE clause of SQL statements. This module is responsible for
97876 ** generating the code that loops through a table looking for applicable
97877 ** rows. Indices are selected and used to speed the search when doing
97878 ** so is applicable. Because this module is responsible for selecting
97879 ** indices, you might also think of this module as the "query optimizer".
97884 ** Trace output macros
97886 #if defined(SQLITE_TEST) || defined(SQLITE_DEBUG)
97887 SQLITE_PRIVATE int sqlite3WhereTrace = 0;
97888 #endif
97889 #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
97890 # define WHERETRACE(X) if(sqlite3WhereTrace) sqlite3DebugPrintf X
97891 #else
97892 # define WHERETRACE(X)
97893 #endif
97895 /* Forward reference
97897 typedef struct WhereClause WhereClause;
97898 typedef struct WhereMaskSet WhereMaskSet;
97899 typedef struct WhereOrInfo WhereOrInfo;
97900 typedef struct WhereAndInfo WhereAndInfo;
97901 typedef struct WhereCost WhereCost;
97904 ** The query generator uses an array of instances of this structure to
97905 ** help it analyze the subexpressions of the WHERE clause. Each WHERE
97906 ** clause subexpression is separated from the others by AND operators,
97907 ** usually, or sometimes subexpressions separated by OR.
97909 ** All WhereTerms are collected into a single WhereClause structure.
97910 ** The following identity holds:
97912 ** WhereTerm.pWC->a[WhereTerm.idx] == WhereTerm
97914 ** When a term is of the form:
97916 ** X <op> <expr>
97918 ** where X is a column name and <op> is one of certain operators,
97919 ** then WhereTerm.leftCursor and WhereTerm.u.leftColumn record the
97920 ** cursor number and column number for X. WhereTerm.eOperator records
97921 ** the <op> using a bitmask encoding defined by WO_xxx below. The
97922 ** use of a bitmask encoding for the operator allows us to search
97923 ** quickly for terms that match any of several different operators.
97925 ** A WhereTerm might also be two or more subterms connected by OR:
97927 ** (t1.X <op> <expr>) OR (t1.Y <op> <expr>) OR ....
97929 ** In this second case, wtFlag as the TERM_ORINFO set and eOperator==WO_OR
97930 ** and the WhereTerm.u.pOrInfo field points to auxiliary information that
97931 ** is collected about the
97933 ** If a term in the WHERE clause does not match either of the two previous
97934 ** categories, then eOperator==0. The WhereTerm.pExpr field is still set
97935 ** to the original subexpression content and wtFlags is set up appropriately
97936 ** but no other fields in the WhereTerm object are meaningful.
97938 ** When eOperator!=0, prereqRight and prereqAll record sets of cursor numbers,
97939 ** but they do so indirectly. A single WhereMaskSet structure translates
97940 ** cursor number into bits and the translated bit is stored in the prereq
97941 ** fields. The translation is used in order to maximize the number of
97942 ** bits that will fit in a Bitmask. The VDBE cursor numbers might be
97943 ** spread out over the non-negative integers. For example, the cursor
97944 ** numbers might be 3, 8, 9, 10, 20, 23, 41, and 45. The WhereMaskSet
97945 ** translates these sparse cursor numbers into consecutive integers
97946 ** beginning with 0 in order to make the best possible use of the available
97947 ** bits in the Bitmask. So, in the example above, the cursor numbers
97948 ** would be mapped into integers 0 through 7.
97950 ** The number of terms in a join is limited by the number of bits
97951 ** in prereqRight and prereqAll. The default is 64 bits, hence SQLite
97952 ** is only able to process joins with 64 or fewer tables.
97954 typedef struct WhereTerm WhereTerm;
97955 struct WhereTerm {
97956 Expr *pExpr; /* Pointer to the subexpression that is this term */
97957 int iParent; /* Disable pWC->a[iParent] when this term disabled */
97958 int leftCursor; /* Cursor number of X in "X <op> <expr>" */
97959 union {
97960 int leftColumn; /* Column number of X in "X <op> <expr>" */
97961 WhereOrInfo *pOrInfo; /* Extra information if eOperator==WO_OR */
97962 WhereAndInfo *pAndInfo; /* Extra information if eOperator==WO_AND */
97963 } u;
97964 u16 eOperator; /* A WO_xx value describing <op> */
97965 u8 wtFlags; /* TERM_xxx bit flags. See below */
97966 u8 nChild; /* Number of children that must disable us */
97967 WhereClause *pWC; /* The clause this term is part of */
97968 Bitmask prereqRight; /* Bitmask of tables used by pExpr->pRight */
97969 Bitmask prereqAll; /* Bitmask of tables referenced by pExpr */
97973 ** Allowed values of WhereTerm.wtFlags
97975 #define TERM_DYNAMIC 0x01 /* Need to call sqlite3ExprDelete(db, pExpr) */
97976 #define TERM_VIRTUAL 0x02 /* Added by the optimizer. Do not code */
97977 #define TERM_CODED 0x04 /* This term is already coded */
97978 #define TERM_COPIED 0x08 /* Has a child */
97979 #define TERM_ORINFO 0x10 /* Need to free the WhereTerm.u.pOrInfo object */
97980 #define TERM_ANDINFO 0x20 /* Need to free the WhereTerm.u.pAndInfo obj */
97981 #define TERM_OR_OK 0x40 /* Used during OR-clause processing */
97982 #ifdef SQLITE_ENABLE_STAT2
97983 # define TERM_VNULL 0x80 /* Manufactured x>NULL or x<=NULL term */
97984 #else
97985 # define TERM_VNULL 0x00 /* Disabled if not using stat2 */
97986 #endif
97989 ** An instance of the following structure holds all information about a
97990 ** WHERE clause. Mostly this is a container for one or more WhereTerms.
97992 struct WhereClause {
97993 Parse *pParse; /* The parser context */
97994 WhereMaskSet *pMaskSet; /* Mapping of table cursor numbers to bitmasks */
97995 Bitmask vmask; /* Bitmask identifying virtual table cursors */
97996 u8 op; /* Split operator. TK_AND or TK_OR */
97997 int nTerm; /* Number of terms */
97998 int nSlot; /* Number of entries in a[] */
97999 WhereTerm *a; /* Each a[] describes a term of the WHERE cluase */
98000 #if defined(SQLITE_SMALL_STACK)
98001 WhereTerm aStatic[1]; /* Initial static space for a[] */
98002 #else
98003 WhereTerm aStatic[8]; /* Initial static space for a[] */
98004 #endif
98008 ** A WhereTerm with eOperator==WO_OR has its u.pOrInfo pointer set to
98009 ** a dynamically allocated instance of the following structure.
98011 struct WhereOrInfo {
98012 WhereClause wc; /* Decomposition into subterms */
98013 Bitmask indexable; /* Bitmask of all indexable tables in the clause */
98017 ** A WhereTerm with eOperator==WO_AND has its u.pAndInfo pointer set to
98018 ** a dynamically allocated instance of the following structure.
98020 struct WhereAndInfo {
98021 WhereClause wc; /* The subexpression broken out */
98025 ** An instance of the following structure keeps track of a mapping
98026 ** between VDBE cursor numbers and bits of the bitmasks in WhereTerm.
98028 ** The VDBE cursor numbers are small integers contained in
98029 ** SrcList_item.iCursor and Expr.iTable fields. For any given WHERE
98030 ** clause, the cursor numbers might not begin with 0 and they might
98031 ** contain gaps in the numbering sequence. But we want to make maximum
98032 ** use of the bits in our bitmasks. This structure provides a mapping
98033 ** from the sparse cursor numbers into consecutive integers beginning
98034 ** with 0.
98036 ** If WhereMaskSet.ix[A]==B it means that The A-th bit of a Bitmask
98037 ** corresponds VDBE cursor number B. The A-th bit of a bitmask is 1<<A.
98039 ** For example, if the WHERE clause expression used these VDBE
98040 ** cursors: 4, 5, 8, 29, 57, 73. Then the WhereMaskSet structure
98041 ** would map those cursor numbers into bits 0 through 5.
98043 ** Note that the mapping is not necessarily ordered. In the example
98044 ** above, the mapping might go like this: 4->3, 5->1, 8->2, 29->0,
98045 ** 57->5, 73->4. Or one of 719 other combinations might be used. It
98046 ** does not really matter. What is important is that sparse cursor
98047 ** numbers all get mapped into bit numbers that begin with 0 and contain
98048 ** no gaps.
98050 struct WhereMaskSet {
98051 int n; /* Number of assigned cursor values */
98052 int ix[BMS]; /* Cursor assigned to each bit */
98056 ** A WhereCost object records a lookup strategy and the estimated
98057 ** cost of pursuing that strategy.
98059 struct WhereCost {
98060 WherePlan plan; /* The lookup strategy */
98061 double rCost; /* Overall cost of pursuing this search strategy */
98062 Bitmask used; /* Bitmask of cursors used by this plan */
98066 ** Bitmasks for the operators that indices are able to exploit. An
98067 ** OR-ed combination of these values can be used when searching for
98068 ** terms in the where clause.
98070 #define WO_IN 0x001
98071 #define WO_EQ 0x002
98072 #define WO_LT (WO_EQ<<(TK_LT-TK_EQ))
98073 #define WO_LE (WO_EQ<<(TK_LE-TK_EQ))
98074 #define WO_GT (WO_EQ<<(TK_GT-TK_EQ))
98075 #define WO_GE (WO_EQ<<(TK_GE-TK_EQ))
98076 #define WO_MATCH 0x040
98077 #define WO_ISNULL 0x080
98078 #define WO_OR 0x100 /* Two or more OR-connected terms */
98079 #define WO_AND 0x200 /* Two or more AND-connected terms */
98080 #define WO_NOOP 0x800 /* This term does not restrict search space */
98082 #define WO_ALL 0xfff /* Mask of all possible WO_* values */
98083 #define WO_SINGLE 0x0ff /* Mask of all non-compound WO_* values */
98086 ** Value for wsFlags returned by bestIndex() and stored in
98087 ** WhereLevel.wsFlags. These flags determine which search
98088 ** strategies are appropriate.
98090 ** The least significant 12 bits is reserved as a mask for WO_ values above.
98091 ** The WhereLevel.wsFlags field is usually set to WO_IN|WO_EQ|WO_ISNULL.
98092 ** But if the table is the right table of a left join, WhereLevel.wsFlags
98093 ** is set to WO_IN|WO_EQ. The WhereLevel.wsFlags field can then be used as
98094 ** the "op" parameter to findTerm when we are resolving equality constraints.
98095 ** ISNULL constraints will then not be used on the right table of a left
98096 ** join. Tickets #2177 and #2189.
98098 #define WHERE_ROWID_EQ 0x00001000 /* rowid=EXPR or rowid IN (...) */
98099 #define WHERE_ROWID_RANGE 0x00002000 /* rowid<EXPR and/or rowid>EXPR */
98100 #define WHERE_COLUMN_EQ 0x00010000 /* x=EXPR or x IN (...) or x IS NULL */
98101 #define WHERE_COLUMN_RANGE 0x00020000 /* x<EXPR and/or x>EXPR */
98102 #define WHERE_COLUMN_IN 0x00040000 /* x IN (...) */
98103 #define WHERE_COLUMN_NULL 0x00080000 /* x IS NULL */
98104 #define WHERE_INDEXED 0x000f0000 /* Anything that uses an index */
98105 #define WHERE_NOT_FULLSCAN 0x100f3000 /* Does not do a full table scan */
98106 #define WHERE_IN_ABLE 0x000f1000 /* Able to support an IN operator */
98107 #define WHERE_TOP_LIMIT 0x00100000 /* x<EXPR or x<=EXPR constraint */
98108 #define WHERE_BTM_LIMIT 0x00200000 /* x>EXPR or x>=EXPR constraint */
98109 #define WHERE_BOTH_LIMIT 0x00300000 /* Both x>EXPR and x<EXPR */
98110 #define WHERE_IDX_ONLY 0x00800000 /* Use index only - omit table */
98111 #define WHERE_ORDERBY 0x01000000 /* Output will appear in correct order */
98112 #define WHERE_REVERSE 0x02000000 /* Scan in reverse order */
98113 #define WHERE_UNIQUE 0x04000000 /* Selects no more than one row */
98114 #define WHERE_VIRTUALTABLE 0x08000000 /* Use virtual-table processing */
98115 #define WHERE_MULTI_OR 0x10000000 /* OR using multiple indices */
98116 #define WHERE_TEMP_INDEX 0x20000000 /* Uses an ephemeral index */
98119 ** Initialize a preallocated WhereClause structure.
98121 static void whereClauseInit(
98122 WhereClause *pWC, /* The WhereClause to be initialized */
98123 Parse *pParse, /* The parsing context */
98124 WhereMaskSet *pMaskSet /* Mapping from table cursor numbers to bitmasks */
98126 pWC->pParse = pParse;
98127 pWC->pMaskSet = pMaskSet;
98128 pWC->nTerm = 0;
98129 pWC->nSlot = ArraySize(pWC->aStatic);
98130 pWC->a = pWC->aStatic;
98131 pWC->vmask = 0;
98134 /* Forward reference */
98135 static void whereClauseClear(WhereClause*);
98138 ** Deallocate all memory associated with a WhereOrInfo object.
98140 static void whereOrInfoDelete(sqlite3 *db, WhereOrInfo *p){
98141 whereClauseClear(&p->wc);
98142 sqlite3DbFree(db, p);
98146 ** Deallocate all memory associated with a WhereAndInfo object.
98148 static void whereAndInfoDelete(sqlite3 *db, WhereAndInfo *p){
98149 whereClauseClear(&p->wc);
98150 sqlite3DbFree(db, p);
98154 ** Deallocate a WhereClause structure. The WhereClause structure
98155 ** itself is not freed. This routine is the inverse of whereClauseInit().
98157 static void whereClauseClear(WhereClause *pWC){
98158 int i;
98159 WhereTerm *a;
98160 sqlite3 *db = pWC->pParse->db;
98161 for(i=pWC->nTerm-1, a=pWC->a; i>=0; i--, a++){
98162 if( a->wtFlags & TERM_DYNAMIC ){
98163 sqlite3ExprDelete(db, a->pExpr);
98165 if( a->wtFlags & TERM_ORINFO ){
98166 whereOrInfoDelete(db, a->u.pOrInfo);
98167 }else if( a->wtFlags & TERM_ANDINFO ){
98168 whereAndInfoDelete(db, a->u.pAndInfo);
98171 if( pWC->a!=pWC->aStatic ){
98172 sqlite3DbFree(db, pWC->a);
98177 ** Add a single new WhereTerm entry to the WhereClause object pWC.
98178 ** The new WhereTerm object is constructed from Expr p and with wtFlags.
98179 ** The index in pWC->a[] of the new WhereTerm is returned on success.
98180 ** 0 is returned if the new WhereTerm could not be added due to a memory
98181 ** allocation error. The memory allocation failure will be recorded in
98182 ** the db->mallocFailed flag so that higher-level functions can detect it.
98184 ** This routine will increase the size of the pWC->a[] array as necessary.
98186 ** If the wtFlags argument includes TERM_DYNAMIC, then responsibility
98187 ** for freeing the expression p is assumed by the WhereClause object pWC.
98188 ** This is true even if this routine fails to allocate a new WhereTerm.
98190 ** WARNING: This routine might reallocate the space used to store
98191 ** WhereTerms. All pointers to WhereTerms should be invalidated after
98192 ** calling this routine. Such pointers may be reinitialized by referencing
98193 ** the pWC->a[] array.
98195 static int whereClauseInsert(WhereClause *pWC, Expr *p, u8 wtFlags){
98196 WhereTerm *pTerm;
98197 int idx;
98198 testcase( wtFlags & TERM_VIRTUAL ); /* EV: R-00211-15100 */
98199 if( pWC->nTerm>=pWC->nSlot ){
98200 WhereTerm *pOld = pWC->a;
98201 sqlite3 *db = pWC->pParse->db;
98202 pWC->a = sqlite3DbMallocRaw(db, sizeof(pWC->a[0])*pWC->nSlot*2 );
98203 if( pWC->a==0 ){
98204 if( wtFlags & TERM_DYNAMIC ){
98205 sqlite3ExprDelete(db, p);
98207 pWC->a = pOld;
98208 return 0;
98210 memcpy(pWC->a, pOld, sizeof(pWC->a[0])*pWC->nTerm);
98211 if( pOld!=pWC->aStatic ){
98212 sqlite3DbFree(db, pOld);
98214 pWC->nSlot = sqlite3DbMallocSize(db, pWC->a)/sizeof(pWC->a[0]);
98216 pTerm = &pWC->a[idx = pWC->nTerm++];
98217 pTerm->pExpr = p;
98218 pTerm->wtFlags = wtFlags;
98219 pTerm->pWC = pWC;
98220 pTerm->iParent = -1;
98221 return idx;
98225 ** This routine identifies subexpressions in the WHERE clause where
98226 ** each subexpression is separated by the AND operator or some other
98227 ** operator specified in the op parameter. The WhereClause structure
98228 ** is filled with pointers to subexpressions. For example:
98230 ** WHERE a=='hello' AND coalesce(b,11)<10 AND (c+12!=d OR c==22)
98231 ** \________/ \_______________/ \________________/
98232 ** slot[0] slot[1] slot[2]
98234 ** The original WHERE clause in pExpr is unaltered. All this routine
98235 ** does is make slot[] entries point to substructure within pExpr.
98237 ** In the previous sentence and in the diagram, "slot[]" refers to
98238 ** the WhereClause.a[] array. The slot[] array grows as needed to contain
98239 ** all terms of the WHERE clause.
98241 static void whereSplit(WhereClause *pWC, Expr *pExpr, int op){
98242 pWC->op = (u8)op;
98243 if( pExpr==0 ) return;
98244 if( pExpr->op!=op ){
98245 whereClauseInsert(pWC, pExpr, 0);
98246 }else{
98247 whereSplit(pWC, pExpr->pLeft, op);
98248 whereSplit(pWC, pExpr->pRight, op);
98253 ** Initialize an expression mask set (a WhereMaskSet object)
98255 #define initMaskSet(P) memset(P, 0, sizeof(*P))
98258 ** Return the bitmask for the given cursor number. Return 0 if
98259 ** iCursor is not in the set.
98261 static Bitmask getMask(WhereMaskSet *pMaskSet, int iCursor){
98262 int i;
98263 assert( pMaskSet->n<=(int)sizeof(Bitmask)*8 );
98264 for(i=0; i<pMaskSet->n; i++){
98265 if( pMaskSet->ix[i]==iCursor ){
98266 return ((Bitmask)1)<<i;
98269 return 0;
98273 ** Create a new mask for cursor iCursor.
98275 ** There is one cursor per table in the FROM clause. The number of
98276 ** tables in the FROM clause is limited by a test early in the
98277 ** sqlite3WhereBegin() routine. So we know that the pMaskSet->ix[]
98278 ** array will never overflow.
98280 static void createMask(WhereMaskSet *pMaskSet, int iCursor){
98281 assert( pMaskSet->n < ArraySize(pMaskSet->ix) );
98282 pMaskSet->ix[pMaskSet->n++] = iCursor;
98286 ** This routine walks (recursively) an expression tree and generates
98287 ** a bitmask indicating which tables are used in that expression
98288 ** tree.
98290 ** In order for this routine to work, the calling function must have
98291 ** previously invoked sqlite3ResolveExprNames() on the expression. See
98292 ** the header comment on that routine for additional information.
98293 ** The sqlite3ResolveExprNames() routines looks for column names and
98294 ** sets their opcodes to TK_COLUMN and their Expr.iTable fields to
98295 ** the VDBE cursor number of the table. This routine just has to
98296 ** translate the cursor numbers into bitmask values and OR all
98297 ** the bitmasks together.
98299 static Bitmask exprListTableUsage(WhereMaskSet*, ExprList*);
98300 static Bitmask exprSelectTableUsage(WhereMaskSet*, Select*);
98301 static Bitmask exprTableUsage(WhereMaskSet *pMaskSet, Expr *p){
98302 Bitmask mask = 0;
98303 if( p==0 ) return 0;
98304 if( p->op==TK_COLUMN ){
98305 mask = getMask(pMaskSet, p->iTable);
98306 return mask;
98308 mask = exprTableUsage(pMaskSet, p->pRight);
98309 mask |= exprTableUsage(pMaskSet, p->pLeft);
98310 if( ExprHasProperty(p, EP_xIsSelect) ){
98311 mask |= exprSelectTableUsage(pMaskSet, p->x.pSelect);
98312 }else{
98313 mask |= exprListTableUsage(pMaskSet, p->x.pList);
98315 return mask;
98317 static Bitmask exprListTableUsage(WhereMaskSet *pMaskSet, ExprList *pList){
98318 int i;
98319 Bitmask mask = 0;
98320 if( pList ){
98321 for(i=0; i<pList->nExpr; i++){
98322 mask |= exprTableUsage(pMaskSet, pList->a[i].pExpr);
98325 return mask;
98327 static Bitmask exprSelectTableUsage(WhereMaskSet *pMaskSet, Select *pS){
98328 Bitmask mask = 0;
98329 while( pS ){
98330 mask |= exprListTableUsage(pMaskSet, pS->pEList);
98331 mask |= exprListTableUsage(pMaskSet, pS->pGroupBy);
98332 mask |= exprListTableUsage(pMaskSet, pS->pOrderBy);
98333 mask |= exprTableUsage(pMaskSet, pS->pWhere);
98334 mask |= exprTableUsage(pMaskSet, pS->pHaving);
98335 pS = pS->pPrior;
98337 return mask;
98341 ** Return TRUE if the given operator is one of the operators that is
98342 ** allowed for an indexable WHERE clause term. The allowed operators are
98343 ** "=", "<", ">", "<=", ">=", and "IN".
98345 ** IMPLEMENTATION-OF: R-59926-26393 To be usable by an index a term must be
98346 ** of one of the following forms: column = expression column > expression
98347 ** column >= expression column < expression column <= expression
98348 ** expression = column expression > column expression >= column
98349 ** expression < column expression <= column column IN
98350 ** (expression-list) column IN (subquery) column IS NULL
98352 static int allowedOp(int op){
98353 assert( TK_GT>TK_EQ && TK_GT<TK_GE );
98354 assert( TK_LT>TK_EQ && TK_LT<TK_GE );
98355 assert( TK_LE>TK_EQ && TK_LE<TK_GE );
98356 assert( TK_GE==TK_EQ+4 );
98357 return op==TK_IN || (op>=TK_EQ && op<=TK_GE) || op==TK_ISNULL;
98361 ** Swap two objects of type TYPE.
98363 #define SWAP(TYPE,A,B) {TYPE t=A; A=B; B=t;}
98366 ** Commute a comparison operator. Expressions of the form "X op Y"
98367 ** are converted into "Y op X".
98369 ** If a collation sequence is associated with either the left or right
98370 ** side of the comparison, it remains associated with the same side after
98371 ** the commutation. So "Y collate NOCASE op X" becomes
98372 ** "X collate NOCASE op Y". This is because any collation sequence on
98373 ** the left hand side of a comparison overrides any collation sequence
98374 ** attached to the right. For the same reason the EP_ExpCollate flag
98375 ** is not commuted.
98377 static void exprCommute(Parse *pParse, Expr *pExpr){
98378 u16 expRight = (pExpr->pRight->flags & EP_ExpCollate);
98379 u16 expLeft = (pExpr->pLeft->flags & EP_ExpCollate);
98380 assert( allowedOp(pExpr->op) && pExpr->op!=TK_IN );
98381 pExpr->pRight->pColl = sqlite3ExprCollSeq(pParse, pExpr->pRight);
98382 pExpr->pLeft->pColl = sqlite3ExprCollSeq(pParse, pExpr->pLeft);
98383 SWAP(CollSeq*,pExpr->pRight->pColl,pExpr->pLeft->pColl);
98384 pExpr->pRight->flags = (pExpr->pRight->flags & ~EP_ExpCollate) | expLeft;
98385 pExpr->pLeft->flags = (pExpr->pLeft->flags & ~EP_ExpCollate) | expRight;
98386 SWAP(Expr*,pExpr->pRight,pExpr->pLeft);
98387 if( pExpr->op>=TK_GT ){
98388 assert( TK_LT==TK_GT+2 );
98389 assert( TK_GE==TK_LE+2 );
98390 assert( TK_GT>TK_EQ );
98391 assert( TK_GT<TK_LE );
98392 assert( pExpr->op>=TK_GT && pExpr->op<=TK_GE );
98393 pExpr->op = ((pExpr->op-TK_GT)^2)+TK_GT;
98398 ** Translate from TK_xx operator to WO_xx bitmask.
98400 static u16 operatorMask(int op){
98401 u16 c;
98402 assert( allowedOp(op) );
98403 if( op==TK_IN ){
98404 c = WO_IN;
98405 }else if( op==TK_ISNULL ){
98406 c = WO_ISNULL;
98407 }else{
98408 assert( (WO_EQ<<(op-TK_EQ)) < 0x7fff );
98409 c = (u16)(WO_EQ<<(op-TK_EQ));
98411 assert( op!=TK_ISNULL || c==WO_ISNULL );
98412 assert( op!=TK_IN || c==WO_IN );
98413 assert( op!=TK_EQ || c==WO_EQ );
98414 assert( op!=TK_LT || c==WO_LT );
98415 assert( op!=TK_LE || c==WO_LE );
98416 assert( op!=TK_GT || c==WO_GT );
98417 assert( op!=TK_GE || c==WO_GE );
98418 return c;
98422 ** Search for a term in the WHERE clause that is of the form "X <op> <expr>"
98423 ** where X is a reference to the iColumn of table iCur and <op> is one of
98424 ** the WO_xx operator codes specified by the op parameter.
98425 ** Return a pointer to the term. Return 0 if not found.
98427 static WhereTerm *findTerm(
98428 WhereClause *pWC, /* The WHERE clause to be searched */
98429 int iCur, /* Cursor number of LHS */
98430 int iColumn, /* Column number of LHS */
98431 Bitmask notReady, /* RHS must not overlap with this mask */
98432 u32 op, /* Mask of WO_xx values describing operator */
98433 Index *pIdx /* Must be compatible with this index, if not NULL */
98435 WhereTerm *pTerm;
98436 int k;
98437 assert( iCur>=0 );
98438 op &= WO_ALL;
98439 for(pTerm=pWC->a, k=pWC->nTerm; k; k--, pTerm++){
98440 if( pTerm->leftCursor==iCur
98441 && (pTerm->prereqRight & notReady)==0
98442 && pTerm->u.leftColumn==iColumn
98443 && (pTerm->eOperator & op)!=0
98445 if( pIdx && pTerm->eOperator!=WO_ISNULL ){
98446 Expr *pX = pTerm->pExpr;
98447 CollSeq *pColl;
98448 char idxaff;
98449 int j;
98450 Parse *pParse = pWC->pParse;
98452 idxaff = pIdx->pTable->aCol[iColumn].affinity;
98453 if( !sqlite3IndexAffinityOk(pX, idxaff) ) continue;
98455 /* Figure out the collation sequence required from an index for
98456 ** it to be useful for optimising expression pX. Store this
98457 ** value in variable pColl.
98459 assert(pX->pLeft);
98460 pColl = sqlite3BinaryCompareCollSeq(pParse, pX->pLeft, pX->pRight);
98461 assert(pColl || pParse->nErr);
98463 for(j=0; pIdx->aiColumn[j]!=iColumn; j++){
98464 if( NEVER(j>=pIdx->nColumn) ) return 0;
98466 if( pColl && sqlite3StrICmp(pColl->zName, pIdx->azColl[j]) ) continue;
98468 return pTerm;
98471 return 0;
98474 /* Forward reference */
98475 static void exprAnalyze(SrcList*, WhereClause*, int);
98478 ** Call exprAnalyze on all terms in a WHERE clause.
98482 static void exprAnalyzeAll(
98483 SrcList *pTabList, /* the FROM clause */
98484 WhereClause *pWC /* the WHERE clause to be analyzed */
98486 int i;
98487 for(i=pWC->nTerm-1; i>=0; i--){
98488 exprAnalyze(pTabList, pWC, i);
98492 #ifndef SQLITE_OMIT_LIKE_OPTIMIZATION
98494 ** Check to see if the given expression is a LIKE or GLOB operator that
98495 ** can be optimized using inequality constraints. Return TRUE if it is
98496 ** so and false if not.
98498 ** In order for the operator to be optimizible, the RHS must be a string
98499 ** literal that does not begin with a wildcard.
98501 static int isLikeOrGlob(
98502 Parse *pParse, /* Parsing and code generating context */
98503 Expr *pExpr, /* Test this expression */
98504 Expr **ppPrefix, /* Pointer to TK_STRING expression with pattern prefix */
98505 int *pisComplete, /* True if the only wildcard is % in the last character */
98506 int *pnoCase /* True if uppercase is equivalent to lowercase */
98508 const char *z = 0; /* String on RHS of LIKE operator */
98509 Expr *pRight, *pLeft; /* Right and left size of LIKE operator */
98510 ExprList *pList; /* List of operands to the LIKE operator */
98511 int c; /* One character in z[] */
98512 int cnt; /* Number of non-wildcard prefix characters */
98513 char wc[3]; /* Wildcard characters */
98514 sqlite3 *db = pParse->db; /* Database connection */
98515 sqlite3_value *pVal = 0;
98516 int op; /* Opcode of pRight */
98518 if( !sqlite3IsLikeFunction(db, pExpr, pnoCase, wc) ){
98519 return 0;
98521 #ifdef SQLITE_EBCDIC
98522 if( *pnoCase ) return 0;
98523 #endif
98524 pList = pExpr->x.pList;
98525 pLeft = pList->a[1].pExpr;
98526 if( pLeft->op!=TK_COLUMN || sqlite3ExprAffinity(pLeft)!=SQLITE_AFF_TEXT ){
98527 /* IMP: R-02065-49465 The left-hand side of the LIKE or GLOB operator must
98528 ** be the name of an indexed column with TEXT affinity. */
98529 return 0;
98531 assert( pLeft->iColumn!=(-1) ); /* Because IPK never has AFF_TEXT */
98533 pRight = pList->a[0].pExpr;
98534 op = pRight->op;
98535 if( op==TK_REGISTER ){
98536 op = pRight->op2;
98538 if( op==TK_VARIABLE ){
98539 Vdbe *pReprepare = pParse->pReprepare;
98540 int iCol = pRight->iColumn;
98541 pVal = sqlite3VdbeGetValue(pReprepare, iCol, SQLITE_AFF_NONE);
98542 if( pVal && sqlite3_value_type(pVal)==SQLITE_TEXT ){
98543 z = (char *)sqlite3_value_text(pVal);
98545 sqlite3VdbeSetVarmask(pParse->pVdbe, iCol); /* IMP: R-23257-02778 */
98546 assert( pRight->op==TK_VARIABLE || pRight->op==TK_REGISTER );
98547 }else if( op==TK_STRING ){
98548 z = pRight->u.zToken;
98550 if( z ){
98551 cnt = 0;
98552 while( (c=z[cnt])!=0 && c!=wc[0] && c!=wc[1] && c!=wc[2] ){
98553 cnt++;
98555 if( cnt!=0 && 255!=(u8)z[cnt-1] ){
98556 Expr *pPrefix;
98557 *pisComplete = c==wc[0] && z[cnt+1]==0;
98558 pPrefix = sqlite3Expr(db, TK_STRING, z);
98559 if( pPrefix ) pPrefix->u.zToken[cnt] = 0;
98560 *ppPrefix = pPrefix;
98561 if( op==TK_VARIABLE ){
98562 Vdbe *v = pParse->pVdbe;
98563 sqlite3VdbeSetVarmask(v, pRight->iColumn); /* IMP: R-23257-02778 */
98564 if( *pisComplete && pRight->u.zToken[1] ){
98565 /* If the rhs of the LIKE expression is a variable, and the current
98566 ** value of the variable means there is no need to invoke the LIKE
98567 ** function, then no OP_Variable will be added to the program.
98568 ** This causes problems for the sqlite3_bind_parameter_name()
98569 ** API. To workaround them, add a dummy OP_Variable here.
98571 int r1 = sqlite3GetTempReg(pParse);
98572 sqlite3ExprCodeTarget(pParse, pRight, r1);
98573 sqlite3VdbeChangeP3(v, sqlite3VdbeCurrentAddr(v)-1, 0);
98574 sqlite3ReleaseTempReg(pParse, r1);
98577 }else{
98578 z = 0;
98582 sqlite3ValueFree(pVal);
98583 return (z!=0);
98585 #endif /* SQLITE_OMIT_LIKE_OPTIMIZATION */
98588 #ifndef SQLITE_OMIT_VIRTUALTABLE
98590 ** Check to see if the given expression is of the form
98592 ** column MATCH expr
98594 ** If it is then return TRUE. If not, return FALSE.
98596 static int isMatchOfColumn(
98597 Expr *pExpr /* Test this expression */
98599 ExprList *pList;
98601 if( pExpr->op!=TK_FUNCTION ){
98602 return 0;
98604 if( sqlite3StrICmp(pExpr->u.zToken,"match")!=0 ){
98605 return 0;
98607 pList = pExpr->x.pList;
98608 if( pList->nExpr!=2 ){
98609 return 0;
98611 if( pList->a[1].pExpr->op != TK_COLUMN ){
98612 return 0;
98614 return 1;
98616 #endif /* SQLITE_OMIT_VIRTUALTABLE */
98619 ** If the pBase expression originated in the ON or USING clause of
98620 ** a join, then transfer the appropriate markings over to derived.
98622 static void transferJoinMarkings(Expr *pDerived, Expr *pBase){
98623 pDerived->flags |= pBase->flags & EP_FromJoin;
98624 pDerived->iRightJoinTable = pBase->iRightJoinTable;
98627 #if !defined(SQLITE_OMIT_OR_OPTIMIZATION) && !defined(SQLITE_OMIT_SUBQUERY)
98629 ** Analyze a term that consists of two or more OR-connected
98630 ** subterms. So in:
98632 ** ... WHERE (a=5) AND (b=7 OR c=9 OR d=13) AND (d=13)
98633 ** ^^^^^^^^^^^^^^^^^^^^
98635 ** This routine analyzes terms such as the middle term in the above example.
98636 ** A WhereOrTerm object is computed and attached to the term under
98637 ** analysis, regardless of the outcome of the analysis. Hence:
98639 ** WhereTerm.wtFlags |= TERM_ORINFO
98640 ** WhereTerm.u.pOrInfo = a dynamically allocated WhereOrTerm object
98642 ** The term being analyzed must have two or more of OR-connected subterms.
98643 ** A single subterm might be a set of AND-connected sub-subterms.
98644 ** Examples of terms under analysis:
98646 ** (A) t1.x=t2.y OR t1.x=t2.z OR t1.y=15 OR t1.z=t3.a+5
98647 ** (B) x=expr1 OR expr2=x OR x=expr3
98648 ** (C) t1.x=t2.y OR (t1.x=t2.z AND t1.y=15)
98649 ** (D) x=expr1 OR (y>11 AND y<22 AND z LIKE '*hello*')
98650 ** (E) (p.a=1 AND q.b=2 AND r.c=3) OR (p.x=4 AND q.y=5 AND r.z=6)
98652 ** CASE 1:
98654 ** If all subterms are of the form T.C=expr for some single column of C
98655 ** a single table T (as shown in example B above) then create a new virtual
98656 ** term that is an equivalent IN expression. In other words, if the term
98657 ** being analyzed is:
98659 ** x = expr1 OR expr2 = x OR x = expr3
98661 ** then create a new virtual term like this:
98663 ** x IN (expr1,expr2,expr3)
98665 ** CASE 2:
98667 ** If all subterms are indexable by a single table T, then set
98669 ** WhereTerm.eOperator = WO_OR
98670 ** WhereTerm.u.pOrInfo->indexable |= the cursor number for table T
98672 ** A subterm is "indexable" if it is of the form
98673 ** "T.C <op> <expr>" where C is any column of table T and
98674 ** <op> is one of "=", "<", "<=", ">", ">=", "IS NULL", or "IN".
98675 ** A subterm is also indexable if it is an AND of two or more
98676 ** subsubterms at least one of which is indexable. Indexable AND
98677 ** subterms have their eOperator set to WO_AND and they have
98678 ** u.pAndInfo set to a dynamically allocated WhereAndTerm object.
98680 ** From another point of view, "indexable" means that the subterm could
98681 ** potentially be used with an index if an appropriate index exists.
98682 ** This analysis does not consider whether or not the index exists; that
98683 ** is something the bestIndex() routine will determine. This analysis
98684 ** only looks at whether subterms appropriate for indexing exist.
98686 ** All examples A through E above all satisfy case 2. But if a term
98687 ** also statisfies case 1 (such as B) we know that the optimizer will
98688 ** always prefer case 1, so in that case we pretend that case 2 is not
98689 ** satisfied.
98691 ** It might be the case that multiple tables are indexable. For example,
98692 ** (E) above is indexable on tables P, Q, and R.
98694 ** Terms that satisfy case 2 are candidates for lookup by using
98695 ** separate indices to find rowids for each subterm and composing
98696 ** the union of all rowids using a RowSet object. This is similar
98697 ** to "bitmap indices" in other database engines.
98699 ** OTHERWISE:
98701 ** If neither case 1 nor case 2 apply, then leave the eOperator set to
98702 ** zero. This term is not useful for search.
98704 static void exprAnalyzeOrTerm(
98705 SrcList *pSrc, /* the FROM clause */
98706 WhereClause *pWC, /* the complete WHERE clause */
98707 int idxTerm /* Index of the OR-term to be analyzed */
98709 Parse *pParse = pWC->pParse; /* Parser context */
98710 sqlite3 *db = pParse->db; /* Database connection */
98711 WhereTerm *pTerm = &pWC->a[idxTerm]; /* The term to be analyzed */
98712 Expr *pExpr = pTerm->pExpr; /* The expression of the term */
98713 WhereMaskSet *pMaskSet = pWC->pMaskSet; /* Table use masks */
98714 int i; /* Loop counters */
98715 WhereClause *pOrWc; /* Breakup of pTerm into subterms */
98716 WhereTerm *pOrTerm; /* A Sub-term within the pOrWc */
98717 WhereOrInfo *pOrInfo; /* Additional information associated with pTerm */
98718 Bitmask chngToIN; /* Tables that might satisfy case 1 */
98719 Bitmask indexable; /* Tables that are indexable, satisfying case 2 */
98722 ** Break the OR clause into its separate subterms. The subterms are
98723 ** stored in a WhereClause structure containing within the WhereOrInfo
98724 ** object that is attached to the original OR clause term.
98726 assert( (pTerm->wtFlags & (TERM_DYNAMIC|TERM_ORINFO|TERM_ANDINFO))==0 );
98727 assert( pExpr->op==TK_OR );
98728 pTerm->u.pOrInfo = pOrInfo = sqlite3DbMallocZero(db, sizeof(*pOrInfo));
98729 if( pOrInfo==0 ) return;
98730 pTerm->wtFlags |= TERM_ORINFO;
98731 pOrWc = &pOrInfo->wc;
98732 whereClauseInit(pOrWc, pWC->pParse, pMaskSet);
98733 whereSplit(pOrWc, pExpr, TK_OR);
98734 exprAnalyzeAll(pSrc, pOrWc);
98735 if( db->mallocFailed ) return;
98736 assert( pOrWc->nTerm>=2 );
98739 ** Compute the set of tables that might satisfy cases 1 or 2.
98741 indexable = ~(Bitmask)0;
98742 chngToIN = ~(pWC->vmask);
98743 for(i=pOrWc->nTerm-1, pOrTerm=pOrWc->a; i>=0 && indexable; i--, pOrTerm++){
98744 if( (pOrTerm->eOperator & WO_SINGLE)==0 ){
98745 WhereAndInfo *pAndInfo;
98746 assert( pOrTerm->eOperator==0 );
98747 assert( (pOrTerm->wtFlags & (TERM_ANDINFO|TERM_ORINFO))==0 );
98748 chngToIN = 0;
98749 pAndInfo = sqlite3DbMallocRaw(db, sizeof(*pAndInfo));
98750 if( pAndInfo ){
98751 WhereClause *pAndWC;
98752 WhereTerm *pAndTerm;
98753 int j;
98754 Bitmask b = 0;
98755 pOrTerm->u.pAndInfo = pAndInfo;
98756 pOrTerm->wtFlags |= TERM_ANDINFO;
98757 pOrTerm->eOperator = WO_AND;
98758 pAndWC = &pAndInfo->wc;
98759 whereClauseInit(pAndWC, pWC->pParse, pMaskSet);
98760 whereSplit(pAndWC, pOrTerm->pExpr, TK_AND);
98761 exprAnalyzeAll(pSrc, pAndWC);
98762 testcase( db->mallocFailed );
98763 if( !db->mallocFailed ){
98764 for(j=0, pAndTerm=pAndWC->a; j<pAndWC->nTerm; j++, pAndTerm++){
98765 assert( pAndTerm->pExpr );
98766 if( allowedOp(pAndTerm->pExpr->op) ){
98767 b |= getMask(pMaskSet, pAndTerm->leftCursor);
98771 indexable &= b;
98773 }else if( pOrTerm->wtFlags & TERM_COPIED ){
98774 /* Skip this term for now. We revisit it when we process the
98775 ** corresponding TERM_VIRTUAL term */
98776 }else{
98777 Bitmask b;
98778 b = getMask(pMaskSet, pOrTerm->leftCursor);
98779 if( pOrTerm->wtFlags & TERM_VIRTUAL ){
98780 WhereTerm *pOther = &pOrWc->a[pOrTerm->iParent];
98781 b |= getMask(pMaskSet, pOther->leftCursor);
98783 indexable &= b;
98784 if( pOrTerm->eOperator!=WO_EQ ){
98785 chngToIN = 0;
98786 }else{
98787 chngToIN &= b;
98793 ** Record the set of tables that satisfy case 2. The set might be
98794 ** empty.
98796 pOrInfo->indexable = indexable;
98797 pTerm->eOperator = indexable==0 ? 0 : WO_OR;
98800 ** chngToIN holds a set of tables that *might* satisfy case 1. But
98801 ** we have to do some additional checking to see if case 1 really
98802 ** is satisfied.
98804 ** chngToIN will hold either 0, 1, or 2 bits. The 0-bit case means
98805 ** that there is no possibility of transforming the OR clause into an
98806 ** IN operator because one or more terms in the OR clause contain
98807 ** something other than == on a column in the single table. The 1-bit
98808 ** case means that every term of the OR clause is of the form
98809 ** "table.column=expr" for some single table. The one bit that is set
98810 ** will correspond to the common table. We still need to check to make
98811 ** sure the same column is used on all terms. The 2-bit case is when
98812 ** the all terms are of the form "table1.column=table2.column". It
98813 ** might be possible to form an IN operator with either table1.column
98814 ** or table2.column as the LHS if either is common to every term of
98815 ** the OR clause.
98817 ** Note that terms of the form "table.column1=table.column2" (the
98818 ** same table on both sizes of the ==) cannot be optimized.
98820 if( chngToIN ){
98821 int okToChngToIN = 0; /* True if the conversion to IN is valid */
98822 int iColumn = -1; /* Column index on lhs of IN operator */
98823 int iCursor = -1; /* Table cursor common to all terms */
98824 int j = 0; /* Loop counter */
98826 /* Search for a table and column that appears on one side or the
98827 ** other of the == operator in every subterm. That table and column
98828 ** will be recorded in iCursor and iColumn. There might not be any
98829 ** such table and column. Set okToChngToIN if an appropriate table
98830 ** and column is found but leave okToChngToIN false if not found.
98832 for(j=0; j<2 && !okToChngToIN; j++){
98833 pOrTerm = pOrWc->a;
98834 for(i=pOrWc->nTerm-1; i>=0; i--, pOrTerm++){
98835 assert( pOrTerm->eOperator==WO_EQ );
98836 pOrTerm->wtFlags &= ~TERM_OR_OK;
98837 if( pOrTerm->leftCursor==iCursor ){
98838 /* This is the 2-bit case and we are on the second iteration and
98839 ** current term is from the first iteration. So skip this term. */
98840 assert( j==1 );
98841 continue;
98843 if( (chngToIN & getMask(pMaskSet, pOrTerm->leftCursor))==0 ){
98844 /* This term must be of the form t1.a==t2.b where t2 is in the
98845 ** chngToIN set but t1 is not. This term will be either preceeded
98846 ** or follwed by an inverted copy (t2.b==t1.a). Skip this term
98847 ** and use its inversion. */
98848 testcase( pOrTerm->wtFlags & TERM_COPIED );
98849 testcase( pOrTerm->wtFlags & TERM_VIRTUAL );
98850 assert( pOrTerm->wtFlags & (TERM_COPIED|TERM_VIRTUAL) );
98851 continue;
98853 iColumn = pOrTerm->u.leftColumn;
98854 iCursor = pOrTerm->leftCursor;
98855 break;
98857 if( i<0 ){
98858 /* No candidate table+column was found. This can only occur
98859 ** on the second iteration */
98860 assert( j==1 );
98861 assert( (chngToIN&(chngToIN-1))==0 );
98862 assert( chngToIN==getMask(pMaskSet, iCursor) );
98863 break;
98865 testcase( j==1 );
98867 /* We have found a candidate table and column. Check to see if that
98868 ** table and column is common to every term in the OR clause */
98869 okToChngToIN = 1;
98870 for(; i>=0 && okToChngToIN; i--, pOrTerm++){
98871 assert( pOrTerm->eOperator==WO_EQ );
98872 if( pOrTerm->leftCursor!=iCursor ){
98873 pOrTerm->wtFlags &= ~TERM_OR_OK;
98874 }else if( pOrTerm->u.leftColumn!=iColumn ){
98875 okToChngToIN = 0;
98876 }else{
98877 int affLeft, affRight;
98878 /* If the right-hand side is also a column, then the affinities
98879 ** of both right and left sides must be such that no type
98880 ** conversions are required on the right. (Ticket #2249)
98882 affRight = sqlite3ExprAffinity(pOrTerm->pExpr->pRight);
98883 affLeft = sqlite3ExprAffinity(pOrTerm->pExpr->pLeft);
98884 if( affRight!=0 && affRight!=affLeft ){
98885 okToChngToIN = 0;
98886 }else{
98887 pOrTerm->wtFlags |= TERM_OR_OK;
98893 /* At this point, okToChngToIN is true if original pTerm satisfies
98894 ** case 1. In that case, construct a new virtual term that is
98895 ** pTerm converted into an IN operator.
98897 ** EV: R-00211-15100
98899 if( okToChngToIN ){
98900 Expr *pDup; /* A transient duplicate expression */
98901 ExprList *pList = 0; /* The RHS of the IN operator */
98902 Expr *pLeft = 0; /* The LHS of the IN operator */
98903 Expr *pNew; /* The complete IN operator */
98905 for(i=pOrWc->nTerm-1, pOrTerm=pOrWc->a; i>=0; i--, pOrTerm++){
98906 if( (pOrTerm->wtFlags & TERM_OR_OK)==0 ) continue;
98907 assert( pOrTerm->eOperator==WO_EQ );
98908 assert( pOrTerm->leftCursor==iCursor );
98909 assert( pOrTerm->u.leftColumn==iColumn );
98910 pDup = sqlite3ExprDup(db, pOrTerm->pExpr->pRight, 0);
98911 pList = sqlite3ExprListAppend(pWC->pParse, pList, pDup);
98912 pLeft = pOrTerm->pExpr->pLeft;
98914 assert( pLeft!=0 );
98915 pDup = sqlite3ExprDup(db, pLeft, 0);
98916 pNew = sqlite3PExpr(pParse, TK_IN, pDup, 0, 0);
98917 if( pNew ){
98918 int idxNew;
98919 transferJoinMarkings(pNew, pExpr);
98920 assert( !ExprHasProperty(pNew, EP_xIsSelect) );
98921 pNew->x.pList = pList;
98922 idxNew = whereClauseInsert(pWC, pNew, TERM_VIRTUAL|TERM_DYNAMIC);
98923 testcase( idxNew==0 );
98924 exprAnalyze(pSrc, pWC, idxNew);
98925 pTerm = &pWC->a[idxTerm];
98926 pWC->a[idxNew].iParent = idxTerm;
98927 pTerm->nChild = 1;
98928 }else{
98929 sqlite3ExprListDelete(db, pList);
98931 pTerm->eOperator = WO_NOOP; /* case 1 trumps case 2 */
98935 #endif /* !SQLITE_OMIT_OR_OPTIMIZATION && !SQLITE_OMIT_SUBQUERY */
98939 ** The input to this routine is an WhereTerm structure with only the
98940 ** "pExpr" field filled in. The job of this routine is to analyze the
98941 ** subexpression and populate all the other fields of the WhereTerm
98942 ** structure.
98944 ** If the expression is of the form "<expr> <op> X" it gets commuted
98945 ** to the standard form of "X <op> <expr>".
98947 ** If the expression is of the form "X <op> Y" where both X and Y are
98948 ** columns, then the original expression is unchanged and a new virtual
98949 ** term of the form "Y <op> X" is added to the WHERE clause and
98950 ** analyzed separately. The original term is marked with TERM_COPIED
98951 ** and the new term is marked with TERM_DYNAMIC (because it's pExpr
98952 ** needs to be freed with the WhereClause) and TERM_VIRTUAL (because it
98953 ** is a commuted copy of a prior term.) The original term has nChild=1
98954 ** and the copy has idxParent set to the index of the original term.
98956 static void exprAnalyze(
98957 SrcList *pSrc, /* the FROM clause */
98958 WhereClause *pWC, /* the WHERE clause */
98959 int idxTerm /* Index of the term to be analyzed */
98961 WhereTerm *pTerm; /* The term to be analyzed */
98962 WhereMaskSet *pMaskSet; /* Set of table index masks */
98963 Expr *pExpr; /* The expression to be analyzed */
98964 Bitmask prereqLeft; /* Prerequesites of the pExpr->pLeft */
98965 Bitmask prereqAll; /* Prerequesites of pExpr */
98966 Bitmask extraRight = 0; /* Extra dependencies on LEFT JOIN */
98967 Expr *pStr1 = 0; /* RHS of LIKE/GLOB operator */
98968 int isComplete = 0; /* RHS of LIKE/GLOB ends with wildcard */
98969 int noCase = 0; /* LIKE/GLOB distinguishes case */
98970 int op; /* Top-level operator. pExpr->op */
98971 Parse *pParse = pWC->pParse; /* Parsing context */
98972 sqlite3 *db = pParse->db; /* Database connection */
98974 if( db->mallocFailed ){
98975 return;
98977 pTerm = &pWC->a[idxTerm];
98978 pMaskSet = pWC->pMaskSet;
98979 pExpr = pTerm->pExpr;
98980 prereqLeft = exprTableUsage(pMaskSet, pExpr->pLeft);
98981 op = pExpr->op;
98982 if( op==TK_IN ){
98983 assert( pExpr->pRight==0 );
98984 if( ExprHasProperty(pExpr, EP_xIsSelect) ){
98985 pTerm->prereqRight = exprSelectTableUsage(pMaskSet, pExpr->x.pSelect);
98986 }else{
98987 pTerm->prereqRight = exprListTableUsage(pMaskSet, pExpr->x.pList);
98989 }else if( op==TK_ISNULL ){
98990 pTerm->prereqRight = 0;
98991 }else{
98992 pTerm->prereqRight = exprTableUsage(pMaskSet, pExpr->pRight);
98994 prereqAll = exprTableUsage(pMaskSet, pExpr);
98995 if( ExprHasProperty(pExpr, EP_FromJoin) ){
98996 Bitmask x = getMask(pMaskSet, pExpr->iRightJoinTable);
98997 prereqAll |= x;
98998 extraRight = x-1; /* ON clause terms may not be used with an index
98999 ** on left table of a LEFT JOIN. Ticket #3015 */
99001 pTerm->prereqAll = prereqAll;
99002 pTerm->leftCursor = -1;
99003 pTerm->iParent = -1;
99004 pTerm->eOperator = 0;
99005 if( allowedOp(op) && (pTerm->prereqRight & prereqLeft)==0 ){
99006 Expr *pLeft = pExpr->pLeft;
99007 Expr *pRight = pExpr->pRight;
99008 if( pLeft->op==TK_COLUMN ){
99009 pTerm->leftCursor = pLeft->iTable;
99010 pTerm->u.leftColumn = pLeft->iColumn;
99011 pTerm->eOperator = operatorMask(op);
99013 if( pRight && pRight->op==TK_COLUMN ){
99014 WhereTerm *pNew;
99015 Expr *pDup;
99016 if( pTerm->leftCursor>=0 ){
99017 int idxNew;
99018 pDup = sqlite3ExprDup(db, pExpr, 0);
99019 if( db->mallocFailed ){
99020 sqlite3ExprDelete(db, pDup);
99021 return;
99023 idxNew = whereClauseInsert(pWC, pDup, TERM_VIRTUAL|TERM_DYNAMIC);
99024 if( idxNew==0 ) return;
99025 pNew = &pWC->a[idxNew];
99026 pNew->iParent = idxTerm;
99027 pTerm = &pWC->a[idxTerm];
99028 pTerm->nChild = 1;
99029 pTerm->wtFlags |= TERM_COPIED;
99030 }else{
99031 pDup = pExpr;
99032 pNew = pTerm;
99034 exprCommute(pParse, pDup);
99035 pLeft = pDup->pLeft;
99036 pNew->leftCursor = pLeft->iTable;
99037 pNew->u.leftColumn = pLeft->iColumn;
99038 testcase( (prereqLeft | extraRight) != prereqLeft );
99039 pNew->prereqRight = prereqLeft | extraRight;
99040 pNew->prereqAll = prereqAll;
99041 pNew->eOperator = operatorMask(pDup->op);
99045 #ifndef SQLITE_OMIT_BETWEEN_OPTIMIZATION
99046 /* If a term is the BETWEEN operator, create two new virtual terms
99047 ** that define the range that the BETWEEN implements. For example:
99049 ** a BETWEEN b AND c
99051 ** is converted into:
99053 ** (a BETWEEN b AND c) AND (a>=b) AND (a<=c)
99055 ** The two new terms are added onto the end of the WhereClause object.
99056 ** The new terms are "dynamic" and are children of the original BETWEEN
99057 ** term. That means that if the BETWEEN term is coded, the children are
99058 ** skipped. Or, if the children are satisfied by an index, the original
99059 ** BETWEEN term is skipped.
99061 else if( pExpr->op==TK_BETWEEN && pWC->op==TK_AND ){
99062 ExprList *pList = pExpr->x.pList;
99063 int i;
99064 static const u8 ops[] = {TK_GE, TK_LE};
99065 assert( pList!=0 );
99066 assert( pList->nExpr==2 );
99067 for(i=0; i<2; i++){
99068 Expr *pNewExpr;
99069 int idxNew;
99070 pNewExpr = sqlite3PExpr(pParse, ops[i],
99071 sqlite3ExprDup(db, pExpr->pLeft, 0),
99072 sqlite3ExprDup(db, pList->a[i].pExpr, 0), 0);
99073 idxNew = whereClauseInsert(pWC, pNewExpr, TERM_VIRTUAL|TERM_DYNAMIC);
99074 testcase( idxNew==0 );
99075 exprAnalyze(pSrc, pWC, idxNew);
99076 pTerm = &pWC->a[idxTerm];
99077 pWC->a[idxNew].iParent = idxTerm;
99079 pTerm->nChild = 2;
99081 #endif /* SQLITE_OMIT_BETWEEN_OPTIMIZATION */
99083 #if !defined(SQLITE_OMIT_OR_OPTIMIZATION) && !defined(SQLITE_OMIT_SUBQUERY)
99084 /* Analyze a term that is composed of two or more subterms connected by
99085 ** an OR operator.
99087 else if( pExpr->op==TK_OR ){
99088 assert( pWC->op==TK_AND );
99089 exprAnalyzeOrTerm(pSrc, pWC, idxTerm);
99090 pTerm = &pWC->a[idxTerm];
99092 #endif /* SQLITE_OMIT_OR_OPTIMIZATION */
99094 #ifndef SQLITE_OMIT_LIKE_OPTIMIZATION
99095 /* Add constraints to reduce the search space on a LIKE or GLOB
99096 ** operator.
99098 ** A like pattern of the form "x LIKE 'abc%'" is changed into constraints
99100 ** x>='abc' AND x<'abd' AND x LIKE 'abc%'
99102 ** The last character of the prefix "abc" is incremented to form the
99103 ** termination condition "abd".
99105 if( pWC->op==TK_AND
99106 && isLikeOrGlob(pParse, pExpr, &pStr1, &isComplete, &noCase)
99108 Expr *pLeft; /* LHS of LIKE/GLOB operator */
99109 Expr *pStr2; /* Copy of pStr1 - RHS of LIKE/GLOB operator */
99110 Expr *pNewExpr1;
99111 Expr *pNewExpr2;
99112 int idxNew1;
99113 int idxNew2;
99114 CollSeq *pColl; /* Collating sequence to use */
99116 pLeft = pExpr->x.pList->a[1].pExpr;
99117 pStr2 = sqlite3ExprDup(db, pStr1, 0);
99118 if( !db->mallocFailed ){
99119 u8 c, *pC; /* Last character before the first wildcard */
99120 pC = (u8*)&pStr2->u.zToken[sqlite3Strlen30(pStr2->u.zToken)-1];
99121 c = *pC;
99122 if( noCase ){
99123 /* The point is to increment the last character before the first
99124 ** wildcard. But if we increment '@', that will push it into the
99125 ** alphabetic range where case conversions will mess up the
99126 ** inequality. To avoid this, make sure to also run the full
99127 ** LIKE on all candidate expressions by clearing the isComplete flag
99129 if( c=='A'-1 ) isComplete = 0; /* EV: R-64339-08207 */
99132 c = sqlite3UpperToLower[c];
99134 *pC = c + 1;
99136 pColl = sqlite3FindCollSeq(db, SQLITE_UTF8, noCase ? "NOCASE" : "BINARY",0);
99137 pNewExpr1 = sqlite3PExpr(pParse, TK_GE,
99138 sqlite3ExprSetColl(sqlite3ExprDup(db,pLeft,0), pColl),
99139 pStr1, 0);
99140 idxNew1 = whereClauseInsert(pWC, pNewExpr1, TERM_VIRTUAL|TERM_DYNAMIC);
99141 testcase( idxNew1==0 );
99142 exprAnalyze(pSrc, pWC, idxNew1);
99143 pNewExpr2 = sqlite3PExpr(pParse, TK_LT,
99144 sqlite3ExprSetColl(sqlite3ExprDup(db,pLeft,0), pColl),
99145 pStr2, 0);
99146 idxNew2 = whereClauseInsert(pWC, pNewExpr2, TERM_VIRTUAL|TERM_DYNAMIC);
99147 testcase( idxNew2==0 );
99148 exprAnalyze(pSrc, pWC, idxNew2);
99149 pTerm = &pWC->a[idxTerm];
99150 if( isComplete ){
99151 pWC->a[idxNew1].iParent = idxTerm;
99152 pWC->a[idxNew2].iParent = idxTerm;
99153 pTerm->nChild = 2;
99156 #endif /* SQLITE_OMIT_LIKE_OPTIMIZATION */
99158 #ifndef SQLITE_OMIT_VIRTUALTABLE
99159 /* Add a WO_MATCH auxiliary term to the constraint set if the
99160 ** current expression is of the form: column MATCH expr.
99161 ** This information is used by the xBestIndex methods of
99162 ** virtual tables. The native query optimizer does not attempt
99163 ** to do anything with MATCH functions.
99165 if( isMatchOfColumn(pExpr) ){
99166 int idxNew;
99167 Expr *pRight, *pLeft;
99168 WhereTerm *pNewTerm;
99169 Bitmask prereqColumn, prereqExpr;
99171 pRight = pExpr->x.pList->a[0].pExpr;
99172 pLeft = pExpr->x.pList->a[1].pExpr;
99173 prereqExpr = exprTableUsage(pMaskSet, pRight);
99174 prereqColumn = exprTableUsage(pMaskSet, pLeft);
99175 if( (prereqExpr & prereqColumn)==0 ){
99176 Expr *pNewExpr;
99177 pNewExpr = sqlite3PExpr(pParse, TK_MATCH,
99178 0, sqlite3ExprDup(db, pRight, 0), 0);
99179 idxNew = whereClauseInsert(pWC, pNewExpr, TERM_VIRTUAL|TERM_DYNAMIC);
99180 testcase( idxNew==0 );
99181 pNewTerm = &pWC->a[idxNew];
99182 pNewTerm->prereqRight = prereqExpr;
99183 pNewTerm->leftCursor = pLeft->iTable;
99184 pNewTerm->u.leftColumn = pLeft->iColumn;
99185 pNewTerm->eOperator = WO_MATCH;
99186 pNewTerm->iParent = idxTerm;
99187 pTerm = &pWC->a[idxTerm];
99188 pTerm->nChild = 1;
99189 pTerm->wtFlags |= TERM_COPIED;
99190 pNewTerm->prereqAll = pTerm->prereqAll;
99193 #endif /* SQLITE_OMIT_VIRTUALTABLE */
99195 #ifdef SQLITE_ENABLE_STAT2
99196 /* When sqlite_stat2 histogram data is available an operator of the
99197 ** form "x IS NOT NULL" can sometimes be evaluated more efficiently
99198 ** as "x>NULL" if x is not an INTEGER PRIMARY KEY. So construct a
99199 ** virtual term of that form.
99201 ** Note that the virtual term must be tagged with TERM_VNULL. This
99202 ** TERM_VNULL tag will suppress the not-null check at the beginning
99203 ** of the loop. Without the TERM_VNULL flag, the not-null check at
99204 ** the start of the loop will prevent any results from being returned.
99206 if( pExpr->op==TK_NOTNULL
99207 && pExpr->pLeft->op==TK_COLUMN
99208 && pExpr->pLeft->iColumn>=0
99210 Expr *pNewExpr;
99211 Expr *pLeft = pExpr->pLeft;
99212 int idxNew;
99213 WhereTerm *pNewTerm;
99215 pNewExpr = sqlite3PExpr(pParse, TK_GT,
99216 sqlite3ExprDup(db, pLeft, 0),
99217 sqlite3PExpr(pParse, TK_NULL, 0, 0, 0), 0);
99219 idxNew = whereClauseInsert(pWC, pNewExpr,
99220 TERM_VIRTUAL|TERM_DYNAMIC|TERM_VNULL);
99221 if( idxNew ){
99222 pNewTerm = &pWC->a[idxNew];
99223 pNewTerm->prereqRight = 0;
99224 pNewTerm->leftCursor = pLeft->iTable;
99225 pNewTerm->u.leftColumn = pLeft->iColumn;
99226 pNewTerm->eOperator = WO_GT;
99227 pNewTerm->iParent = idxTerm;
99228 pTerm = &pWC->a[idxTerm];
99229 pTerm->nChild = 1;
99230 pTerm->wtFlags |= TERM_COPIED;
99231 pNewTerm->prereqAll = pTerm->prereqAll;
99234 #endif /* SQLITE_ENABLE_STAT2 */
99236 /* Prevent ON clause terms of a LEFT JOIN from being used to drive
99237 ** an index for tables to the left of the join.
99239 pTerm->prereqRight |= extraRight;
99243 ** Return TRUE if any of the expressions in pList->a[iFirst...] contain
99244 ** a reference to any table other than the iBase table.
99246 static int referencesOtherTables(
99247 ExprList *pList, /* Search expressions in ths list */
99248 WhereMaskSet *pMaskSet, /* Mapping from tables to bitmaps */
99249 int iFirst, /* Be searching with the iFirst-th expression */
99250 int iBase /* Ignore references to this table */
99252 Bitmask allowed = ~getMask(pMaskSet, iBase);
99253 while( iFirst<pList->nExpr ){
99254 if( (exprTableUsage(pMaskSet, pList->a[iFirst++].pExpr)&allowed)!=0 ){
99255 return 1;
99258 return 0;
99263 ** This routine decides if pIdx can be used to satisfy the ORDER BY
99264 ** clause. If it can, it returns 1. If pIdx cannot satisfy the
99265 ** ORDER BY clause, this routine returns 0.
99267 ** pOrderBy is an ORDER BY clause from a SELECT statement. pTab is the
99268 ** left-most table in the FROM clause of that same SELECT statement and
99269 ** the table has a cursor number of "base". pIdx is an index on pTab.
99271 ** nEqCol is the number of columns of pIdx that are used as equality
99272 ** constraints. Any of these columns may be missing from the ORDER BY
99273 ** clause and the match can still be a success.
99275 ** All terms of the ORDER BY that match against the index must be either
99276 ** ASC or DESC. (Terms of the ORDER BY clause past the end of a UNIQUE
99277 ** index do not need to satisfy this constraint.) The *pbRev value is
99278 ** set to 1 if the ORDER BY clause is all DESC and it is set to 0 if
99279 ** the ORDER BY clause is all ASC.
99281 static int isSortingIndex(
99282 Parse *pParse, /* Parsing context */
99283 WhereMaskSet *pMaskSet, /* Mapping from table cursor numbers to bitmaps */
99284 Index *pIdx, /* The index we are testing */
99285 int base, /* Cursor number for the table to be sorted */
99286 ExprList *pOrderBy, /* The ORDER BY clause */
99287 int nEqCol, /* Number of index columns with == constraints */
99288 int wsFlags, /* Index usages flags */
99289 int *pbRev /* Set to 1 if ORDER BY is DESC */
99291 int i, j; /* Loop counters */
99292 int sortOrder = 0; /* XOR of index and ORDER BY sort direction */
99293 int nTerm; /* Number of ORDER BY terms */
99294 struct ExprList_item *pTerm; /* A term of the ORDER BY clause */
99295 sqlite3 *db = pParse->db;
99297 assert( pOrderBy!=0 );
99298 nTerm = pOrderBy->nExpr;
99299 assert( nTerm>0 );
99301 /* Argument pIdx must either point to a 'real' named index structure,
99302 ** or an index structure allocated on the stack by bestBtreeIndex() to
99303 ** represent the rowid index that is part of every table. */
99304 assert( pIdx->zName || (pIdx->nColumn==1 && pIdx->aiColumn[0]==-1) );
99306 /* Match terms of the ORDER BY clause against columns of
99307 ** the index.
99309 ** Note that indices have pIdx->nColumn regular columns plus
99310 ** one additional column containing the rowid. The rowid column
99311 ** of the index is also allowed to match against the ORDER BY
99312 ** clause.
99314 for(i=j=0, pTerm=pOrderBy->a; j<nTerm && i<=pIdx->nColumn; i++){
99315 Expr *pExpr; /* The expression of the ORDER BY pTerm */
99316 CollSeq *pColl; /* The collating sequence of pExpr */
99317 int termSortOrder; /* Sort order for this term */
99318 int iColumn; /* The i-th column of the index. -1 for rowid */
99319 int iSortOrder; /* 1 for DESC, 0 for ASC on the i-th index term */
99320 const char *zColl; /* Name of the collating sequence for i-th index term */
99322 pExpr = pTerm->pExpr;
99323 if( pExpr->op!=TK_COLUMN || pExpr->iTable!=base ){
99324 /* Can not use an index sort on anything that is not a column in the
99325 ** left-most table of the FROM clause */
99326 break;
99328 pColl = sqlite3ExprCollSeq(pParse, pExpr);
99329 if( !pColl ){
99330 pColl = db->pDfltColl;
99332 if( pIdx->zName && i<pIdx->nColumn ){
99333 iColumn = pIdx->aiColumn[i];
99334 if( iColumn==pIdx->pTable->iPKey ){
99335 iColumn = -1;
99337 iSortOrder = pIdx->aSortOrder[i];
99338 zColl = pIdx->azColl[i];
99339 }else{
99340 iColumn = -1;
99341 iSortOrder = 0;
99342 zColl = pColl->zName;
99344 if( pExpr->iColumn!=iColumn || sqlite3StrICmp(pColl->zName, zColl) ){
99345 /* Term j of the ORDER BY clause does not match column i of the index */
99346 if( i<nEqCol ){
99347 /* If an index column that is constrained by == fails to match an
99348 ** ORDER BY term, that is OK. Just ignore that column of the index
99350 continue;
99351 }else if( i==pIdx->nColumn ){
99352 /* Index column i is the rowid. All other terms match. */
99353 break;
99354 }else{
99355 /* If an index column fails to match and is not constrained by ==
99356 ** then the index cannot satisfy the ORDER BY constraint.
99358 return 0;
99361 assert( pIdx->aSortOrder!=0 || iColumn==-1 );
99362 assert( pTerm->sortOrder==0 || pTerm->sortOrder==1 );
99363 assert( iSortOrder==0 || iSortOrder==1 );
99364 termSortOrder = iSortOrder ^ pTerm->sortOrder;
99365 if( i>nEqCol ){
99366 if( termSortOrder!=sortOrder ){
99367 /* Indices can only be used if all ORDER BY terms past the
99368 ** equality constraints are all either DESC or ASC. */
99369 return 0;
99371 }else{
99372 sortOrder = termSortOrder;
99374 j++;
99375 pTerm++;
99376 if( iColumn<0 && !referencesOtherTables(pOrderBy, pMaskSet, j, base) ){
99377 /* If the indexed column is the primary key and everything matches
99378 ** so far and none of the ORDER BY terms to the right reference other
99379 ** tables in the join, then we are assured that the index can be used
99380 ** to sort because the primary key is unique and so none of the other
99381 ** columns will make any difference
99383 j = nTerm;
99387 *pbRev = sortOrder!=0;
99388 if( j>=nTerm ){
99389 /* All terms of the ORDER BY clause are covered by this index so
99390 ** this index can be used for sorting. */
99391 return 1;
99393 if( pIdx->onError!=OE_None && i==pIdx->nColumn
99394 && (wsFlags & WHERE_COLUMN_NULL)==0
99395 && !referencesOtherTables(pOrderBy, pMaskSet, j, base) ){
99396 /* All terms of this index match some prefix of the ORDER BY clause
99397 ** and the index is UNIQUE and no terms on the tail of the ORDER BY
99398 ** clause reference other tables in a join. If this is all true then
99399 ** the order by clause is superfluous. Not that if the matching
99400 ** condition is IS NULL then the result is not necessarily unique
99401 ** even on a UNIQUE index, so disallow those cases. */
99402 return 1;
99404 return 0;
99408 ** Prepare a crude estimate of the logarithm of the input value.
99409 ** The results need not be exact. This is only used for estimating
99410 ** the total cost of performing operations with O(logN) or O(NlogN)
99411 ** complexity. Because N is just a guess, it is no great tragedy if
99412 ** logN is a little off.
99414 static double estLog(double N){
99415 double logN = 1;
99416 double x = 10;
99417 while( N>x ){
99418 logN += 1;
99419 x *= 10;
99421 return logN;
99425 ** Two routines for printing the content of an sqlite3_index_info
99426 ** structure. Used for testing and debugging only. If neither
99427 ** SQLITE_TEST or SQLITE_DEBUG are defined, then these routines
99428 ** are no-ops.
99430 #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_DEBUG)
99431 static void TRACE_IDX_INPUTS(sqlite3_index_info *p){
99432 int i;
99433 if( !sqlite3WhereTrace ) return;
99434 for(i=0; i<p->nConstraint; i++){
99435 sqlite3DebugPrintf(" constraint[%d]: col=%d termid=%d op=%d usabled=%d\n",
99437 p->aConstraint[i].iColumn,
99438 p->aConstraint[i].iTermOffset,
99439 p->aConstraint[i].op,
99440 p->aConstraint[i].usable);
99442 for(i=0; i<p->nOrderBy; i++){
99443 sqlite3DebugPrintf(" orderby[%d]: col=%d desc=%d\n",
99445 p->aOrderBy[i].iColumn,
99446 p->aOrderBy[i].desc);
99449 static void TRACE_IDX_OUTPUTS(sqlite3_index_info *p){
99450 int i;
99451 if( !sqlite3WhereTrace ) return;
99452 for(i=0; i<p->nConstraint; i++){
99453 sqlite3DebugPrintf(" usage[%d]: argvIdx=%d omit=%d\n",
99455 p->aConstraintUsage[i].argvIndex,
99456 p->aConstraintUsage[i].omit);
99458 sqlite3DebugPrintf(" idxNum=%d\n", p->idxNum);
99459 sqlite3DebugPrintf(" idxStr=%s\n", p->idxStr);
99460 sqlite3DebugPrintf(" orderByConsumed=%d\n", p->orderByConsumed);
99461 sqlite3DebugPrintf(" estimatedCost=%g\n", p->estimatedCost);
99463 #else
99464 #define TRACE_IDX_INPUTS(A)
99465 #define TRACE_IDX_OUTPUTS(A)
99466 #endif
99469 ** Required because bestIndex() is called by bestOrClauseIndex()
99471 static void bestIndex(
99472 Parse*, WhereClause*, struct SrcList_item*,
99473 Bitmask, Bitmask, ExprList*, WhereCost*);
99476 ** This routine attempts to find an scanning strategy that can be used
99477 ** to optimize an 'OR' expression that is part of a WHERE clause.
99479 ** The table associated with FROM clause term pSrc may be either a
99480 ** regular B-Tree table or a virtual table.
99482 static void bestOrClauseIndex(
99483 Parse *pParse, /* The parsing context */
99484 WhereClause *pWC, /* The WHERE clause */
99485 struct SrcList_item *pSrc, /* The FROM clause term to search */
99486 Bitmask notReady, /* Mask of cursors not available for indexing */
99487 Bitmask notValid, /* Cursors not available for any purpose */
99488 ExprList *pOrderBy, /* The ORDER BY clause */
99489 WhereCost *pCost /* Lowest cost query plan */
99491 #ifndef SQLITE_OMIT_OR_OPTIMIZATION
99492 const int iCur = pSrc->iCursor; /* The cursor of the table to be accessed */
99493 const Bitmask maskSrc = getMask(pWC->pMaskSet, iCur); /* Bitmask for pSrc */
99494 WhereTerm * const pWCEnd = &pWC->a[pWC->nTerm]; /* End of pWC->a[] */
99495 WhereTerm *pTerm; /* A single term of the WHERE clause */
99497 /* No OR-clause optimization allowed if the INDEXED BY or NOT INDEXED clauses
99498 ** are used */
99499 if( pSrc->notIndexed || pSrc->pIndex!=0 ){
99500 return;
99503 /* Search the WHERE clause terms for a usable WO_OR term. */
99504 for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){
99505 if( pTerm->eOperator==WO_OR
99506 && ((pTerm->prereqAll & ~maskSrc) & notReady)==0
99507 && (pTerm->u.pOrInfo->indexable & maskSrc)!=0
99509 WhereClause * const pOrWC = &pTerm->u.pOrInfo->wc;
99510 WhereTerm * const pOrWCEnd = &pOrWC->a[pOrWC->nTerm];
99511 WhereTerm *pOrTerm;
99512 int flags = WHERE_MULTI_OR;
99513 double rTotal = 0;
99514 double nRow = 0;
99515 Bitmask used = 0;
99517 for(pOrTerm=pOrWC->a; pOrTerm<pOrWCEnd; pOrTerm++){
99518 WhereCost sTermCost;
99519 WHERETRACE(("... Multi-index OR testing for term %d of %d....\n",
99520 (pOrTerm - pOrWC->a), (pTerm - pWC->a)
99522 if( pOrTerm->eOperator==WO_AND ){
99523 WhereClause *pAndWC = &pOrTerm->u.pAndInfo->wc;
99524 bestIndex(pParse, pAndWC, pSrc, notReady, notValid, 0, &sTermCost);
99525 }else if( pOrTerm->leftCursor==iCur ){
99526 WhereClause tempWC;
99527 tempWC.pParse = pWC->pParse;
99528 tempWC.pMaskSet = pWC->pMaskSet;
99529 tempWC.op = TK_AND;
99530 tempWC.a = pOrTerm;
99531 tempWC.nTerm = 1;
99532 bestIndex(pParse, &tempWC, pSrc, notReady, notValid, 0, &sTermCost);
99533 }else{
99534 continue;
99536 rTotal += sTermCost.rCost;
99537 nRow += sTermCost.plan.nRow;
99538 used |= sTermCost.used;
99539 if( rTotal>=pCost->rCost ) break;
99542 /* If there is an ORDER BY clause, increase the scan cost to account
99543 ** for the cost of the sort. */
99544 if( pOrderBy!=0 ){
99545 WHERETRACE(("... sorting increases OR cost %.9g to %.9g\n",
99546 rTotal, rTotal+nRow*estLog(nRow)));
99547 rTotal += nRow*estLog(nRow);
99550 /* If the cost of scanning using this OR term for optimization is
99551 ** less than the current cost stored in pCost, replace the contents
99552 ** of pCost. */
99553 WHERETRACE(("... multi-index OR cost=%.9g nrow=%.9g\n", rTotal, nRow));
99554 if( rTotal<pCost->rCost ){
99555 pCost->rCost = rTotal;
99556 pCost->used = used;
99557 pCost->plan.nRow = nRow;
99558 pCost->plan.wsFlags = flags;
99559 pCost->plan.u.pTerm = pTerm;
99563 #endif /* SQLITE_OMIT_OR_OPTIMIZATION */
99566 #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
99568 ** Return TRUE if the WHERE clause term pTerm is of a form where it
99569 ** could be used with an index to access pSrc, assuming an appropriate
99570 ** index existed.
99572 static int termCanDriveIndex(
99573 WhereTerm *pTerm, /* WHERE clause term to check */
99574 struct SrcList_item *pSrc, /* Table we are trying to access */
99575 Bitmask notReady /* Tables in outer loops of the join */
99577 char aff;
99578 if( pTerm->leftCursor!=pSrc->iCursor ) return 0;
99579 if( pTerm->eOperator!=WO_EQ ) return 0;
99580 if( (pTerm->prereqRight & notReady)!=0 ) return 0;
99581 aff = pSrc->pTab->aCol[pTerm->u.leftColumn].affinity;
99582 if( !sqlite3IndexAffinityOk(pTerm->pExpr, aff) ) return 0;
99583 return 1;
99585 #endif
99587 #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
99589 ** If the query plan for pSrc specified in pCost is a full table scan
99590 ** and indexing is allows (if there is no NOT INDEXED clause) and it
99591 ** possible to construct a transient index that would perform better
99592 ** than a full table scan even when the cost of constructing the index
99593 ** is taken into account, then alter the query plan to use the
99594 ** transient index.
99596 static void bestAutomaticIndex(
99597 Parse *pParse, /* The parsing context */
99598 WhereClause *pWC, /* The WHERE clause */
99599 struct SrcList_item *pSrc, /* The FROM clause term to search */
99600 Bitmask notReady, /* Mask of cursors that are not available */
99601 WhereCost *pCost /* Lowest cost query plan */
99603 double nTableRow; /* Rows in the input table */
99604 double logN; /* log(nTableRow) */
99605 double costTempIdx; /* per-query cost of the transient index */
99606 WhereTerm *pTerm; /* A single term of the WHERE clause */
99607 WhereTerm *pWCEnd; /* End of pWC->a[] */
99608 Table *pTable; /* Table tht might be indexed */
99610 if( (pParse->db->flags & SQLITE_AutoIndex)==0 ){
99611 /* Automatic indices are disabled at run-time */
99612 return;
99614 if( (pCost->plan.wsFlags & WHERE_NOT_FULLSCAN)!=0 ){
99615 /* We already have some kind of index in use for this query. */
99616 return;
99618 if( pSrc->notIndexed ){
99619 /* The NOT INDEXED clause appears in the SQL. */
99620 return;
99623 assert( pParse->nQueryLoop >= (double)1 );
99624 pTable = pSrc->pTab;
99625 nTableRow = pTable->nRowEst;
99626 logN = estLog(nTableRow);
99627 costTempIdx = 2*logN*(nTableRow/pParse->nQueryLoop + 1);
99628 if( costTempIdx>=pCost->rCost ){
99629 /* The cost of creating the transient table would be greater than
99630 ** doing the full table scan */
99631 return;
99634 /* Search for any equality comparison term */
99635 pWCEnd = &pWC->a[pWC->nTerm];
99636 for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){
99637 if( termCanDriveIndex(pTerm, pSrc, notReady) ){
99638 WHERETRACE(("auto-index reduces cost from %.1f to %.1f\n",
99639 pCost->rCost, costTempIdx));
99640 pCost->rCost = costTempIdx;
99641 pCost->plan.nRow = logN + 1;
99642 pCost->plan.wsFlags = WHERE_TEMP_INDEX;
99643 pCost->used = pTerm->prereqRight;
99644 break;
99648 #else
99649 # define bestAutomaticIndex(A,B,C,D,E) /* no-op */
99650 #endif /* SQLITE_OMIT_AUTOMATIC_INDEX */
99653 #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
99655 ** Generate code to construct the Index object for an automatic index
99656 ** and to set up the WhereLevel object pLevel so that the code generator
99657 ** makes use of the automatic index.
99659 static void constructAutomaticIndex(
99660 Parse *pParse, /* The parsing context */
99661 WhereClause *pWC, /* The WHERE clause */
99662 struct SrcList_item *pSrc, /* The FROM clause term to get the next index */
99663 Bitmask notReady, /* Mask of cursors that are not available */
99664 WhereLevel *pLevel /* Write new index here */
99666 int nColumn; /* Number of columns in the constructed index */
99667 WhereTerm *pTerm; /* A single term of the WHERE clause */
99668 WhereTerm *pWCEnd; /* End of pWC->a[] */
99669 int nByte; /* Byte of memory needed for pIdx */
99670 Index *pIdx; /* Object describing the transient index */
99671 Vdbe *v; /* Prepared statement under construction */
99672 int regIsInit; /* Register set by initialization */
99673 int addrInit; /* Address of the initialization bypass jump */
99674 Table *pTable; /* The table being indexed */
99675 KeyInfo *pKeyinfo; /* Key information for the index */
99676 int addrTop; /* Top of the index fill loop */
99677 int regRecord; /* Register holding an index record */
99678 int n; /* Column counter */
99679 int i; /* Loop counter */
99680 int mxBitCol; /* Maximum column in pSrc->colUsed */
99681 CollSeq *pColl; /* Collating sequence to on a column */
99682 Bitmask idxCols; /* Bitmap of columns used for indexing */
99683 Bitmask extraCols; /* Bitmap of additional columns */
99685 /* Generate code to skip over the creation and initialization of the
99686 ** transient index on 2nd and subsequent iterations of the loop. */
99687 v = pParse->pVdbe;
99688 assert( v!=0 );
99689 regIsInit = ++pParse->nMem;
99690 addrInit = sqlite3VdbeAddOp1(v, OP_If, regIsInit);
99691 sqlite3VdbeAddOp2(v, OP_Integer, 1, regIsInit);
99693 /* Count the number of columns that will be added to the index
99694 ** and used to match WHERE clause constraints */
99695 nColumn = 0;
99696 pTable = pSrc->pTab;
99697 pWCEnd = &pWC->a[pWC->nTerm];
99698 idxCols = 0;
99699 for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){
99700 if( termCanDriveIndex(pTerm, pSrc, notReady) ){
99701 int iCol = pTerm->u.leftColumn;
99702 Bitmask cMask = iCol>=BMS ? ((Bitmask)1)<<(BMS-1) : ((Bitmask)1)<<iCol;
99703 testcase( iCol==BMS );
99704 testcase( iCol==BMS-1 );
99705 if( (idxCols & cMask)==0 ){
99706 nColumn++;
99707 idxCols |= cMask;
99711 assert( nColumn>0 );
99712 pLevel->plan.nEq = nColumn;
99714 /* Count the number of additional columns needed to create a
99715 ** covering index. A "covering index" is an index that contains all
99716 ** columns that are needed by the query. With a covering index, the
99717 ** original table never needs to be accessed. Automatic indices must
99718 ** be a covering index because the index will not be updated if the
99719 ** original table changes and the index and table cannot both be used
99720 ** if they go out of sync.
99722 extraCols = pSrc->colUsed & (~idxCols | (((Bitmask)1)<<(BMS-1)));
99723 mxBitCol = (pTable->nCol >= BMS-1) ? BMS-1 : pTable->nCol;
99724 testcase( pTable->nCol==BMS-1 );
99725 testcase( pTable->nCol==BMS-2 );
99726 for(i=0; i<mxBitCol; i++){
99727 if( extraCols & (((Bitmask)1)<<i) ) nColumn++;
99729 if( pSrc->colUsed & (((Bitmask)1)<<(BMS-1)) ){
99730 nColumn += pTable->nCol - BMS + 1;
99732 pLevel->plan.wsFlags |= WHERE_COLUMN_EQ | WHERE_IDX_ONLY | WO_EQ;
99734 /* Construct the Index object to describe this index */
99735 nByte = sizeof(Index);
99736 nByte += nColumn*sizeof(int); /* Index.aiColumn */
99737 nByte += nColumn*sizeof(char*); /* Index.azColl */
99738 nByte += nColumn; /* Index.aSortOrder */
99739 pIdx = sqlite3DbMallocZero(pParse->db, nByte);
99740 if( pIdx==0 ) return;
99741 pLevel->plan.u.pIdx = pIdx;
99742 pIdx->azColl = (char**)&pIdx[1];
99743 pIdx->aiColumn = (int*)&pIdx->azColl[nColumn];
99744 pIdx->aSortOrder = (u8*)&pIdx->aiColumn[nColumn];
99745 pIdx->zName = "auto-index";
99746 pIdx->nColumn = nColumn;
99747 pIdx->pTable = pTable;
99748 n = 0;
99749 idxCols = 0;
99750 for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){
99751 if( termCanDriveIndex(pTerm, pSrc, notReady) ){
99752 int iCol = pTerm->u.leftColumn;
99753 Bitmask cMask = iCol>=BMS ? ((Bitmask)1)<<(BMS-1) : ((Bitmask)1)<<iCol;
99754 if( (idxCols & cMask)==0 ){
99755 Expr *pX = pTerm->pExpr;
99756 idxCols |= cMask;
99757 pIdx->aiColumn[n] = pTerm->u.leftColumn;
99758 pColl = sqlite3BinaryCompareCollSeq(pParse, pX->pLeft, pX->pRight);
99759 pIdx->azColl[n] = ALWAYS(pColl) ? pColl->zName : "BINARY";
99760 n++;
99764 assert( (u32)n==pLevel->plan.nEq );
99766 /* Add additional columns needed to make the automatic index into
99767 ** a covering index */
99768 for(i=0; i<mxBitCol; i++){
99769 if( extraCols & (((Bitmask)1)<<i) ){
99770 pIdx->aiColumn[n] = i;
99771 pIdx->azColl[n] = "BINARY";
99772 n++;
99775 if( pSrc->colUsed & (((Bitmask)1)<<(BMS-1)) ){
99776 for(i=BMS-1; i<pTable->nCol; i++){
99777 pIdx->aiColumn[n] = i;
99778 pIdx->azColl[n] = "BINARY";
99779 n++;
99782 assert( n==nColumn );
99784 /* Create the automatic index */
99785 pKeyinfo = sqlite3IndexKeyinfo(pParse, pIdx);
99786 assert( pLevel->iIdxCur>=0 );
99787 sqlite3VdbeAddOp4(v, OP_OpenAutoindex, pLevel->iIdxCur, nColumn+1, 0,
99788 (char*)pKeyinfo, P4_KEYINFO_HANDOFF);
99789 VdbeComment((v, "for %s", pTable->zName));
99791 /* Fill the automatic index with content */
99792 addrTop = sqlite3VdbeAddOp1(v, OP_Rewind, pLevel->iTabCur);
99793 regRecord = sqlite3GetTempReg(pParse);
99794 sqlite3GenerateIndexKey(pParse, pIdx, pLevel->iTabCur, regRecord, 1);
99795 sqlite3VdbeAddOp2(v, OP_IdxInsert, pLevel->iIdxCur, regRecord);
99796 sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
99797 sqlite3VdbeAddOp2(v, OP_Next, pLevel->iTabCur, addrTop+1);
99798 sqlite3VdbeChangeP5(v, SQLITE_STMTSTATUS_AUTOINDEX);
99799 sqlite3VdbeJumpHere(v, addrTop);
99800 sqlite3ReleaseTempReg(pParse, regRecord);
99802 /* Jump here when skipping the initialization */
99803 sqlite3VdbeJumpHere(v, addrInit);
99805 #endif /* SQLITE_OMIT_AUTOMATIC_INDEX */
99807 #ifndef SQLITE_OMIT_VIRTUALTABLE
99809 ** Allocate and populate an sqlite3_index_info structure. It is the
99810 ** responsibility of the caller to eventually release the structure
99811 ** by passing the pointer returned by this function to sqlite3_free().
99813 static sqlite3_index_info *allocateIndexInfo(
99814 Parse *pParse,
99815 WhereClause *pWC,
99816 struct SrcList_item *pSrc,
99817 ExprList *pOrderBy
99819 int i, j;
99820 int nTerm;
99821 struct sqlite3_index_constraint *pIdxCons;
99822 struct sqlite3_index_orderby *pIdxOrderBy;
99823 struct sqlite3_index_constraint_usage *pUsage;
99824 WhereTerm *pTerm;
99825 int nOrderBy;
99826 sqlite3_index_info *pIdxInfo;
99828 WHERETRACE(("Recomputing index info for %s...\n", pSrc->pTab->zName));
99830 /* Count the number of possible WHERE clause constraints referring
99831 ** to this virtual table */
99832 for(i=nTerm=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
99833 if( pTerm->leftCursor != pSrc->iCursor ) continue;
99834 assert( (pTerm->eOperator&(pTerm->eOperator-1))==0 );
99835 testcase( pTerm->eOperator==WO_IN );
99836 testcase( pTerm->eOperator==WO_ISNULL );
99837 if( pTerm->eOperator & (WO_IN|WO_ISNULL) ) continue;
99838 nTerm++;
99841 /* If the ORDER BY clause contains only columns in the current
99842 ** virtual table then allocate space for the aOrderBy part of
99843 ** the sqlite3_index_info structure.
99845 nOrderBy = 0;
99846 if( pOrderBy ){
99847 for(i=0; i<pOrderBy->nExpr; i++){
99848 Expr *pExpr = pOrderBy->a[i].pExpr;
99849 if( pExpr->op!=TK_COLUMN || pExpr->iTable!=pSrc->iCursor ) break;
99851 if( i==pOrderBy->nExpr ){
99852 nOrderBy = pOrderBy->nExpr;
99856 /* Allocate the sqlite3_index_info structure
99858 pIdxInfo = sqlite3DbMallocZero(pParse->db, sizeof(*pIdxInfo)
99859 + (sizeof(*pIdxCons) + sizeof(*pUsage))*nTerm
99860 + sizeof(*pIdxOrderBy)*nOrderBy );
99861 if( pIdxInfo==0 ){
99862 sqlite3ErrorMsg(pParse, "out of memory");
99863 /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
99864 return 0;
99867 /* Initialize the structure. The sqlite3_index_info structure contains
99868 ** many fields that are declared "const" to prevent xBestIndex from
99869 ** changing them. We have to do some funky casting in order to
99870 ** initialize those fields.
99872 pIdxCons = (struct sqlite3_index_constraint*)&pIdxInfo[1];
99873 pIdxOrderBy = (struct sqlite3_index_orderby*)&pIdxCons[nTerm];
99874 pUsage = (struct sqlite3_index_constraint_usage*)&pIdxOrderBy[nOrderBy];
99875 *(int*)&pIdxInfo->nConstraint = nTerm;
99876 *(int*)&pIdxInfo->nOrderBy = nOrderBy;
99877 *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint = pIdxCons;
99878 *(struct sqlite3_index_orderby**)&pIdxInfo->aOrderBy = pIdxOrderBy;
99879 *(struct sqlite3_index_constraint_usage**)&pIdxInfo->aConstraintUsage =
99880 pUsage;
99882 for(i=j=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
99883 if( pTerm->leftCursor != pSrc->iCursor ) continue;
99884 assert( (pTerm->eOperator&(pTerm->eOperator-1))==0 );
99885 testcase( pTerm->eOperator==WO_IN );
99886 testcase( pTerm->eOperator==WO_ISNULL );
99887 if( pTerm->eOperator & (WO_IN|WO_ISNULL) ) continue;
99888 pIdxCons[j].iColumn = pTerm->u.leftColumn;
99889 pIdxCons[j].iTermOffset = i;
99890 pIdxCons[j].op = (u8)pTerm->eOperator;
99891 /* The direct assignment in the previous line is possible only because
99892 ** the WO_ and SQLITE_INDEX_CONSTRAINT_ codes are identical. The
99893 ** following asserts verify this fact. */
99894 assert( WO_EQ==SQLITE_INDEX_CONSTRAINT_EQ );
99895 assert( WO_LT==SQLITE_INDEX_CONSTRAINT_LT );
99896 assert( WO_LE==SQLITE_INDEX_CONSTRAINT_LE );
99897 assert( WO_GT==SQLITE_INDEX_CONSTRAINT_GT );
99898 assert( WO_GE==SQLITE_INDEX_CONSTRAINT_GE );
99899 assert( WO_MATCH==SQLITE_INDEX_CONSTRAINT_MATCH );
99900 assert( pTerm->eOperator & (WO_EQ|WO_LT|WO_LE|WO_GT|WO_GE|WO_MATCH) );
99901 j++;
99903 for(i=0; i<nOrderBy; i++){
99904 Expr *pExpr = pOrderBy->a[i].pExpr;
99905 pIdxOrderBy[i].iColumn = pExpr->iColumn;
99906 pIdxOrderBy[i].desc = pOrderBy->a[i].sortOrder;
99909 return pIdxInfo;
99913 ** The table object reference passed as the second argument to this function
99914 ** must represent a virtual table. This function invokes the xBestIndex()
99915 ** method of the virtual table with the sqlite3_index_info pointer passed
99916 ** as the argument.
99918 ** If an error occurs, pParse is populated with an error message and a
99919 ** non-zero value is returned. Otherwise, 0 is returned and the output
99920 ** part of the sqlite3_index_info structure is left populated.
99922 ** Whether or not an error is returned, it is the responsibility of the
99923 ** caller to eventually free p->idxStr if p->needToFreeIdxStr indicates
99924 ** that this is required.
99926 static int vtabBestIndex(Parse *pParse, Table *pTab, sqlite3_index_info *p){
99927 sqlite3_vtab *pVtab = sqlite3GetVTable(pParse->db, pTab)->pVtab;
99928 int i;
99929 int rc;
99931 WHERETRACE(("xBestIndex for %s\n", pTab->zName));
99932 TRACE_IDX_INPUTS(p);
99933 rc = pVtab->pModule->xBestIndex(pVtab, p);
99934 TRACE_IDX_OUTPUTS(p);
99936 if( rc!=SQLITE_OK ){
99937 if( rc==SQLITE_NOMEM ){
99938 pParse->db->mallocFailed = 1;
99939 }else if( !pVtab->zErrMsg ){
99940 sqlite3ErrorMsg(pParse, "%s", sqlite3ErrStr(rc));
99941 }else{
99942 sqlite3ErrorMsg(pParse, "%s", pVtab->zErrMsg);
99945 sqlite3_free(pVtab->zErrMsg);
99946 pVtab->zErrMsg = 0;
99948 for(i=0; i<p->nConstraint; i++){
99949 if( !p->aConstraint[i].usable && p->aConstraintUsage[i].argvIndex>0 ){
99950 sqlite3ErrorMsg(pParse,
99951 "table %s: xBestIndex returned an invalid plan", pTab->zName);
99955 return pParse->nErr;
99960 ** Compute the best index for a virtual table.
99962 ** The best index is computed by the xBestIndex method of the virtual
99963 ** table module. This routine is really just a wrapper that sets up
99964 ** the sqlite3_index_info structure that is used to communicate with
99965 ** xBestIndex.
99967 ** In a join, this routine might be called multiple times for the
99968 ** same virtual table. The sqlite3_index_info structure is created
99969 ** and initialized on the first invocation and reused on all subsequent
99970 ** invocations. The sqlite3_index_info structure is also used when
99971 ** code is generated to access the virtual table. The whereInfoDelete()
99972 ** routine takes care of freeing the sqlite3_index_info structure after
99973 ** everybody has finished with it.
99975 static void bestVirtualIndex(
99976 Parse *pParse, /* The parsing context */
99977 WhereClause *pWC, /* The WHERE clause */
99978 struct SrcList_item *pSrc, /* The FROM clause term to search */
99979 Bitmask notReady, /* Mask of cursors not available for index */
99980 Bitmask notValid, /* Cursors not valid for any purpose */
99981 ExprList *pOrderBy, /* The order by clause */
99982 WhereCost *pCost, /* Lowest cost query plan */
99983 sqlite3_index_info **ppIdxInfo /* Index information passed to xBestIndex */
99985 Table *pTab = pSrc->pTab;
99986 sqlite3_index_info *pIdxInfo;
99987 struct sqlite3_index_constraint *pIdxCons;
99988 struct sqlite3_index_constraint_usage *pUsage;
99989 WhereTerm *pTerm;
99990 int i, j;
99991 int nOrderBy;
99992 double rCost;
99994 /* Make sure wsFlags is initialized to some sane value. Otherwise, if the
99995 ** malloc in allocateIndexInfo() fails and this function returns leaving
99996 ** wsFlags in an uninitialized state, the caller may behave unpredictably.
99998 memset(pCost, 0, sizeof(*pCost));
99999 pCost->plan.wsFlags = WHERE_VIRTUALTABLE;
100001 /* If the sqlite3_index_info structure has not been previously
100002 ** allocated and initialized, then allocate and initialize it now.
100004 pIdxInfo = *ppIdxInfo;
100005 if( pIdxInfo==0 ){
100006 *ppIdxInfo = pIdxInfo = allocateIndexInfo(pParse, pWC, pSrc, pOrderBy);
100008 if( pIdxInfo==0 ){
100009 return;
100012 /* At this point, the sqlite3_index_info structure that pIdxInfo points
100013 ** to will have been initialized, either during the current invocation or
100014 ** during some prior invocation. Now we just have to customize the
100015 ** details of pIdxInfo for the current invocation and pass it to
100016 ** xBestIndex.
100019 /* The module name must be defined. Also, by this point there must
100020 ** be a pointer to an sqlite3_vtab structure. Otherwise
100021 ** sqlite3ViewGetColumnNames() would have picked up the error.
100023 assert( pTab->azModuleArg && pTab->azModuleArg[0] );
100024 assert( sqlite3GetVTable(pParse->db, pTab) );
100026 /* Set the aConstraint[].usable fields and initialize all
100027 ** output variables to zero.
100029 ** aConstraint[].usable is true for constraints where the right-hand
100030 ** side contains only references to tables to the left of the current
100031 ** table. In other words, if the constraint is of the form:
100033 ** column = expr
100035 ** and we are evaluating a join, then the constraint on column is
100036 ** only valid if all tables referenced in expr occur to the left
100037 ** of the table containing column.
100039 ** The aConstraints[] array contains entries for all constraints
100040 ** on the current table. That way we only have to compute it once
100041 ** even though we might try to pick the best index multiple times.
100042 ** For each attempt at picking an index, the order of tables in the
100043 ** join might be different so we have to recompute the usable flag
100044 ** each time.
100046 pIdxCons = *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint;
100047 pUsage = pIdxInfo->aConstraintUsage;
100048 for(i=0; i<pIdxInfo->nConstraint; i++, pIdxCons++){
100049 j = pIdxCons->iTermOffset;
100050 pTerm = &pWC->a[j];
100051 pIdxCons->usable = (pTerm->prereqRight&notReady) ? 0 : 1;
100053 memset(pUsage, 0, sizeof(pUsage[0])*pIdxInfo->nConstraint);
100054 if( pIdxInfo->needToFreeIdxStr ){
100055 sqlite3_free(pIdxInfo->idxStr);
100057 pIdxInfo->idxStr = 0;
100058 pIdxInfo->idxNum = 0;
100059 pIdxInfo->needToFreeIdxStr = 0;
100060 pIdxInfo->orderByConsumed = 0;
100061 /* ((double)2) In case of SQLITE_OMIT_FLOATING_POINT... */
100062 pIdxInfo->estimatedCost = SQLITE_BIG_DBL / ((double)2);
100063 nOrderBy = pIdxInfo->nOrderBy;
100064 if( !pOrderBy ){
100065 pIdxInfo->nOrderBy = 0;
100068 if( vtabBestIndex(pParse, pTab, pIdxInfo) ){
100069 return;
100072 pIdxCons = *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint;
100073 for(i=0; i<pIdxInfo->nConstraint; i++){
100074 if( pUsage[i].argvIndex>0 ){
100075 pCost->used |= pWC->a[pIdxCons[i].iTermOffset].prereqRight;
100079 /* If there is an ORDER BY clause, and the selected virtual table index
100080 ** does not satisfy it, increase the cost of the scan accordingly. This
100081 ** matches the processing for non-virtual tables in bestBtreeIndex().
100083 rCost = pIdxInfo->estimatedCost;
100084 if( pOrderBy && pIdxInfo->orderByConsumed==0 ){
100085 rCost += estLog(rCost)*rCost;
100088 /* The cost is not allowed to be larger than SQLITE_BIG_DBL (the
100089 ** inital value of lowestCost in this loop. If it is, then the
100090 ** (cost<lowestCost) test below will never be true.
100092 ** Use "(double)2" instead of "2.0" in case OMIT_FLOATING_POINT
100093 ** is defined.
100095 if( (SQLITE_BIG_DBL/((double)2))<rCost ){
100096 pCost->rCost = (SQLITE_BIG_DBL/((double)2));
100097 }else{
100098 pCost->rCost = rCost;
100100 pCost->plan.u.pVtabIdx = pIdxInfo;
100101 if( pIdxInfo->orderByConsumed ){
100102 pCost->plan.wsFlags |= WHERE_ORDERBY;
100104 pCost->plan.nEq = 0;
100105 pIdxInfo->nOrderBy = nOrderBy;
100107 /* Try to find a more efficient access pattern by using multiple indexes
100108 ** to optimize an OR expression within the WHERE clause.
100110 bestOrClauseIndex(pParse, pWC, pSrc, notReady, notValid, pOrderBy, pCost);
100112 #endif /* SQLITE_OMIT_VIRTUALTABLE */
100115 ** Argument pIdx is a pointer to an index structure that has an array of
100116 ** SQLITE_INDEX_SAMPLES evenly spaced samples of the first indexed column
100117 ** stored in Index.aSample. These samples divide the domain of values stored
100118 ** the index into (SQLITE_INDEX_SAMPLES+1) regions.
100119 ** Region 0 contains all values less than the first sample value. Region
100120 ** 1 contains values between the first and second samples. Region 2 contains
100121 ** values between samples 2 and 3. And so on. Region SQLITE_INDEX_SAMPLES
100122 ** contains values larger than the last sample.
100124 ** If the index contains many duplicates of a single value, then it is
100125 ** possible that two or more adjacent samples can hold the same value.
100126 ** When that is the case, the smallest possible region code is returned
100127 ** when roundUp is false and the largest possible region code is returned
100128 ** when roundUp is true.
100130 ** If successful, this function determines which of the regions value
100131 ** pVal lies in, sets *piRegion to the region index (a value between 0
100132 ** and SQLITE_INDEX_SAMPLES+1, inclusive) and returns SQLITE_OK.
100133 ** Or, if an OOM occurs while converting text values between encodings,
100134 ** SQLITE_NOMEM is returned and *piRegion is undefined.
100136 #ifdef SQLITE_ENABLE_STAT2
100137 static int whereRangeRegion(
100138 Parse *pParse, /* Database connection */
100139 Index *pIdx, /* Index to consider domain of */
100140 sqlite3_value *pVal, /* Value to consider */
100141 int roundUp, /* Return largest valid region if true */
100142 int *piRegion /* OUT: Region of domain in which value lies */
100144 assert( roundUp==0 || roundUp==1 );
100145 if( ALWAYS(pVal) ){
100146 IndexSample *aSample = pIdx->aSample;
100147 int i = 0;
100148 int eType = sqlite3_value_type(pVal);
100150 if( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT ){
100151 double r = sqlite3_value_double(pVal);
100152 for(i=0; i<SQLITE_INDEX_SAMPLES; i++){
100153 if( aSample[i].eType==SQLITE_NULL ) continue;
100154 if( aSample[i].eType>=SQLITE_TEXT ) break;
100155 if( roundUp ){
100156 if( aSample[i].u.r>r ) break;
100157 }else{
100158 if( aSample[i].u.r>=r ) break;
100161 }else if( eType==SQLITE_NULL ){
100162 i = 0;
100163 if( roundUp ){
100164 while( i<SQLITE_INDEX_SAMPLES && aSample[i].eType==SQLITE_NULL ) i++;
100166 }else{
100167 sqlite3 *db = pParse->db;
100168 CollSeq *pColl;
100169 const u8 *z;
100170 int n;
100172 /* pVal comes from sqlite3ValueFromExpr() so the type cannot be NULL */
100173 assert( eType==SQLITE_TEXT || eType==SQLITE_BLOB );
100175 if( eType==SQLITE_BLOB ){
100176 z = (const u8 *)sqlite3_value_blob(pVal);
100177 pColl = db->pDfltColl;
100178 assert( pColl->enc==SQLITE_UTF8 );
100179 }else{
100180 pColl = sqlite3GetCollSeq(db, SQLITE_UTF8, 0, *pIdx->azColl);
100181 if( pColl==0 ){
100182 sqlite3ErrorMsg(pParse, "no such collation sequence: %s",
100183 *pIdx->azColl);
100184 return SQLITE_ERROR;
100186 z = (const u8 *)sqlite3ValueText(pVal, pColl->enc);
100187 if( !z ){
100188 return SQLITE_NOMEM;
100190 assert( z && pColl && pColl->xCmp );
100192 n = sqlite3ValueBytes(pVal, pColl->enc);
100194 for(i=0; i<SQLITE_INDEX_SAMPLES; i++){
100195 int c;
100196 int eSampletype = aSample[i].eType;
100197 if( eSampletype==SQLITE_NULL || eSampletype<eType ) continue;
100198 if( (eSampletype!=eType) ) break;
100199 #ifndef SQLITE_OMIT_UTF16
100200 if( pColl->enc!=SQLITE_UTF8 ){
100201 int nSample;
100202 char *zSample = sqlite3Utf8to16(
100203 db, pColl->enc, aSample[i].u.z, aSample[i].nByte, &nSample
100205 if( !zSample ){
100206 assert( db->mallocFailed );
100207 return SQLITE_NOMEM;
100209 c = pColl->xCmp(pColl->pUser, nSample, zSample, n, z);
100210 sqlite3DbFree(db, zSample);
100211 }else
100212 #endif
100214 c = pColl->xCmp(pColl->pUser, aSample[i].nByte, aSample[i].u.z, n, z);
100216 if( c-roundUp>=0 ) break;
100220 assert( i>=0 && i<=SQLITE_INDEX_SAMPLES );
100221 *piRegion = i;
100223 return SQLITE_OK;
100225 #endif /* #ifdef SQLITE_ENABLE_STAT2 */
100228 ** If expression pExpr represents a literal value, set *pp to point to
100229 ** an sqlite3_value structure containing the same value, with affinity
100230 ** aff applied to it, before returning. It is the responsibility of the
100231 ** caller to eventually release this structure by passing it to
100232 ** sqlite3ValueFree().
100234 ** If the current parse is a recompile (sqlite3Reprepare()) and pExpr
100235 ** is an SQL variable that currently has a non-NULL value bound to it,
100236 ** create an sqlite3_value structure containing this value, again with
100237 ** affinity aff applied to it, instead.
100239 ** If neither of the above apply, set *pp to NULL.
100241 ** If an error occurs, return an error code. Otherwise, SQLITE_OK.
100243 #ifdef SQLITE_ENABLE_STAT2
100244 static int valueFromExpr(
100245 Parse *pParse,
100246 Expr *pExpr,
100247 u8 aff,
100248 sqlite3_value **pp
100250 if( pExpr->op==TK_VARIABLE
100251 || (pExpr->op==TK_REGISTER && pExpr->op2==TK_VARIABLE)
100253 int iVar = pExpr->iColumn;
100254 sqlite3VdbeSetVarmask(pParse->pVdbe, iVar); /* IMP: R-23257-02778 */
100255 *pp = sqlite3VdbeGetValue(pParse->pReprepare, iVar, aff);
100256 return SQLITE_OK;
100258 return sqlite3ValueFromExpr(pParse->db, pExpr, SQLITE_UTF8, aff, pp);
100260 #endif
100263 ** This function is used to estimate the number of rows that will be visited
100264 ** by scanning an index for a range of values. The range may have an upper
100265 ** bound, a lower bound, or both. The WHERE clause terms that set the upper
100266 ** and lower bounds are represented by pLower and pUpper respectively. For
100267 ** example, assuming that index p is on t1(a):
100269 ** ... FROM t1 WHERE a > ? AND a < ? ...
100270 ** |_____| |_____|
100271 ** | |
100272 ** pLower pUpper
100274 ** If either of the upper or lower bound is not present, then NULL is passed in
100275 ** place of the corresponding WhereTerm.
100277 ** The nEq parameter is passed the index of the index column subject to the
100278 ** range constraint. Or, equivalently, the number of equality constraints
100279 ** optimized by the proposed index scan. For example, assuming index p is
100280 ** on t1(a, b), and the SQL query is:
100282 ** ... FROM t1 WHERE a = ? AND b > ? AND b < ? ...
100284 ** then nEq should be passed the value 1 (as the range restricted column,
100285 ** b, is the second left-most column of the index). Or, if the query is:
100287 ** ... FROM t1 WHERE a > ? AND a < ? ...
100289 ** then nEq should be passed 0.
100291 ** The returned value is an integer between 1 and 100, inclusive. A return
100292 ** value of 1 indicates that the proposed range scan is expected to visit
100293 ** approximately 1/100th (1%) of the rows selected by the nEq equality
100294 ** constraints (if any). A return value of 100 indicates that it is expected
100295 ** that the range scan will visit every row (100%) selected by the equality
100296 ** constraints.
100298 ** In the absence of sqlite_stat2 ANALYZE data, each range inequality
100299 ** reduces the search space by 3/4ths. Hence a single constraint (x>?)
100300 ** results in a return of 25 and a range constraint (x>? AND x<?) results
100301 ** in a return of 6.
100303 static int whereRangeScanEst(
100304 Parse *pParse, /* Parsing & code generating context */
100305 Index *p, /* The index containing the range-compared column; "x" */
100306 int nEq, /* index into p->aCol[] of the range-compared column */
100307 WhereTerm *pLower, /* Lower bound on the range. ex: "x>123" Might be NULL */
100308 WhereTerm *pUpper, /* Upper bound on the range. ex: "x<455" Might be NULL */
100309 int *piEst /* OUT: Return value */
100311 int rc = SQLITE_OK;
100313 #ifdef SQLITE_ENABLE_STAT2
100315 if( nEq==0 && p->aSample ){
100316 sqlite3_value *pLowerVal = 0;
100317 sqlite3_value *pUpperVal = 0;
100318 int iEst;
100319 int iLower = 0;
100320 int iUpper = SQLITE_INDEX_SAMPLES;
100321 int roundUpUpper = 0;
100322 int roundUpLower = 0;
100323 u8 aff = p->pTable->aCol[p->aiColumn[0]].affinity;
100325 if( pLower ){
100326 Expr *pExpr = pLower->pExpr->pRight;
100327 rc = valueFromExpr(pParse, pExpr, aff, &pLowerVal);
100328 assert( pLower->eOperator==WO_GT || pLower->eOperator==WO_GE );
100329 roundUpLower = (pLower->eOperator==WO_GT) ?1:0;
100331 if( rc==SQLITE_OK && pUpper ){
100332 Expr *pExpr = pUpper->pExpr->pRight;
100333 rc = valueFromExpr(pParse, pExpr, aff, &pUpperVal);
100334 assert( pUpper->eOperator==WO_LT || pUpper->eOperator==WO_LE );
100335 roundUpUpper = (pUpper->eOperator==WO_LE) ?1:0;
100338 if( rc!=SQLITE_OK || (pLowerVal==0 && pUpperVal==0) ){
100339 sqlite3ValueFree(pLowerVal);
100340 sqlite3ValueFree(pUpperVal);
100341 goto range_est_fallback;
100342 }else if( pLowerVal==0 ){
100343 rc = whereRangeRegion(pParse, p, pUpperVal, roundUpUpper, &iUpper);
100344 if( pLower ) iLower = iUpper/2;
100345 }else if( pUpperVal==0 ){
100346 rc = whereRangeRegion(pParse, p, pLowerVal, roundUpLower, &iLower);
100347 if( pUpper ) iUpper = (iLower + SQLITE_INDEX_SAMPLES + 1)/2;
100348 }else{
100349 rc = whereRangeRegion(pParse, p, pUpperVal, roundUpUpper, &iUpper);
100350 if( rc==SQLITE_OK ){
100351 rc = whereRangeRegion(pParse, p, pLowerVal, roundUpLower, &iLower);
100354 WHERETRACE(("range scan regions: %d..%d\n", iLower, iUpper));
100356 iEst = iUpper - iLower;
100357 testcase( iEst==SQLITE_INDEX_SAMPLES );
100358 assert( iEst<=SQLITE_INDEX_SAMPLES );
100359 if( iEst<1 ){
100360 *piEst = 50/SQLITE_INDEX_SAMPLES;
100361 }else{
100362 *piEst = (iEst*100)/SQLITE_INDEX_SAMPLES;
100364 sqlite3ValueFree(pLowerVal);
100365 sqlite3ValueFree(pUpperVal);
100366 return rc;
100368 range_est_fallback:
100369 #else
100370 UNUSED_PARAMETER(pParse);
100371 UNUSED_PARAMETER(p);
100372 UNUSED_PARAMETER(nEq);
100373 #endif
100374 assert( pLower || pUpper );
100375 *piEst = 100;
100376 if( pLower && (pLower->wtFlags & TERM_VNULL)==0 ) *piEst /= 4;
100377 if( pUpper ) *piEst /= 4;
100378 return rc;
100381 #ifdef SQLITE_ENABLE_STAT2
100383 ** Estimate the number of rows that will be returned based on
100384 ** an equality constraint x=VALUE and where that VALUE occurs in
100385 ** the histogram data. This only works when x is the left-most
100386 ** column of an index and sqlite_stat2 histogram data is available
100387 ** for that index. When pExpr==NULL that means the constraint is
100388 ** "x IS NULL" instead of "x=VALUE".
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 whereEqualScanEst(
100400 Parse *pParse, /* Parsing & code generating context */
100401 Index *p, /* The index whose left-most column is pTerm */
100402 Expr *pExpr, /* Expression for VALUE in the x=VALUE constraint */
100403 double *pnRow /* Write the revised row estimate here */
100405 sqlite3_value *pRhs = 0; /* VALUE on right-hand side of pTerm */
100406 int iLower, iUpper; /* Range of histogram regions containing pRhs */
100407 u8 aff; /* Column affinity */
100408 int rc; /* Subfunction return code */
100409 double nRowEst; /* New estimate of the number of rows */
100411 assert( p->aSample!=0 );
100412 aff = p->pTable->aCol[p->aiColumn[0]].affinity;
100413 if( pExpr ){
100414 rc = valueFromExpr(pParse, pExpr, aff, &pRhs);
100415 if( rc ) goto whereEqualScanEst_cancel;
100416 }else{
100417 pRhs = sqlite3ValueNew(pParse->db);
100419 if( pRhs==0 ) return SQLITE_NOTFOUND;
100420 rc = whereRangeRegion(pParse, p, pRhs, 0, &iLower);
100421 if( rc ) goto whereEqualScanEst_cancel;
100422 rc = whereRangeRegion(pParse, p, pRhs, 1, &iUpper);
100423 if( rc ) goto whereEqualScanEst_cancel;
100424 WHERETRACE(("equality scan regions: %d..%d\n", iLower, iUpper));
100425 if( iLower>=iUpper ){
100426 nRowEst = p->aiRowEst[0]/(SQLITE_INDEX_SAMPLES*2);
100427 if( nRowEst<*pnRow ) *pnRow = nRowEst;
100428 }else{
100429 nRowEst = (iUpper-iLower)*p->aiRowEst[0]/SQLITE_INDEX_SAMPLES;
100430 *pnRow = nRowEst;
100433 whereEqualScanEst_cancel:
100434 sqlite3ValueFree(pRhs);
100435 return rc;
100437 #endif /* defined(SQLITE_ENABLE_STAT2) */
100439 #ifdef SQLITE_ENABLE_STAT2
100441 ** Estimate the number of rows that will be returned based on
100442 ** an IN constraint where the right-hand side of the IN operator
100443 ** is a list of values. Example:
100445 ** WHERE x IN (1,2,3,4)
100447 ** Write the estimated row count into *pnRow and return SQLITE_OK.
100448 ** If unable to make an estimate, leave *pnRow unchanged and return
100449 ** non-zero.
100451 ** This routine can fail if it is unable to load a collating sequence
100452 ** required for string comparison, or if unable to allocate memory
100453 ** for a UTF conversion required for comparison. The error is stored
100454 ** in the pParse structure.
100456 static int whereInScanEst(
100457 Parse *pParse, /* Parsing & code generating context */
100458 Index *p, /* The index whose left-most column is pTerm */
100459 ExprList *pList, /* The value list on the RHS of "x IN (v1,v2,v3,...)" */
100460 double *pnRow /* Write the revised row estimate here */
100462 sqlite3_value *pVal = 0; /* One value from list */
100463 int iLower, iUpper; /* Range of histogram regions containing pRhs */
100464 u8 aff; /* Column affinity */
100465 int rc = SQLITE_OK; /* Subfunction return code */
100466 double nRowEst; /* New estimate of the number of rows */
100467 int nSpan = 0; /* Number of histogram regions spanned */
100468 int nSingle = 0; /* Histogram regions hit by a single value */
100469 int nNotFound = 0; /* Count of values that are not constants */
100470 int i; /* Loop counter */
100471 u8 aSpan[SQLITE_INDEX_SAMPLES+1]; /* Histogram regions that are spanned */
100472 u8 aSingle[SQLITE_INDEX_SAMPLES+1]; /* Histogram regions hit once */
100474 assert( p->aSample!=0 );
100475 aff = p->pTable->aCol[p->aiColumn[0]].affinity;
100476 memset(aSpan, 0, sizeof(aSpan));
100477 memset(aSingle, 0, sizeof(aSingle));
100478 for(i=0; i<pList->nExpr; i++){
100479 sqlite3ValueFree(pVal);
100480 rc = valueFromExpr(pParse, pList->a[i].pExpr, aff, &pVal);
100481 if( rc ) break;
100482 if( pVal==0 || sqlite3_value_type(pVal)==SQLITE_NULL ){
100483 nNotFound++;
100484 continue;
100486 rc = whereRangeRegion(pParse, p, pVal, 0, &iLower);
100487 if( rc ) break;
100488 rc = whereRangeRegion(pParse, p, pVal, 1, &iUpper);
100489 if( rc ) break;
100490 if( iLower>=iUpper ){
100491 aSingle[iLower] = 1;
100492 }else{
100493 assert( iLower>=0 && iUpper<=SQLITE_INDEX_SAMPLES );
100494 while( iLower<iUpper ) aSpan[iLower++] = 1;
100497 if( rc==SQLITE_OK ){
100498 for(i=nSpan=0; i<=SQLITE_INDEX_SAMPLES; i++){
100499 if( aSpan[i] ){
100500 nSpan++;
100501 }else if( aSingle[i] ){
100502 nSingle++;
100505 nRowEst = (nSpan*2+nSingle)*p->aiRowEst[0]/(2*SQLITE_INDEX_SAMPLES)
100506 + nNotFound*p->aiRowEst[1];
100507 if( nRowEst > p->aiRowEst[0] ) nRowEst = p->aiRowEst[0];
100508 *pnRow = nRowEst;
100509 WHERETRACE(("IN row estimate: nSpan=%d, nSingle=%d, nNotFound=%d, est=%g\n",
100510 nSpan, nSingle, nNotFound, nRowEst));
100512 sqlite3ValueFree(pVal);
100513 return rc;
100515 #endif /* defined(SQLITE_ENABLE_STAT2) */
100519 ** Find the best query plan for accessing a particular table. Write the
100520 ** best query plan and its cost into the WhereCost object supplied as the
100521 ** last parameter.
100523 ** The lowest cost plan wins. The cost is an estimate of the amount of
100524 ** CPU and disk I/O needed to process the requested result.
100525 ** Factors that influence cost include:
100527 ** * The estimated number of rows that will be retrieved. (The
100528 ** fewer the better.)
100530 ** * Whether or not sorting must occur.
100532 ** * Whether or not there must be separate lookups in the
100533 ** index and in the main table.
100535 ** If there was an INDEXED BY clause (pSrc->pIndex) attached to the table in
100536 ** the SQL statement, then this function only considers plans using the
100537 ** named index. If no such plan is found, then the returned cost is
100538 ** SQLITE_BIG_DBL. If a plan is found that uses the named index,
100539 ** then the cost is calculated in the usual way.
100541 ** If a NOT INDEXED clause (pSrc->notIndexed!=0) was attached to the table
100542 ** in the SELECT statement, then no indexes are considered. However, the
100543 ** selected plan may still take advantage of the built-in rowid primary key
100544 ** index.
100546 static void bestBtreeIndex(
100547 Parse *pParse, /* The parsing context */
100548 WhereClause *pWC, /* The WHERE clause */
100549 struct SrcList_item *pSrc, /* The FROM clause term to search */
100550 Bitmask notReady, /* Mask of cursors not available for indexing */
100551 Bitmask notValid, /* Cursors not available for any purpose */
100552 ExprList *pOrderBy, /* The ORDER BY clause */
100553 WhereCost *pCost /* Lowest cost query plan */
100555 int iCur = pSrc->iCursor; /* The cursor of the table to be accessed */
100556 Index *pProbe; /* An index we are evaluating */
100557 Index *pIdx; /* Copy of pProbe, or zero for IPK index */
100558 int eqTermMask; /* Current mask of valid equality operators */
100559 int idxEqTermMask; /* Index mask of valid equality operators */
100560 Index sPk; /* A fake index object for the primary key */
100561 unsigned int aiRowEstPk[2]; /* The aiRowEst[] value for the sPk index */
100562 int aiColumnPk = -1; /* The aColumn[] value for the sPk index */
100563 int wsFlagMask; /* Allowed flags in pCost->plan.wsFlag */
100565 /* Initialize the cost to a worst-case value */
100566 memset(pCost, 0, sizeof(*pCost));
100567 pCost->rCost = SQLITE_BIG_DBL;
100569 /* If the pSrc table is the right table of a LEFT JOIN then we may not
100570 ** use an index to satisfy IS NULL constraints on that table. This is
100571 ** because columns might end up being NULL if the table does not match -
100572 ** a circumstance which the index cannot help us discover. Ticket #2177.
100574 if( pSrc->jointype & JT_LEFT ){
100575 idxEqTermMask = WO_EQ|WO_IN;
100576 }else{
100577 idxEqTermMask = WO_EQ|WO_IN|WO_ISNULL;
100580 if( pSrc->pIndex ){
100581 /* An INDEXED BY clause specifies a particular index to use */
100582 pIdx = pProbe = pSrc->pIndex;
100583 wsFlagMask = ~(WHERE_ROWID_EQ|WHERE_ROWID_RANGE);
100584 eqTermMask = idxEqTermMask;
100585 }else{
100586 /* There is no INDEXED BY clause. Create a fake Index object in local
100587 ** variable sPk to represent the rowid primary key index. Make this
100588 ** fake index the first in a chain of Index objects with all of the real
100589 ** indices to follow */
100590 Index *pFirst; /* First of real indices on the table */
100591 memset(&sPk, 0, sizeof(Index));
100592 sPk.nColumn = 1;
100593 sPk.aiColumn = &aiColumnPk;
100594 sPk.aiRowEst = aiRowEstPk;
100595 sPk.onError = OE_Replace;
100596 sPk.pTable = pSrc->pTab;
100597 aiRowEstPk[0] = pSrc->pTab->nRowEst;
100598 aiRowEstPk[1] = 1;
100599 pFirst = pSrc->pTab->pIndex;
100600 if( pSrc->notIndexed==0 ){
100601 /* The real indices of the table are only considered if the
100602 ** NOT INDEXED qualifier is omitted from the FROM clause */
100603 sPk.pNext = pFirst;
100605 pProbe = &sPk;
100606 wsFlagMask = ~(
100607 WHERE_COLUMN_IN|WHERE_COLUMN_EQ|WHERE_COLUMN_NULL|WHERE_COLUMN_RANGE
100609 eqTermMask = WO_EQ|WO_IN;
100610 pIdx = 0;
100613 /* Loop over all indices looking for the best one to use
100615 for(; pProbe; pIdx=pProbe=pProbe->pNext){
100616 const unsigned int * const aiRowEst = pProbe->aiRowEst;
100617 double cost; /* Cost of using pProbe */
100618 double nRow; /* Estimated number of rows in result set */
100619 double log10N; /* base-10 logarithm of nRow (inexact) */
100620 int rev; /* True to scan in reverse order */
100621 int wsFlags = 0;
100622 Bitmask used = 0;
100624 /* The following variables are populated based on the properties of
100625 ** index being evaluated. They are then used to determine the expected
100626 ** cost and number of rows returned.
100628 ** nEq:
100629 ** Number of equality terms that can be implemented using the index.
100630 ** In other words, the number of initial fields in the index that
100631 ** are used in == or IN or NOT NULL constraints of the WHERE clause.
100633 ** nInMul:
100634 ** The "in-multiplier". This is an estimate of how many seek operations
100635 ** SQLite must perform on the index in question. For example, if the
100636 ** WHERE clause is:
100638 ** WHERE a IN (1, 2, 3) AND b IN (4, 5, 6)
100640 ** SQLite must perform 9 lookups on an index on (a, b), so nInMul is
100641 ** set to 9. Given the same schema and either of the following WHERE
100642 ** clauses:
100644 ** WHERE a = 1
100645 ** WHERE a >= 2
100647 ** nInMul is set to 1.
100649 ** If there exists a WHERE term of the form "x IN (SELECT ...)", then
100650 ** the sub-select is assumed to return 25 rows for the purposes of
100651 ** determining nInMul.
100653 ** bInEst:
100654 ** Set to true if there was at least one "x IN (SELECT ...)" term used
100655 ** in determining the value of nInMul. Note that the RHS of the
100656 ** IN operator must be a SELECT, not a value list, for this variable
100657 ** to be true.
100659 ** estBound:
100660 ** An estimate on the amount of the table that must be searched. A
100661 ** value of 100 means the entire table is searched. Range constraints
100662 ** might reduce this to a value less than 100 to indicate that only
100663 ** a fraction of the table needs searching. In the absence of
100664 ** sqlite_stat2 ANALYZE data, a single inequality reduces the search
100665 ** space to 1/4rd its original size. So an x>? constraint reduces
100666 ** estBound to 25. Two constraints (x>? AND x<?) reduce estBound to 6.
100668 ** bSort:
100669 ** Boolean. True if there is an ORDER BY clause that will require an
100670 ** external sort (i.e. scanning the index being evaluated will not
100671 ** correctly order records).
100673 ** bLookup:
100674 ** Boolean. True if a table lookup is required for each index entry
100675 ** visited. In other words, true if this is not a covering index.
100676 ** This is always false for the rowid primary key index of a table.
100677 ** For other indexes, it is true unless all the columns of the table
100678 ** used by the SELECT statement are present in the index (such an
100679 ** index is sometimes described as a covering index).
100680 ** For example, given the index on (a, b), the second of the following
100681 ** two queries requires table b-tree lookups in order to find the value
100682 ** of column c, but the first does not because columns a and b are
100683 ** both available in the index.
100685 ** SELECT a, b FROM tbl WHERE a = 1;
100686 ** SELECT a, b, c FROM tbl WHERE a = 1;
100688 int nEq; /* Number of == or IN terms matching index */
100689 int bInEst = 0; /* True if "x IN (SELECT...)" seen */
100690 int nInMul = 1; /* Number of distinct equalities to lookup */
100691 int estBound = 100; /* Estimated reduction in search space */
100692 int nBound = 0; /* Number of range constraints seen */
100693 int bSort = 0; /* True if external sort required */
100694 int bLookup = 0; /* True if not a covering index */
100695 WhereTerm *pTerm; /* A single term of the WHERE clause */
100696 #ifdef SQLITE_ENABLE_STAT2
100697 WhereTerm *pFirstTerm = 0; /* First term matching the index */
100698 #endif
100700 /* Determine the values of nEq and nInMul */
100701 for(nEq=0; nEq<pProbe->nColumn; nEq++){
100702 int j = pProbe->aiColumn[nEq];
100703 pTerm = findTerm(pWC, iCur, j, notReady, eqTermMask, pIdx);
100704 if( pTerm==0 ) break;
100705 wsFlags |= (WHERE_COLUMN_EQ|WHERE_ROWID_EQ);
100706 if( pTerm->eOperator & WO_IN ){
100707 Expr *pExpr = pTerm->pExpr;
100708 wsFlags |= WHERE_COLUMN_IN;
100709 if( ExprHasProperty(pExpr, EP_xIsSelect) ){
100710 /* "x IN (SELECT ...)": Assume the SELECT returns 25 rows */
100711 nInMul *= 25;
100712 bInEst = 1;
100713 }else if( ALWAYS(pExpr->x.pList && pExpr->x.pList->nExpr) ){
100714 /* "x IN (value, value, ...)" */
100715 nInMul *= pExpr->x.pList->nExpr;
100717 }else if( pTerm->eOperator & WO_ISNULL ){
100718 wsFlags |= WHERE_COLUMN_NULL;
100720 #ifdef SQLITE_ENABLE_STAT2
100721 if( nEq==0 && pProbe->aSample ) pFirstTerm = pTerm;
100722 #endif
100723 used |= pTerm->prereqRight;
100726 /* Determine the value of estBound. */
100727 if( nEq<pProbe->nColumn && pProbe->bUnordered==0 ){
100728 int j = pProbe->aiColumn[nEq];
100729 if( findTerm(pWC, iCur, j, notReady, WO_LT|WO_LE|WO_GT|WO_GE, pIdx) ){
100730 WhereTerm *pTop = findTerm(pWC, iCur, j, notReady, WO_LT|WO_LE, pIdx);
100731 WhereTerm *pBtm = findTerm(pWC, iCur, j, notReady, WO_GT|WO_GE, pIdx);
100732 whereRangeScanEst(pParse, pProbe, nEq, pBtm, pTop, &estBound);
100733 if( pTop ){
100734 nBound = 1;
100735 wsFlags |= WHERE_TOP_LIMIT;
100736 used |= pTop->prereqRight;
100738 if( pBtm ){
100739 nBound++;
100740 wsFlags |= WHERE_BTM_LIMIT;
100741 used |= pBtm->prereqRight;
100743 wsFlags |= (WHERE_COLUMN_RANGE|WHERE_ROWID_RANGE);
100745 }else if( pProbe->onError!=OE_None ){
100746 testcase( wsFlags & WHERE_COLUMN_IN );
100747 testcase( wsFlags & WHERE_COLUMN_NULL );
100748 if( (wsFlags & (WHERE_COLUMN_IN|WHERE_COLUMN_NULL))==0 ){
100749 wsFlags |= WHERE_UNIQUE;
100753 /* If there is an ORDER BY clause and the index being considered will
100754 ** naturally scan rows in the required order, set the appropriate flags
100755 ** in wsFlags. Otherwise, if there is an ORDER BY clause but the index
100756 ** will scan rows in a different order, set the bSort variable. */
100757 if( pOrderBy ){
100758 if( (wsFlags & WHERE_COLUMN_IN)==0
100759 && pProbe->bUnordered==0
100760 && isSortingIndex(pParse, pWC->pMaskSet, pProbe, iCur, pOrderBy,
100761 nEq, wsFlags, &rev)
100763 wsFlags |= WHERE_ROWID_RANGE|WHERE_COLUMN_RANGE|WHERE_ORDERBY;
100764 wsFlags |= (rev ? WHERE_REVERSE : 0);
100765 }else{
100766 bSort = 1;
100770 /* If currently calculating the cost of using an index (not the IPK
100771 ** index), determine if all required column data may be obtained without
100772 ** using the main table (i.e. if the index is a covering
100773 ** index for this query). If it is, set the WHERE_IDX_ONLY flag in
100774 ** wsFlags. Otherwise, set the bLookup variable to true. */
100775 if( pIdx && wsFlags ){
100776 Bitmask m = pSrc->colUsed;
100777 int j;
100778 for(j=0; j<pIdx->nColumn; j++){
100779 int x = pIdx->aiColumn[j];
100780 if( x<BMS-1 ){
100781 m &= ~(((Bitmask)1)<<x);
100784 if( m==0 ){
100785 wsFlags |= WHERE_IDX_ONLY;
100786 }else{
100787 bLookup = 1;
100792 ** Estimate the number of rows of output. For an "x IN (SELECT...)"
100793 ** constraint, do not let the estimate exceed half the rows in the table.
100795 nRow = (double)(aiRowEst[nEq] * nInMul);
100796 if( bInEst && nRow*2>aiRowEst[0] ){
100797 nRow = aiRowEst[0]/2;
100798 nInMul = (int)(nRow / aiRowEst[nEq]);
100801 #ifdef SQLITE_ENABLE_STAT2
100802 /* If the constraint is of the form x=VALUE and histogram
100803 ** data is available for column x, then it might be possible
100804 ** to get a better estimate on the number of rows based on
100805 ** VALUE and how common that value is according to the histogram.
100807 if( nRow>(double)1 && nEq==1 && pFirstTerm!=0 ){
100808 if( pFirstTerm->eOperator & (WO_EQ|WO_ISNULL) ){
100809 testcase( pFirstTerm->eOperator==WO_EQ );
100810 testcase( pFirstTerm->eOperator==WO_ISNULL );
100811 whereEqualScanEst(pParse, pProbe, pFirstTerm->pExpr->pRight, &nRow);
100812 }else if( pFirstTerm->eOperator==WO_IN && bInEst==0 ){
100813 whereInScanEst(pParse, pProbe, pFirstTerm->pExpr->x.pList, &nRow);
100816 #endif /* SQLITE_ENABLE_STAT2 */
100818 /* Adjust the number of output rows and downward to reflect rows
100819 ** that are excluded by range constraints.
100821 nRow = (nRow * (double)estBound) / (double)100;
100822 if( nRow<1 ) nRow = 1;
100824 /* Experiments run on real SQLite databases show that the time needed
100825 ** to do a binary search to locate a row in a table or index is roughly
100826 ** log10(N) times the time to move from one row to the next row within
100827 ** a table or index. The actual times can vary, with the size of
100828 ** records being an important factor. Both moves and searches are
100829 ** slower with larger records, presumably because fewer records fit
100830 ** on one page and hence more pages have to be fetched.
100832 ** The ANALYZE command and the sqlite_stat1 and sqlite_stat2 tables do
100833 ** not give us data on the relative sizes of table and index records.
100834 ** So this computation assumes table records are about twice as big
100835 ** as index records
100837 if( (wsFlags & WHERE_NOT_FULLSCAN)==0 ){
100838 /* The cost of a full table scan is a number of move operations equal
100839 ** to the number of rows in the table.
100841 ** We add an additional 4x penalty to full table scans. This causes
100842 ** the cost function to err on the side of choosing an index over
100843 ** choosing a full scan. This 4x full-scan penalty is an arguable
100844 ** decision and one which we expect to revisit in the future. But
100845 ** it seems to be working well enough at the moment.
100847 cost = aiRowEst[0]*4;
100848 }else{
100849 log10N = estLog(aiRowEst[0]);
100850 cost = nRow;
100851 if( pIdx ){
100852 if( bLookup ){
100853 /* For an index lookup followed by a table lookup:
100854 ** nInMul index searches to find the start of each index range
100855 ** + nRow steps through the index
100856 ** + nRow table searches to lookup the table entry using the rowid
100858 cost += (nInMul + nRow)*log10N;
100859 }else{
100860 /* For a covering index:
100861 ** nInMul index searches to find the initial entry
100862 ** + nRow steps through the index
100864 cost += nInMul*log10N;
100866 }else{
100867 /* For a rowid primary key lookup:
100868 ** nInMult table searches to find the initial entry for each range
100869 ** + nRow steps through the table
100871 cost += nInMul*log10N;
100875 /* Add in the estimated cost of sorting the result. Actual experimental
100876 ** measurements of sorting performance in SQLite show that sorting time
100877 ** adds C*N*log10(N) to the cost, where N is the number of rows to be
100878 ** sorted and C is a factor between 1.95 and 4.3. We will split the
100879 ** difference and select C of 3.0.
100881 if( bSort ){
100882 cost += nRow*estLog(nRow)*3;
100885 /**** Cost of using this index has now been computed ****/
100887 /* If there are additional constraints on this table that cannot
100888 ** be used with the current index, but which might lower the number
100889 ** of output rows, adjust the nRow value accordingly. This only
100890 ** matters if the current index is the least costly, so do not bother
100891 ** with this step if we already know this index will not be chosen.
100892 ** Also, never reduce the output row count below 2 using this step.
100894 ** It is critical that the notValid mask be used here instead of
100895 ** the notReady mask. When computing an "optimal" index, the notReady
100896 ** mask will only have one bit set - the bit for the current table.
100897 ** The notValid mask, on the other hand, always has all bits set for
100898 ** tables that are not in outer loops. If notReady is used here instead
100899 ** of notValid, then a optimal index that depends on inner joins loops
100900 ** might be selected even when there exists an optimal index that has
100901 ** no such dependency.
100903 if( nRow>2 && cost<=pCost->rCost ){
100904 int k; /* Loop counter */
100905 int nSkipEq = nEq; /* Number of == constraints to skip */
100906 int nSkipRange = nBound; /* Number of < constraints to skip */
100907 Bitmask thisTab; /* Bitmap for pSrc */
100909 thisTab = getMask(pWC->pMaskSet, iCur);
100910 for(pTerm=pWC->a, k=pWC->nTerm; nRow>2 && k; k--, pTerm++){
100911 if( pTerm->wtFlags & TERM_VIRTUAL ) continue;
100912 if( (pTerm->prereqAll & notValid)!=thisTab ) continue;
100913 if( pTerm->eOperator & (WO_EQ|WO_IN|WO_ISNULL) ){
100914 if( nSkipEq ){
100915 /* Ignore the first nEq equality matches since the index
100916 ** has already accounted for these */
100917 nSkipEq--;
100918 }else{
100919 /* Assume each additional equality match reduces the result
100920 ** set size by a factor of 10 */
100921 nRow /= 10;
100923 }else if( pTerm->eOperator & (WO_LT|WO_LE|WO_GT|WO_GE) ){
100924 if( nSkipRange ){
100925 /* Ignore the first nSkipRange range constraints since the index
100926 ** has already accounted for these */
100927 nSkipRange--;
100928 }else{
100929 /* Assume each additional range constraint reduces the result
100930 ** set size by a factor of 3. Indexed range constraints reduce
100931 ** the search space by a larger factor: 4. We make indexed range
100932 ** more selective intentionally because of the subjective
100933 ** observation that indexed range constraints really are more
100934 ** selective in practice, on average. */
100935 nRow /= 3;
100937 }else if( pTerm->eOperator!=WO_NOOP ){
100938 /* Any other expression lowers the output row count by half */
100939 nRow /= 2;
100942 if( nRow<2 ) nRow = 2;
100946 WHERETRACE((
100947 "%s(%s): nEq=%d nInMul=%d estBound=%d bSort=%d bLookup=%d wsFlags=0x%x\n"
100948 " notReady=0x%llx log10N=%.1f nRow=%.1f cost=%.1f used=0x%llx\n",
100949 pSrc->pTab->zName, (pIdx ? pIdx->zName : "ipk"),
100950 nEq, nInMul, estBound, bSort, bLookup, wsFlags,
100951 notReady, log10N, nRow, cost, used
100954 /* If this index is the best we have seen so far, then record this
100955 ** index and its cost in the pCost structure.
100957 if( (!pIdx || wsFlags)
100958 && (cost<pCost->rCost || (cost<=pCost->rCost && nRow<pCost->plan.nRow))
100960 pCost->rCost = cost;
100961 pCost->used = used;
100962 pCost->plan.nRow = nRow;
100963 pCost->plan.wsFlags = (wsFlags&wsFlagMask);
100964 pCost->plan.nEq = nEq;
100965 pCost->plan.u.pIdx = pIdx;
100968 /* If there was an INDEXED BY clause, then only that one index is
100969 ** considered. */
100970 if( pSrc->pIndex ) break;
100972 /* Reset masks for the next index in the loop */
100973 wsFlagMask = ~(WHERE_ROWID_EQ|WHERE_ROWID_RANGE);
100974 eqTermMask = idxEqTermMask;
100977 /* If there is no ORDER BY clause and the SQLITE_ReverseOrder flag
100978 ** is set, then reverse the order that the index will be scanned
100979 ** in. This is used for application testing, to help find cases
100980 ** where application behaviour depends on the (undefined) order that
100981 ** SQLite outputs rows in in the absence of an ORDER BY clause. */
100982 if( !pOrderBy && pParse->db->flags & SQLITE_ReverseOrder ){
100983 pCost->plan.wsFlags |= WHERE_REVERSE;
100986 assert( pOrderBy || (pCost->plan.wsFlags&WHERE_ORDERBY)==0 );
100987 assert( pCost->plan.u.pIdx==0 || (pCost->plan.wsFlags&WHERE_ROWID_EQ)==0 );
100988 assert( pSrc->pIndex==0
100989 || pCost->plan.u.pIdx==0
100990 || pCost->plan.u.pIdx==pSrc->pIndex
100993 WHERETRACE(("best index is: %s\n",
100994 ((pCost->plan.wsFlags & WHERE_NOT_FULLSCAN)==0 ? "none" :
100995 pCost->plan.u.pIdx ? pCost->plan.u.pIdx->zName : "ipk")
100998 bestOrClauseIndex(pParse, pWC, pSrc, notReady, notValid, pOrderBy, pCost);
100999 bestAutomaticIndex(pParse, pWC, pSrc, notReady, pCost);
101000 pCost->plan.wsFlags |= eqTermMask;
101004 ** Find the query plan for accessing table pSrc->pTab. Write the
101005 ** best query plan and its cost into the WhereCost object supplied
101006 ** as the last parameter. This function may calculate the cost of
101007 ** both real and virtual table scans.
101009 static void bestIndex(
101010 Parse *pParse, /* The parsing context */
101011 WhereClause *pWC, /* The WHERE clause */
101012 struct SrcList_item *pSrc, /* The FROM clause term to search */
101013 Bitmask notReady, /* Mask of cursors not available for indexing */
101014 Bitmask notValid, /* Cursors not available for any purpose */
101015 ExprList *pOrderBy, /* The ORDER BY clause */
101016 WhereCost *pCost /* Lowest cost query plan */
101018 #ifndef SQLITE_OMIT_VIRTUALTABLE
101019 if( IsVirtual(pSrc->pTab) ){
101020 sqlite3_index_info *p = 0;
101021 bestVirtualIndex(pParse, pWC, pSrc, notReady, notValid, pOrderBy, pCost,&p);
101022 if( p->needToFreeIdxStr ){
101023 sqlite3_free(p->idxStr);
101025 sqlite3DbFree(pParse->db, p);
101026 }else
101027 #endif
101029 bestBtreeIndex(pParse, pWC, pSrc, notReady, notValid, pOrderBy, pCost);
101034 ** Disable a term in the WHERE clause. Except, do not disable the term
101035 ** if it controls a LEFT OUTER JOIN and it did not originate in the ON
101036 ** or USING clause of that join.
101038 ** Consider the term t2.z='ok' in the following queries:
101040 ** (1) SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x WHERE t2.z='ok'
101041 ** (2) SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x AND t2.z='ok'
101042 ** (3) SELECT * FROM t1, t2 WHERE t1.a=t2.x AND t2.z='ok'
101044 ** The t2.z='ok' is disabled in the in (2) because it originates
101045 ** in the ON clause. The term is disabled in (3) because it is not part
101046 ** of a LEFT OUTER JOIN. In (1), the term is not disabled.
101048 ** IMPLEMENTATION-OF: R-24597-58655 No tests are done for terms that are
101049 ** completely satisfied by indices.
101051 ** Disabling a term causes that term to not be tested in the inner loop
101052 ** of the join. Disabling is an optimization. When terms are satisfied
101053 ** by indices, we disable them to prevent redundant tests in the inner
101054 ** loop. We would get the correct results if nothing were ever disabled,
101055 ** but joins might run a little slower. The trick is to disable as much
101056 ** as we can without disabling too much. If we disabled in (1), we'd get
101057 ** the wrong answer. See ticket #813.
101059 static void disableTerm(WhereLevel *pLevel, WhereTerm *pTerm){
101060 if( pTerm
101061 && (pTerm->wtFlags & TERM_CODED)==0
101062 && (pLevel->iLeftJoin==0 || ExprHasProperty(pTerm->pExpr, EP_FromJoin))
101064 pTerm->wtFlags |= TERM_CODED;
101065 if( pTerm->iParent>=0 ){
101066 WhereTerm *pOther = &pTerm->pWC->a[pTerm->iParent];
101067 if( (--pOther->nChild)==0 ){
101068 disableTerm(pLevel, pOther);
101075 ** Code an OP_Affinity opcode to apply the column affinity string zAff
101076 ** to the n registers starting at base.
101078 ** As an optimization, SQLITE_AFF_NONE entries (which are no-ops) at the
101079 ** beginning and end of zAff are ignored. If all entries in zAff are
101080 ** SQLITE_AFF_NONE, then no code gets generated.
101082 ** This routine makes its own copy of zAff so that the caller is free
101083 ** to modify zAff after this routine returns.
101085 static void codeApplyAffinity(Parse *pParse, int base, int n, char *zAff){
101086 Vdbe *v = pParse->pVdbe;
101087 if( zAff==0 ){
101088 assert( pParse->db->mallocFailed );
101089 return;
101091 assert( v!=0 );
101093 /* Adjust base and n to skip over SQLITE_AFF_NONE entries at the beginning
101094 ** and end of the affinity string.
101096 while( n>0 && zAff[0]==SQLITE_AFF_NONE ){
101098 base++;
101099 zAff++;
101101 while( n>1 && zAff[n-1]==SQLITE_AFF_NONE ){
101105 /* Code the OP_Affinity opcode if there is anything left to do. */
101106 if( n>0 ){
101107 sqlite3VdbeAddOp2(v, OP_Affinity, base, n);
101108 sqlite3VdbeChangeP4(v, -1, zAff, n);
101109 sqlite3ExprCacheAffinityChange(pParse, base, n);
101115 ** Generate code for a single equality term of the WHERE clause. An equality
101116 ** term can be either X=expr or X IN (...). pTerm is the term to be
101117 ** coded.
101119 ** The current value for the constraint is left in register iReg.
101121 ** For a constraint of the form X=expr, the expression is evaluated and its
101122 ** result is left on the stack. For constraints of the form X IN (...)
101123 ** this routine sets up a loop that will iterate over all values of X.
101125 static int codeEqualityTerm(
101126 Parse *pParse, /* The parsing context */
101127 WhereTerm *pTerm, /* The term of the WHERE clause to be coded */
101128 WhereLevel *pLevel, /* When level of the FROM clause we are working on */
101129 int iTarget /* Attempt to leave results in this register */
101131 Expr *pX = pTerm->pExpr;
101132 Vdbe *v = pParse->pVdbe;
101133 int iReg; /* Register holding results */
101135 assert( iTarget>0 );
101136 if( pX->op==TK_EQ ){
101137 iReg = sqlite3ExprCodeTarget(pParse, pX->pRight, iTarget);
101138 }else if( pX->op==TK_ISNULL ){
101139 iReg = iTarget;
101140 sqlite3VdbeAddOp2(v, OP_Null, 0, iReg);
101141 #ifndef SQLITE_OMIT_SUBQUERY
101142 }else{
101143 int eType;
101144 int iTab;
101145 struct InLoop *pIn;
101147 assert( pX->op==TK_IN );
101148 iReg = iTarget;
101149 eType = sqlite3FindInIndex(pParse, pX, 0);
101150 iTab = pX->iTable;
101151 sqlite3VdbeAddOp2(v, OP_Rewind, iTab, 0);
101152 assert( pLevel->plan.wsFlags & WHERE_IN_ABLE );
101153 if( pLevel->u.in.nIn==0 ){
101154 pLevel->addrNxt = sqlite3VdbeMakeLabel(v);
101156 pLevel->u.in.nIn++;
101157 pLevel->u.in.aInLoop =
101158 sqlite3DbReallocOrFree(pParse->db, pLevel->u.in.aInLoop,
101159 sizeof(pLevel->u.in.aInLoop[0])*pLevel->u.in.nIn);
101160 pIn = pLevel->u.in.aInLoop;
101161 if( pIn ){
101162 pIn += pLevel->u.in.nIn - 1;
101163 pIn->iCur = iTab;
101164 if( eType==IN_INDEX_ROWID ){
101165 pIn->addrInTop = sqlite3VdbeAddOp2(v, OP_Rowid, iTab, iReg);
101166 }else{
101167 pIn->addrInTop = sqlite3VdbeAddOp3(v, OP_Column, iTab, 0, iReg);
101169 sqlite3VdbeAddOp1(v, OP_IsNull, iReg);
101170 }else{
101171 pLevel->u.in.nIn = 0;
101173 #endif
101175 disableTerm(pLevel, pTerm);
101176 return iReg;
101180 ** Generate code that will evaluate all == and IN constraints for an
101181 ** index.
101183 ** For example, consider table t1(a,b,c,d,e,f) with index i1(a,b,c).
101184 ** Suppose the WHERE clause is this: a==5 AND b IN (1,2,3) AND c>5 AND c<10
101185 ** The index has as many as three equality constraints, but in this
101186 ** example, the third "c" value is an inequality. So only two
101187 ** constraints are coded. This routine will generate code to evaluate
101188 ** a==5 and b IN (1,2,3). The current values for a and b will be stored
101189 ** in consecutive registers and the index of the first register is returned.
101191 ** In the example above nEq==2. But this subroutine works for any value
101192 ** of nEq including 0. If nEq==0, this routine is nearly a no-op.
101193 ** The only thing it does is allocate the pLevel->iMem memory cell and
101194 ** compute the affinity string.
101196 ** This routine always allocates at least one memory cell and returns
101197 ** the index of that memory cell. The code that
101198 ** calls this routine will use that memory cell to store the termination
101199 ** key value of the loop. If one or more IN operators appear, then
101200 ** this routine allocates an additional nEq memory cells for internal
101201 ** use.
101203 ** Before returning, *pzAff is set to point to a buffer containing a
101204 ** copy of the column affinity string of the index allocated using
101205 ** sqlite3DbMalloc(). Except, entries in the copy of the string associated
101206 ** with equality constraints that use NONE affinity are set to
101207 ** SQLITE_AFF_NONE. This is to deal with SQL such as the following:
101209 ** CREATE TABLE t1(a TEXT PRIMARY KEY, b);
101210 ** SELECT ... FROM t1 AS t2, t1 WHERE t1.a = t2.b;
101212 ** In the example above, the index on t1(a) has TEXT affinity. But since
101213 ** the right hand side of the equality constraint (t2.b) has NONE affinity,
101214 ** no conversion should be attempted before using a t2.b value as part of
101215 ** a key to search the index. Hence the first byte in the returned affinity
101216 ** string in this example would be set to SQLITE_AFF_NONE.
101218 static int codeAllEqualityTerms(
101219 Parse *pParse, /* Parsing context */
101220 WhereLevel *pLevel, /* Which nested loop of the FROM we are coding */
101221 WhereClause *pWC, /* The WHERE clause */
101222 Bitmask notReady, /* Which parts of FROM have not yet been coded */
101223 int nExtraReg, /* Number of extra registers to allocate */
101224 char **pzAff /* OUT: Set to point to affinity string */
101226 int nEq = pLevel->plan.nEq; /* The number of == or IN constraints to code */
101227 Vdbe *v = pParse->pVdbe; /* The vm under construction */
101228 Index *pIdx; /* The index being used for this loop */
101229 int iCur = pLevel->iTabCur; /* The cursor of the table */
101230 WhereTerm *pTerm; /* A single constraint term */
101231 int j; /* Loop counter */
101232 int regBase; /* Base register */
101233 int nReg; /* Number of registers to allocate */
101234 char *zAff; /* Affinity string to return */
101236 /* This module is only called on query plans that use an index. */
101237 assert( pLevel->plan.wsFlags & WHERE_INDEXED );
101238 pIdx = pLevel->plan.u.pIdx;
101240 /* Figure out how many memory cells we will need then allocate them.
101242 regBase = pParse->nMem + 1;
101243 nReg = pLevel->plan.nEq + nExtraReg;
101244 pParse->nMem += nReg;
101246 zAff = sqlite3DbStrDup(pParse->db, sqlite3IndexAffinityStr(v, pIdx));
101247 if( !zAff ){
101248 pParse->db->mallocFailed = 1;
101251 /* Evaluate the equality constraints
101253 assert( pIdx->nColumn>=nEq );
101254 for(j=0; j<nEq; j++){
101255 int r1;
101256 int k = pIdx->aiColumn[j];
101257 pTerm = findTerm(pWC, iCur, k, notReady, pLevel->plan.wsFlags, pIdx);
101258 if( NEVER(pTerm==0) ) break;
101259 /* The following true for indices with redundant columns.
101260 ** Ex: CREATE INDEX i1 ON t1(a,b,a); SELECT * FROM t1 WHERE a=0 AND b=0; */
101261 testcase( (pTerm->wtFlags & TERM_CODED)!=0 );
101262 testcase( pTerm->wtFlags & TERM_VIRTUAL ); /* EV: R-30575-11662 */
101263 r1 = codeEqualityTerm(pParse, pTerm, pLevel, regBase+j);
101264 if( r1!=regBase+j ){
101265 if( nReg==1 ){
101266 sqlite3ReleaseTempReg(pParse, regBase);
101267 regBase = r1;
101268 }else{
101269 sqlite3VdbeAddOp2(v, OP_SCopy, r1, regBase+j);
101272 testcase( pTerm->eOperator & WO_ISNULL );
101273 testcase( pTerm->eOperator & WO_IN );
101274 if( (pTerm->eOperator & (WO_ISNULL|WO_IN))==0 ){
101275 Expr *pRight = pTerm->pExpr->pRight;
101276 sqlite3ExprCodeIsNullJump(v, pRight, regBase+j, pLevel->addrBrk);
101277 if( zAff ){
101278 if( sqlite3CompareAffinity(pRight, zAff[j])==SQLITE_AFF_NONE ){
101279 zAff[j] = SQLITE_AFF_NONE;
101281 if( sqlite3ExprNeedsNoAffinityChange(pRight, zAff[j]) ){
101282 zAff[j] = SQLITE_AFF_NONE;
101287 *pzAff = zAff;
101288 return regBase;
101291 #ifndef SQLITE_OMIT_EXPLAIN
101293 ** This routine is a helper for explainIndexRange() below
101295 ** pStr holds the text of an expression that we are building up one term
101296 ** at a time. This routine adds a new term to the end of the expression.
101297 ** Terms are separated by AND so add the "AND" text for second and subsequent
101298 ** terms only.
101300 static void explainAppendTerm(
101301 StrAccum *pStr, /* The text expression being built */
101302 int iTerm, /* Index of this term. First is zero */
101303 const char *zColumn, /* Name of the column */
101304 const char *zOp /* Name of the operator */
101306 if( iTerm ) sqlite3StrAccumAppend(pStr, " AND ", 5);
101307 sqlite3StrAccumAppend(pStr, zColumn, -1);
101308 sqlite3StrAccumAppend(pStr, zOp, 1);
101309 sqlite3StrAccumAppend(pStr, "?", 1);
101313 ** Argument pLevel describes a strategy for scanning table pTab. This
101314 ** function returns a pointer to a string buffer containing a description
101315 ** of the subset of table rows scanned by the strategy in the form of an
101316 ** SQL expression. Or, if all rows are scanned, NULL is returned.
101318 ** For example, if the query:
101320 ** SELECT * FROM t1 WHERE a=1 AND b>2;
101322 ** is run and there is an index on (a, b), then this function returns a
101323 ** string similar to:
101325 ** "a=? AND b>?"
101327 ** The returned pointer points to memory obtained from sqlite3DbMalloc().
101328 ** It is the responsibility of the caller to free the buffer when it is
101329 ** no longer required.
101331 static char *explainIndexRange(sqlite3 *db, WhereLevel *pLevel, Table *pTab){
101332 WherePlan *pPlan = &pLevel->plan;
101333 Index *pIndex = pPlan->u.pIdx;
101334 int nEq = pPlan->nEq;
101335 int i, j;
101336 Column *aCol = pTab->aCol;
101337 int *aiColumn = pIndex->aiColumn;
101338 StrAccum txt;
101340 if( nEq==0 && (pPlan->wsFlags & (WHERE_BTM_LIMIT|WHERE_TOP_LIMIT))==0 ){
101341 return 0;
101343 sqlite3StrAccumInit(&txt, 0, 0, SQLITE_MAX_LENGTH);
101344 txt.db = db;
101345 sqlite3StrAccumAppend(&txt, " (", 2);
101346 for(i=0; i<nEq; i++){
101347 explainAppendTerm(&txt, i, aCol[aiColumn[i]].zName, "=");
101350 j = i;
101351 if( pPlan->wsFlags&WHERE_BTM_LIMIT ){
101352 explainAppendTerm(&txt, i++, aCol[aiColumn[j]].zName, ">");
101354 if( pPlan->wsFlags&WHERE_TOP_LIMIT ){
101355 explainAppendTerm(&txt, i, aCol[aiColumn[j]].zName, "<");
101357 sqlite3StrAccumAppend(&txt, ")", 1);
101358 return sqlite3StrAccumFinish(&txt);
101362 ** This function is a no-op unless currently processing an EXPLAIN QUERY PLAN
101363 ** command. If the query being compiled is an EXPLAIN QUERY PLAN, a single
101364 ** record is added to the output to describe the table scan strategy in
101365 ** pLevel.
101367 static void explainOneScan(
101368 Parse *pParse, /* Parse context */
101369 SrcList *pTabList, /* Table list this loop refers to */
101370 WhereLevel *pLevel, /* Scan to write OP_Explain opcode for */
101371 int iLevel, /* Value for "level" column of output */
101372 int iFrom, /* Value for "from" column of output */
101373 u16 wctrlFlags /* Flags passed to sqlite3WhereBegin() */
101375 if( pParse->explain==2 ){
101376 u32 flags = pLevel->plan.wsFlags;
101377 struct SrcList_item *pItem = &pTabList->a[pLevel->iFrom];
101378 Vdbe *v = pParse->pVdbe; /* VM being constructed */
101379 sqlite3 *db = pParse->db; /* Database handle */
101380 char *zMsg; /* Text to add to EQP output */
101381 sqlite3_int64 nRow; /* Expected number of rows visited by scan */
101382 int iId = pParse->iSelectId; /* Select id (left-most output column) */
101383 int isSearch; /* True for a SEARCH. False for SCAN. */
101385 if( (flags&WHERE_MULTI_OR) || (wctrlFlags&WHERE_ONETABLE_ONLY) ) return;
101387 isSearch = (pLevel->plan.nEq>0)
101388 || (flags&(WHERE_BTM_LIMIT|WHERE_TOP_LIMIT))!=0
101389 || (wctrlFlags&(WHERE_ORDERBY_MIN|WHERE_ORDERBY_MAX));
101391 zMsg = sqlite3MPrintf(db, "%s", isSearch?"SEARCH":"SCAN");
101392 if( pItem->pSelect ){
101393 zMsg = sqlite3MAppendf(db, zMsg, "%s SUBQUERY %d", zMsg,pItem->iSelectId);
101394 }else{
101395 zMsg = sqlite3MAppendf(db, zMsg, "%s TABLE %s", zMsg, pItem->zName);
101398 if( pItem->zAlias ){
101399 zMsg = sqlite3MAppendf(db, zMsg, "%s AS %s", zMsg, pItem->zAlias);
101401 if( (flags & WHERE_INDEXED)!=0 ){
101402 char *zWhere = explainIndexRange(db, pLevel, pItem->pTab);
101403 zMsg = sqlite3MAppendf(db, zMsg, "%s USING %s%sINDEX%s%s%s", zMsg,
101404 ((flags & WHERE_TEMP_INDEX)?"AUTOMATIC ":""),
101405 ((flags & WHERE_IDX_ONLY)?"COVERING ":""),
101406 ((flags & WHERE_TEMP_INDEX)?"":" "),
101407 ((flags & WHERE_TEMP_INDEX)?"": pLevel->plan.u.pIdx->zName),
101408 zWhere
101410 sqlite3DbFree(db, zWhere);
101411 }else if( flags & (WHERE_ROWID_EQ|WHERE_ROWID_RANGE) ){
101412 zMsg = sqlite3MAppendf(db, zMsg, "%s USING INTEGER PRIMARY KEY", zMsg);
101414 if( flags&WHERE_ROWID_EQ ){
101415 zMsg = sqlite3MAppendf(db, zMsg, "%s (rowid=?)", zMsg);
101416 }else if( (flags&WHERE_BOTH_LIMIT)==WHERE_BOTH_LIMIT ){
101417 zMsg = sqlite3MAppendf(db, zMsg, "%s (rowid>? AND rowid<?)", zMsg);
101418 }else if( flags&WHERE_BTM_LIMIT ){
101419 zMsg = sqlite3MAppendf(db, zMsg, "%s (rowid>?)", zMsg);
101420 }else if( flags&WHERE_TOP_LIMIT ){
101421 zMsg = sqlite3MAppendf(db, zMsg, "%s (rowid<?)", zMsg);
101424 #ifndef SQLITE_OMIT_VIRTUALTABLE
101425 else if( (flags & WHERE_VIRTUALTABLE)!=0 ){
101426 sqlite3_index_info *pVtabIdx = pLevel->plan.u.pVtabIdx;
101427 zMsg = sqlite3MAppendf(db, zMsg, "%s VIRTUAL TABLE INDEX %d:%s", zMsg,
101428 pVtabIdx->idxNum, pVtabIdx->idxStr);
101430 #endif
101431 if( wctrlFlags&(WHERE_ORDERBY_MIN|WHERE_ORDERBY_MAX) ){
101432 testcase( wctrlFlags & WHERE_ORDERBY_MIN );
101433 nRow = 1;
101434 }else{
101435 nRow = (sqlite3_int64)pLevel->plan.nRow;
101437 zMsg = sqlite3MAppendf(db, zMsg, "%s (~%lld rows)", zMsg, nRow);
101438 sqlite3VdbeAddOp4(v, OP_Explain, iId, iLevel, iFrom, zMsg, P4_DYNAMIC);
101441 #else
101442 # define explainOneScan(u,v,w,x,y,z)
101443 #endif /* SQLITE_OMIT_EXPLAIN */
101447 ** Generate code for the start of the iLevel-th loop in the WHERE clause
101448 ** implementation described by pWInfo.
101450 static Bitmask codeOneLoopStart(
101451 WhereInfo *pWInfo, /* Complete information about the WHERE clause */
101452 int iLevel, /* Which level of pWInfo->a[] should be coded */
101453 u16 wctrlFlags, /* One of the WHERE_* flags defined in sqliteInt.h */
101454 Bitmask notReady /* Which tables are currently available */
101456 int j, k; /* Loop counters */
101457 int iCur; /* The VDBE cursor for the table */
101458 int addrNxt; /* Where to jump to continue with the next IN case */
101459 int omitTable; /* True if we use the index only */
101460 int bRev; /* True if we need to scan in reverse order */
101461 WhereLevel *pLevel; /* The where level to be coded */
101462 WhereClause *pWC; /* Decomposition of the entire WHERE clause */
101463 WhereTerm *pTerm; /* A WHERE clause term */
101464 Parse *pParse; /* Parsing context */
101465 Vdbe *v; /* The prepared stmt under constructions */
101466 struct SrcList_item *pTabItem; /* FROM clause term being coded */
101467 int addrBrk; /* Jump here to break out of the loop */
101468 int addrCont; /* Jump here to continue with next cycle */
101469 int iRowidReg = 0; /* Rowid is stored in this register, if not zero */
101470 int iReleaseReg = 0; /* Temp register to free before returning */
101472 pParse = pWInfo->pParse;
101473 v = pParse->pVdbe;
101474 pWC = pWInfo->pWC;
101475 pLevel = &pWInfo->a[iLevel];
101476 pTabItem = &pWInfo->pTabList->a[pLevel->iFrom];
101477 iCur = pTabItem->iCursor;
101478 bRev = (pLevel->plan.wsFlags & WHERE_REVERSE)!=0;
101479 omitTable = (pLevel->plan.wsFlags & WHERE_IDX_ONLY)!=0
101480 && (wctrlFlags & WHERE_FORCE_TABLE)==0;
101482 /* Create labels for the "break" and "continue" instructions
101483 ** for the current loop. Jump to addrBrk to break out of a loop.
101484 ** Jump to cont to go immediately to the next iteration of the
101485 ** loop.
101487 ** When there is an IN operator, we also have a "addrNxt" label that
101488 ** means to continue with the next IN value combination. When
101489 ** there are no IN operators in the constraints, the "addrNxt" label
101490 ** is the same as "addrBrk".
101492 addrBrk = pLevel->addrBrk = pLevel->addrNxt = sqlite3VdbeMakeLabel(v);
101493 addrCont = pLevel->addrCont = sqlite3VdbeMakeLabel(v);
101495 /* If this is the right table of a LEFT OUTER JOIN, allocate and
101496 ** initialize a memory cell that records if this table matches any
101497 ** row of the left table of the join.
101499 if( pLevel->iFrom>0 && (pTabItem[0].jointype & JT_LEFT)!=0 ){
101500 pLevel->iLeftJoin = ++pParse->nMem;
101501 sqlite3VdbeAddOp2(v, OP_Integer, 0, pLevel->iLeftJoin);
101502 VdbeComment((v, "init LEFT JOIN no-match flag"));
101505 #ifndef SQLITE_OMIT_VIRTUALTABLE
101506 if( (pLevel->plan.wsFlags & WHERE_VIRTUALTABLE)!=0 ){
101507 /* Case 0: The table is a virtual-table. Use the VFilter and VNext
101508 ** to access the data.
101510 int iReg; /* P3 Value for OP_VFilter */
101511 sqlite3_index_info *pVtabIdx = pLevel->plan.u.pVtabIdx;
101512 int nConstraint = pVtabIdx->nConstraint;
101513 struct sqlite3_index_constraint_usage *aUsage =
101514 pVtabIdx->aConstraintUsage;
101515 const struct sqlite3_index_constraint *aConstraint =
101516 pVtabIdx->aConstraint;
101518 sqlite3ExprCachePush(pParse);
101519 iReg = sqlite3GetTempRange(pParse, nConstraint+2);
101520 for(j=1; j<=nConstraint; j++){
101521 for(k=0; k<nConstraint; k++){
101522 if( aUsage[k].argvIndex==j ){
101523 int iTerm = aConstraint[k].iTermOffset;
101524 sqlite3ExprCode(pParse, pWC->a[iTerm].pExpr->pRight, iReg+j+1);
101525 break;
101528 if( k==nConstraint ) break;
101530 sqlite3VdbeAddOp2(v, OP_Integer, pVtabIdx->idxNum, iReg);
101531 sqlite3VdbeAddOp2(v, OP_Integer, j-1, iReg+1);
101532 sqlite3VdbeAddOp4(v, OP_VFilter, iCur, addrBrk, iReg, pVtabIdx->idxStr,
101533 pVtabIdx->needToFreeIdxStr ? P4_MPRINTF : P4_STATIC);
101534 pVtabIdx->needToFreeIdxStr = 0;
101535 for(j=0; j<nConstraint; j++){
101536 if( aUsage[j].omit ){
101537 int iTerm = aConstraint[j].iTermOffset;
101538 disableTerm(pLevel, &pWC->a[iTerm]);
101541 pLevel->op = OP_VNext;
101542 pLevel->p1 = iCur;
101543 pLevel->p2 = sqlite3VdbeCurrentAddr(v);
101544 sqlite3ReleaseTempRange(pParse, iReg, nConstraint+2);
101545 sqlite3ExprCachePop(pParse, 1);
101546 }else
101547 #endif /* SQLITE_OMIT_VIRTUALTABLE */
101549 if( pLevel->plan.wsFlags & WHERE_ROWID_EQ ){
101550 /* Case 1: We can directly reference a single row using an
101551 ** equality comparison against the ROWID field. Or
101552 ** we reference multiple rows using a "rowid IN (...)"
101553 ** construct.
101555 iReleaseReg = sqlite3GetTempReg(pParse);
101556 pTerm = findTerm(pWC, iCur, -1, notReady, WO_EQ|WO_IN, 0);
101557 assert( pTerm!=0 );
101558 assert( pTerm->pExpr!=0 );
101559 assert( pTerm->leftCursor==iCur );
101560 assert( omitTable==0 );
101561 testcase( pTerm->wtFlags & TERM_VIRTUAL ); /* EV: R-30575-11662 */
101562 iRowidReg = codeEqualityTerm(pParse, pTerm, pLevel, iReleaseReg);
101563 addrNxt = pLevel->addrNxt;
101564 sqlite3VdbeAddOp2(v, OP_MustBeInt, iRowidReg, addrNxt);
101565 sqlite3VdbeAddOp3(v, OP_NotExists, iCur, addrNxt, iRowidReg);
101566 sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
101567 VdbeComment((v, "pk"));
101568 pLevel->op = OP_Noop;
101569 }else if( pLevel->plan.wsFlags & WHERE_ROWID_RANGE ){
101570 /* Case 2: We have an inequality comparison against the ROWID field.
101572 int testOp = OP_Noop;
101573 int start;
101574 int memEndValue = 0;
101575 WhereTerm *pStart, *pEnd;
101577 assert( omitTable==0 );
101578 pStart = findTerm(pWC, iCur, -1, notReady, WO_GT|WO_GE, 0);
101579 pEnd = findTerm(pWC, iCur, -1, notReady, WO_LT|WO_LE, 0);
101580 if( bRev ){
101581 pTerm = pStart;
101582 pStart = pEnd;
101583 pEnd = pTerm;
101585 if( pStart ){
101586 Expr *pX; /* The expression that defines the start bound */
101587 int r1, rTemp; /* Registers for holding the start boundary */
101589 /* The following constant maps TK_xx codes into corresponding
101590 ** seek opcodes. It depends on a particular ordering of TK_xx
101592 const u8 aMoveOp[] = {
101593 /* TK_GT */ OP_SeekGt,
101594 /* TK_LE */ OP_SeekLe,
101595 /* TK_LT */ OP_SeekLt,
101596 /* TK_GE */ OP_SeekGe
101598 assert( TK_LE==TK_GT+1 ); /* Make sure the ordering.. */
101599 assert( TK_LT==TK_GT+2 ); /* ... of the TK_xx values... */
101600 assert( TK_GE==TK_GT+3 ); /* ... is correcct. */
101602 testcase( pStart->wtFlags & TERM_VIRTUAL ); /* EV: R-30575-11662 */
101603 pX = pStart->pExpr;
101604 assert( pX!=0 );
101605 assert( pStart->leftCursor==iCur );
101606 r1 = sqlite3ExprCodeTemp(pParse, pX->pRight, &rTemp);
101607 sqlite3VdbeAddOp3(v, aMoveOp[pX->op-TK_GT], iCur, addrBrk, r1);
101608 VdbeComment((v, "pk"));
101609 sqlite3ExprCacheAffinityChange(pParse, r1, 1);
101610 sqlite3ReleaseTempReg(pParse, rTemp);
101611 disableTerm(pLevel, pStart);
101612 }else{
101613 sqlite3VdbeAddOp2(v, bRev ? OP_Last : OP_Rewind, iCur, addrBrk);
101615 if( pEnd ){
101616 Expr *pX;
101617 pX = pEnd->pExpr;
101618 assert( pX!=0 );
101619 assert( pEnd->leftCursor==iCur );
101620 testcase( pEnd->wtFlags & TERM_VIRTUAL ); /* EV: R-30575-11662 */
101621 memEndValue = ++pParse->nMem;
101622 sqlite3ExprCode(pParse, pX->pRight, memEndValue);
101623 if( pX->op==TK_LT || pX->op==TK_GT ){
101624 testOp = bRev ? OP_Le : OP_Ge;
101625 }else{
101626 testOp = bRev ? OP_Lt : OP_Gt;
101628 disableTerm(pLevel, pEnd);
101630 start = sqlite3VdbeCurrentAddr(v);
101631 pLevel->op = bRev ? OP_Prev : OP_Next;
101632 pLevel->p1 = iCur;
101633 pLevel->p2 = start;
101634 if( pStart==0 && pEnd==0 ){
101635 pLevel->p5 = SQLITE_STMTSTATUS_FULLSCAN_STEP;
101636 }else{
101637 assert( pLevel->p5==0 );
101639 if( testOp!=OP_Noop ){
101640 iRowidReg = iReleaseReg = sqlite3GetTempReg(pParse);
101641 sqlite3VdbeAddOp2(v, OP_Rowid, iCur, iRowidReg);
101642 sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
101643 sqlite3VdbeAddOp3(v, testOp, memEndValue, addrBrk, iRowidReg);
101644 sqlite3VdbeChangeP5(v, SQLITE_AFF_NUMERIC | SQLITE_JUMPIFNULL);
101646 }else if( pLevel->plan.wsFlags & (WHERE_COLUMN_RANGE|WHERE_COLUMN_EQ) ){
101647 /* Case 3: A scan using an index.
101649 ** The WHERE clause may contain zero or more equality
101650 ** terms ("==" or "IN" operators) that refer to the N
101651 ** left-most columns of the index. It may also contain
101652 ** inequality constraints (>, <, >= or <=) on the indexed
101653 ** column that immediately follows the N equalities. Only
101654 ** the right-most column can be an inequality - the rest must
101655 ** use the "==" and "IN" operators. For example, if the
101656 ** index is on (x,y,z), then the following clauses are all
101657 ** optimized:
101659 ** x=5
101660 ** x=5 AND y=10
101661 ** x=5 AND y<10
101662 ** x=5 AND y>5 AND y<10
101663 ** x=5 AND y=5 AND z<=10
101665 ** The z<10 term of the following cannot be used, only
101666 ** the x=5 term:
101668 ** x=5 AND z<10
101670 ** N may be zero if there are inequality constraints.
101671 ** If there are no inequality constraints, then N is at
101672 ** least one.
101674 ** This case is also used when there are no WHERE clause
101675 ** constraints but an index is selected anyway, in order
101676 ** to force the output order to conform to an ORDER BY.
101678 static const u8 aStartOp[] = {
101681 OP_Rewind, /* 2: (!start_constraints && startEq && !bRev) */
101682 OP_Last, /* 3: (!start_constraints && startEq && bRev) */
101683 OP_SeekGt, /* 4: (start_constraints && !startEq && !bRev) */
101684 OP_SeekLt, /* 5: (start_constraints && !startEq && bRev) */
101685 OP_SeekGe, /* 6: (start_constraints && startEq && !bRev) */
101686 OP_SeekLe /* 7: (start_constraints && startEq && bRev) */
101688 static const u8 aEndOp[] = {
101689 OP_Noop, /* 0: (!end_constraints) */
101690 OP_IdxGE, /* 1: (end_constraints && !bRev) */
101691 OP_IdxLT /* 2: (end_constraints && bRev) */
101693 int nEq = pLevel->plan.nEq; /* Number of == or IN terms */
101694 int isMinQuery = 0; /* If this is an optimized SELECT min(x).. */
101695 int regBase; /* Base register holding constraint values */
101696 int r1; /* Temp register */
101697 WhereTerm *pRangeStart = 0; /* Inequality constraint at range start */
101698 WhereTerm *pRangeEnd = 0; /* Inequality constraint at range end */
101699 int startEq; /* True if range start uses ==, >= or <= */
101700 int endEq; /* True if range end uses ==, >= or <= */
101701 int start_constraints; /* Start of range is constrained */
101702 int nConstraint; /* Number of constraint terms */
101703 Index *pIdx; /* The index we will be using */
101704 int iIdxCur; /* The VDBE cursor for the index */
101705 int nExtraReg = 0; /* Number of extra registers needed */
101706 int op; /* Instruction opcode */
101707 char *zStartAff; /* Affinity for start of range constraint */
101708 char *zEndAff; /* Affinity for end of range constraint */
101710 pIdx = pLevel->plan.u.pIdx;
101711 iIdxCur = pLevel->iIdxCur;
101712 k = pIdx->aiColumn[nEq]; /* Column for inequality constraints */
101714 /* If this loop satisfies a sort order (pOrderBy) request that
101715 ** was passed to this function to implement a "SELECT min(x) ..."
101716 ** query, then the caller will only allow the loop to run for
101717 ** a single iteration. This means that the first row returned
101718 ** should not have a NULL value stored in 'x'. If column 'x' is
101719 ** the first one after the nEq equality constraints in the index,
101720 ** this requires some special handling.
101722 if( (wctrlFlags&WHERE_ORDERBY_MIN)!=0
101723 && (pLevel->plan.wsFlags&WHERE_ORDERBY)
101724 && (pIdx->nColumn>nEq)
101726 /* assert( pOrderBy->nExpr==1 ); */
101727 /* assert( pOrderBy->a[0].pExpr->iColumn==pIdx->aiColumn[nEq] ); */
101728 isMinQuery = 1;
101729 nExtraReg = 1;
101732 /* Find any inequality constraint terms for the start and end
101733 ** of the range.
101735 if( pLevel->plan.wsFlags & WHERE_TOP_LIMIT ){
101736 pRangeEnd = findTerm(pWC, iCur, k, notReady, (WO_LT|WO_LE), pIdx);
101737 nExtraReg = 1;
101739 if( pLevel->plan.wsFlags & WHERE_BTM_LIMIT ){
101740 pRangeStart = findTerm(pWC, iCur, k, notReady, (WO_GT|WO_GE), pIdx);
101741 nExtraReg = 1;
101744 /* Generate code to evaluate all constraint terms using == or IN
101745 ** and store the values of those terms in an array of registers
101746 ** starting at regBase.
101748 regBase = codeAllEqualityTerms(
101749 pParse, pLevel, pWC, notReady, nExtraReg, &zStartAff
101751 zEndAff = sqlite3DbStrDup(pParse->db, zStartAff);
101752 addrNxt = pLevel->addrNxt;
101754 /* If we are doing a reverse order scan on an ascending index, or
101755 ** a forward order scan on a descending index, interchange the
101756 ** start and end terms (pRangeStart and pRangeEnd).
101758 if( nEq<pIdx->nColumn && bRev==(pIdx->aSortOrder[nEq]==SQLITE_SO_ASC) ){
101759 SWAP(WhereTerm *, pRangeEnd, pRangeStart);
101762 testcase( pRangeStart && pRangeStart->eOperator & WO_LE );
101763 testcase( pRangeStart && pRangeStart->eOperator & WO_GE );
101764 testcase( pRangeEnd && pRangeEnd->eOperator & WO_LE );
101765 testcase( pRangeEnd && pRangeEnd->eOperator & WO_GE );
101766 startEq = !pRangeStart || pRangeStart->eOperator & (WO_LE|WO_GE);
101767 endEq = !pRangeEnd || pRangeEnd->eOperator & (WO_LE|WO_GE);
101768 start_constraints = pRangeStart || nEq>0;
101770 /* Seek the index cursor to the start of the range. */
101771 nConstraint = nEq;
101772 if( pRangeStart ){
101773 Expr *pRight = pRangeStart->pExpr->pRight;
101774 sqlite3ExprCode(pParse, pRight, regBase+nEq);
101775 if( (pRangeStart->wtFlags & TERM_VNULL)==0 ){
101776 sqlite3ExprCodeIsNullJump(v, pRight, regBase+nEq, addrNxt);
101778 if( zStartAff ){
101779 if( sqlite3CompareAffinity(pRight, zStartAff[nEq])==SQLITE_AFF_NONE){
101780 /* Since the comparison is to be performed with no conversions
101781 ** applied to the operands, set the affinity to apply to pRight to
101782 ** SQLITE_AFF_NONE. */
101783 zStartAff[nEq] = SQLITE_AFF_NONE;
101785 if( sqlite3ExprNeedsNoAffinityChange(pRight, zStartAff[nEq]) ){
101786 zStartAff[nEq] = SQLITE_AFF_NONE;
101789 nConstraint++;
101790 testcase( pRangeStart->wtFlags & TERM_VIRTUAL ); /* EV: R-30575-11662 */
101791 }else if( isMinQuery ){
101792 sqlite3VdbeAddOp2(v, OP_Null, 0, regBase+nEq);
101793 nConstraint++;
101794 startEq = 0;
101795 start_constraints = 1;
101797 codeApplyAffinity(pParse, regBase, nConstraint, zStartAff);
101798 op = aStartOp[(start_constraints<<2) + (startEq<<1) + bRev];
101799 assert( op!=0 );
101800 testcase( op==OP_Rewind );
101801 testcase( op==OP_Last );
101802 testcase( op==OP_SeekGt );
101803 testcase( op==OP_SeekGe );
101804 testcase( op==OP_SeekLe );
101805 testcase( op==OP_SeekLt );
101806 sqlite3VdbeAddOp4Int(v, op, iIdxCur, addrNxt, regBase, nConstraint);
101808 /* Load the value for the inequality constraint at the end of the
101809 ** range (if any).
101811 nConstraint = nEq;
101812 if( pRangeEnd ){
101813 Expr *pRight = pRangeEnd->pExpr->pRight;
101814 sqlite3ExprCacheRemove(pParse, regBase+nEq, 1);
101815 sqlite3ExprCode(pParse, pRight, regBase+nEq);
101816 if( (pRangeEnd->wtFlags & TERM_VNULL)==0 ){
101817 sqlite3ExprCodeIsNullJump(v, pRight, regBase+nEq, addrNxt);
101819 if( zEndAff ){
101820 if( sqlite3CompareAffinity(pRight, zEndAff[nEq])==SQLITE_AFF_NONE){
101821 /* Since the comparison is to be performed with no conversions
101822 ** applied to the operands, set the affinity to apply to pRight to
101823 ** SQLITE_AFF_NONE. */
101824 zEndAff[nEq] = SQLITE_AFF_NONE;
101826 if( sqlite3ExprNeedsNoAffinityChange(pRight, zEndAff[nEq]) ){
101827 zEndAff[nEq] = SQLITE_AFF_NONE;
101830 codeApplyAffinity(pParse, regBase, nEq+1, zEndAff);
101831 nConstraint++;
101832 testcase( pRangeEnd->wtFlags & TERM_VIRTUAL ); /* EV: R-30575-11662 */
101834 sqlite3DbFree(pParse->db, zStartAff);
101835 sqlite3DbFree(pParse->db, zEndAff);
101837 /* Top of the loop body */
101838 pLevel->p2 = sqlite3VdbeCurrentAddr(v);
101840 /* Check if the index cursor is past the end of the range. */
101841 op = aEndOp[(pRangeEnd || nEq) * (1 + bRev)];
101842 testcase( op==OP_Noop );
101843 testcase( op==OP_IdxGE );
101844 testcase( op==OP_IdxLT );
101845 if( op!=OP_Noop ){
101846 sqlite3VdbeAddOp4Int(v, op, iIdxCur, addrNxt, regBase, nConstraint);
101847 sqlite3VdbeChangeP5(v, endEq!=bRev ?1:0);
101850 /* If there are inequality constraints, check that the value
101851 ** of the table column that the inequality contrains is not NULL.
101852 ** If it is, jump to the next iteration of the loop.
101854 r1 = sqlite3GetTempReg(pParse);
101855 testcase( pLevel->plan.wsFlags & WHERE_BTM_LIMIT );
101856 testcase( pLevel->plan.wsFlags & WHERE_TOP_LIMIT );
101857 if( (pLevel->plan.wsFlags & (WHERE_BTM_LIMIT|WHERE_TOP_LIMIT))!=0 ){
101858 sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, nEq, r1);
101859 sqlite3VdbeAddOp2(v, OP_IsNull, r1, addrCont);
101861 sqlite3ReleaseTempReg(pParse, r1);
101863 /* Seek the table cursor, if required */
101864 disableTerm(pLevel, pRangeStart);
101865 disableTerm(pLevel, pRangeEnd);
101866 if( !omitTable ){
101867 iRowidReg = iReleaseReg = sqlite3GetTempReg(pParse);
101868 sqlite3VdbeAddOp2(v, OP_IdxRowid, iIdxCur, iRowidReg);
101869 sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
101870 sqlite3VdbeAddOp2(v, OP_Seek, iCur, iRowidReg); /* Deferred seek */
101873 /* Record the instruction used to terminate the loop. Disable
101874 ** WHERE clause terms made redundant by the index range scan.
101876 if( pLevel->plan.wsFlags & WHERE_UNIQUE ){
101877 pLevel->op = OP_Noop;
101878 }else if( bRev ){
101879 pLevel->op = OP_Prev;
101880 }else{
101881 pLevel->op = OP_Next;
101883 pLevel->p1 = iIdxCur;
101884 }else
101886 #ifndef SQLITE_OMIT_OR_OPTIMIZATION
101887 if( pLevel->plan.wsFlags & WHERE_MULTI_OR ){
101888 /* Case 4: Two or more separately indexed terms connected by OR
101890 ** Example:
101892 ** CREATE TABLE t1(a,b,c,d);
101893 ** CREATE INDEX i1 ON t1(a);
101894 ** CREATE INDEX i2 ON t1(b);
101895 ** CREATE INDEX i3 ON t1(c);
101897 ** SELECT * FROM t1 WHERE a=5 OR b=7 OR (c=11 AND d=13)
101899 ** In the example, there are three indexed terms connected by OR.
101900 ** The top of the loop looks like this:
101902 ** Null 1 # Zero the rowset in reg 1
101904 ** Then, for each indexed term, the following. The arguments to
101905 ** RowSetTest are such that the rowid of the current row is inserted
101906 ** into the RowSet. If it is already present, control skips the
101907 ** Gosub opcode and jumps straight to the code generated by WhereEnd().
101909 ** sqlite3WhereBegin(<term>)
101910 ** RowSetTest # Insert rowid into rowset
101911 ** Gosub 2 A
101912 ** sqlite3WhereEnd()
101914 ** Following the above, code to terminate the loop. Label A, the target
101915 ** of the Gosub above, jumps to the instruction right after the Goto.
101917 ** Null 1 # Zero the rowset in reg 1
101918 ** Goto B # The loop is finished.
101920 ** A: <loop body> # Return data, whatever.
101922 ** Return 2 # Jump back to the Gosub
101924 ** B: <after the loop>
101927 WhereClause *pOrWc; /* The OR-clause broken out into subterms */
101928 SrcList *pOrTab; /* Shortened table list or OR-clause generation */
101930 int regReturn = ++pParse->nMem; /* Register used with OP_Gosub */
101931 int regRowset = 0; /* Register for RowSet object */
101932 int regRowid = 0; /* Register holding rowid */
101933 int iLoopBody = sqlite3VdbeMakeLabel(v); /* Start of loop body */
101934 int iRetInit; /* Address of regReturn init */
101935 int untestedTerms = 0; /* Some terms not completely tested */
101936 int ii;
101938 pTerm = pLevel->plan.u.pTerm;
101939 assert( pTerm!=0 );
101940 assert( pTerm->eOperator==WO_OR );
101941 assert( (pTerm->wtFlags & TERM_ORINFO)!=0 );
101942 pOrWc = &pTerm->u.pOrInfo->wc;
101943 pLevel->op = OP_Return;
101944 pLevel->p1 = regReturn;
101946 /* Set up a new SrcList ni pOrTab containing the table being scanned
101947 ** by this loop in the a[0] slot and all notReady tables in a[1..] slots.
101948 ** This becomes the SrcList in the recursive call to sqlite3WhereBegin().
101950 if( pWInfo->nLevel>1 ){
101951 int nNotReady; /* The number of notReady tables */
101952 struct SrcList_item *origSrc; /* Original list of tables */
101953 nNotReady = pWInfo->nLevel - iLevel - 1;
101954 pOrTab = sqlite3StackAllocRaw(pParse->db,
101955 sizeof(*pOrTab)+ nNotReady*sizeof(pOrTab->a[0]));
101956 if( pOrTab==0 ) return notReady;
101957 pOrTab->nAlloc = (i16)(nNotReady + 1);
101958 pOrTab->nSrc = pOrTab->nAlloc;
101959 memcpy(pOrTab->a, pTabItem, sizeof(*pTabItem));
101960 origSrc = pWInfo->pTabList->a;
101961 for(k=1; k<=nNotReady; k++){
101962 memcpy(&pOrTab->a[k], &origSrc[pLevel[k].iFrom], sizeof(pOrTab->a[k]));
101964 }else{
101965 pOrTab = pWInfo->pTabList;
101968 /* Initialize the rowset register to contain NULL. An SQL NULL is
101969 ** equivalent to an empty rowset.
101971 ** Also initialize regReturn to contain the address of the instruction
101972 ** immediately following the OP_Return at the bottom of the loop. This
101973 ** is required in a few obscure LEFT JOIN cases where control jumps
101974 ** over the top of the loop into the body of it. In this case the
101975 ** correct response for the end-of-loop code (the OP_Return) is to
101976 ** fall through to the next instruction, just as an OP_Next does if
101977 ** called on an uninitialized cursor.
101979 if( (wctrlFlags & WHERE_DUPLICATES_OK)==0 ){
101980 regRowset = ++pParse->nMem;
101981 regRowid = ++pParse->nMem;
101982 sqlite3VdbeAddOp2(v, OP_Null, 0, regRowset);
101984 iRetInit = sqlite3VdbeAddOp2(v, OP_Integer, 0, regReturn);
101986 for(ii=0; ii<pOrWc->nTerm; ii++){
101987 WhereTerm *pOrTerm = &pOrWc->a[ii];
101988 if( pOrTerm->leftCursor==iCur || pOrTerm->eOperator==WO_AND ){
101989 WhereInfo *pSubWInfo; /* Info for single OR-term scan */
101990 /* Loop through table entries that match term pOrTerm. */
101991 pSubWInfo = sqlite3WhereBegin(pParse, pOrTab, pOrTerm->pExpr, 0,
101992 WHERE_OMIT_OPEN | WHERE_OMIT_CLOSE |
101993 WHERE_FORCE_TABLE | WHERE_ONETABLE_ONLY);
101994 if( pSubWInfo ){
101995 explainOneScan(
101996 pParse, pOrTab, &pSubWInfo->a[0], iLevel, pLevel->iFrom, 0
101998 if( (wctrlFlags & WHERE_DUPLICATES_OK)==0 ){
101999 int iSet = ((ii==pOrWc->nTerm-1)?-1:ii);
102000 int r;
102001 r = sqlite3ExprCodeGetColumn(pParse, pTabItem->pTab, -1, iCur,
102002 regRowid);
102003 sqlite3VdbeAddOp4Int(v, OP_RowSetTest, regRowset,
102004 sqlite3VdbeCurrentAddr(v)+2, r, iSet);
102006 sqlite3VdbeAddOp2(v, OP_Gosub, regReturn, iLoopBody);
102008 /* The pSubWInfo->untestedTerms flag means that this OR term
102009 ** contained one or more AND term from a notReady table. The
102010 ** terms from the notReady table could not be tested and will
102011 ** need to be tested later.
102013 if( pSubWInfo->untestedTerms ) untestedTerms = 1;
102015 /* Finish the loop through table entries that match term pOrTerm. */
102016 sqlite3WhereEnd(pSubWInfo);
102020 sqlite3VdbeChangeP1(v, iRetInit, sqlite3VdbeCurrentAddr(v));
102021 sqlite3VdbeAddOp2(v, OP_Goto, 0, pLevel->addrBrk);
102022 sqlite3VdbeResolveLabel(v, iLoopBody);
102024 if( pWInfo->nLevel>1 ) sqlite3StackFree(pParse->db, pOrTab);
102025 if( !untestedTerms ) disableTerm(pLevel, pTerm);
102026 }else
102027 #endif /* SQLITE_OMIT_OR_OPTIMIZATION */
102030 /* Case 5: There is no usable index. We must do a complete
102031 ** scan of the entire table.
102033 static const u8 aStep[] = { OP_Next, OP_Prev };
102034 static const u8 aStart[] = { OP_Rewind, OP_Last };
102035 assert( bRev==0 || bRev==1 );
102036 assert( omitTable==0 );
102037 pLevel->op = aStep[bRev];
102038 pLevel->p1 = iCur;
102039 pLevel->p2 = 1 + sqlite3VdbeAddOp2(v, aStart[bRev], iCur, addrBrk);
102040 pLevel->p5 = SQLITE_STMTSTATUS_FULLSCAN_STEP;
102042 notReady &= ~getMask(pWC->pMaskSet, iCur);
102044 /* Insert code to test every subexpression that can be completely
102045 ** computed using the current set of tables.
102047 ** IMPLEMENTATION-OF: R-49525-50935 Terms that cannot be satisfied through
102048 ** the use of indices become tests that are evaluated against each row of
102049 ** the relevant input tables.
102051 for(pTerm=pWC->a, j=pWC->nTerm; j>0; j--, pTerm++){
102052 Expr *pE;
102053 testcase( pTerm->wtFlags & TERM_VIRTUAL ); /* IMP: R-30575-11662 */
102054 testcase( pTerm->wtFlags & TERM_CODED );
102055 if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
102056 if( (pTerm->prereqAll & notReady)!=0 ){
102057 testcase( pWInfo->untestedTerms==0
102058 && (pWInfo->wctrlFlags & WHERE_ONETABLE_ONLY)!=0 );
102059 pWInfo->untestedTerms = 1;
102060 continue;
102062 pE = pTerm->pExpr;
102063 assert( pE!=0 );
102064 if( pLevel->iLeftJoin && !ExprHasProperty(pE, EP_FromJoin) ){
102065 continue;
102067 sqlite3ExprIfFalse(pParse, pE, addrCont, SQLITE_JUMPIFNULL);
102068 pTerm->wtFlags |= TERM_CODED;
102071 /* For a LEFT OUTER JOIN, generate code that will record the fact that
102072 ** at least one row of the right table has matched the left table.
102074 if( pLevel->iLeftJoin ){
102075 pLevel->addrFirst = sqlite3VdbeCurrentAddr(v);
102076 sqlite3VdbeAddOp2(v, OP_Integer, 1, pLevel->iLeftJoin);
102077 VdbeComment((v, "record LEFT JOIN hit"));
102078 sqlite3ExprCacheClear(pParse);
102079 for(pTerm=pWC->a, j=0; j<pWC->nTerm; j++, pTerm++){
102080 testcase( pTerm->wtFlags & TERM_VIRTUAL ); /* IMP: R-30575-11662 */
102081 testcase( pTerm->wtFlags & TERM_CODED );
102082 if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
102083 if( (pTerm->prereqAll & notReady)!=0 ){
102084 assert( pWInfo->untestedTerms );
102085 continue;
102087 assert( pTerm->pExpr );
102088 sqlite3ExprIfFalse(pParse, pTerm->pExpr, addrCont, SQLITE_JUMPIFNULL);
102089 pTerm->wtFlags |= TERM_CODED;
102092 sqlite3ReleaseTempReg(pParse, iReleaseReg);
102094 return notReady;
102097 #if defined(SQLITE_TEST)
102099 ** The following variable holds a text description of query plan generated
102100 ** by the most recent call to sqlite3WhereBegin(). Each call to WhereBegin
102101 ** overwrites the previous. This information is used for testing and
102102 ** analysis only.
102104 SQLITE_API char sqlite3_query_plan[BMS*2*40]; /* Text of the join */
102105 static int nQPlan = 0; /* Next free slow in _query_plan[] */
102107 #endif /* SQLITE_TEST */
102111 ** Free a WhereInfo structure
102113 static void whereInfoFree(sqlite3 *db, WhereInfo *pWInfo){
102114 if( ALWAYS(pWInfo) ){
102115 int i;
102116 for(i=0; i<pWInfo->nLevel; i++){
102117 sqlite3_index_info *pInfo = pWInfo->a[i].pIdxInfo;
102118 if( pInfo ){
102119 /* assert( pInfo->needToFreeIdxStr==0 || db->mallocFailed ); */
102120 if( pInfo->needToFreeIdxStr ){
102121 sqlite3_free(pInfo->idxStr);
102123 sqlite3DbFree(db, pInfo);
102125 if( pWInfo->a[i].plan.wsFlags & WHERE_TEMP_INDEX ){
102126 Index *pIdx = pWInfo->a[i].plan.u.pIdx;
102127 if( pIdx ){
102128 sqlite3DbFree(db, pIdx->zColAff);
102129 sqlite3DbFree(db, pIdx);
102133 whereClauseClear(pWInfo->pWC);
102134 sqlite3DbFree(db, pWInfo);
102140 ** Generate the beginning of the loop used for WHERE clause processing.
102141 ** The return value is a pointer to an opaque structure that contains
102142 ** information needed to terminate the loop. Later, the calling routine
102143 ** should invoke sqlite3WhereEnd() with the return value of this function
102144 ** in order to complete the WHERE clause processing.
102146 ** If an error occurs, this routine returns NULL.
102148 ** The basic idea is to do a nested loop, one loop for each table in
102149 ** the FROM clause of a select. (INSERT and UPDATE statements are the
102150 ** same as a SELECT with only a single table in the FROM clause.) For
102151 ** example, if the SQL is this:
102153 ** SELECT * FROM t1, t2, t3 WHERE ...;
102155 ** Then the code generated is conceptually like the following:
102157 ** foreach row1 in t1 do \ Code generated
102158 ** foreach row2 in t2 do |-- by sqlite3WhereBegin()
102159 ** foreach row3 in t3 do /
102160 ** ...
102161 ** end \ Code generated
102162 ** end |-- by sqlite3WhereEnd()
102163 ** end /
102165 ** Note that the loops might not be nested in the order in which they
102166 ** appear in the FROM clause if a different order is better able to make
102167 ** use of indices. Note also that when the IN operator appears in
102168 ** the WHERE clause, it might result in additional nested loops for
102169 ** scanning through all values on the right-hand side of the IN.
102171 ** There are Btree cursors associated with each table. t1 uses cursor
102172 ** number pTabList->a[0].iCursor. t2 uses the cursor pTabList->a[1].iCursor.
102173 ** And so forth. This routine generates code to open those VDBE cursors
102174 ** and sqlite3WhereEnd() generates the code to close them.
102176 ** The code that sqlite3WhereBegin() generates leaves the cursors named
102177 ** in pTabList pointing at their appropriate entries. The [...] code
102178 ** can use OP_Column and OP_Rowid opcodes on these cursors to extract
102179 ** data from the various tables of the loop.
102181 ** If the WHERE clause is empty, the foreach loops must each scan their
102182 ** entire tables. Thus a three-way join is an O(N^3) operation. But if
102183 ** the tables have indices and there are terms in the WHERE clause that
102184 ** refer to those indices, a complete table scan can be avoided and the
102185 ** code will run much faster. Most of the work of this routine is checking
102186 ** to see if there are indices that can be used to speed up the loop.
102188 ** Terms of the WHERE clause are also used to limit which rows actually
102189 ** make it to the "..." in the middle of the loop. After each "foreach",
102190 ** terms of the WHERE clause that use only terms in that loop and outer
102191 ** loops are evaluated and if false a jump is made around all subsequent
102192 ** inner loops (or around the "..." if the test occurs within the inner-
102193 ** most loop)
102195 ** OUTER JOINS
102197 ** An outer join of tables t1 and t2 is conceptally coded as follows:
102199 ** foreach row1 in t1 do
102200 ** flag = 0
102201 ** foreach row2 in t2 do
102202 ** start:
102203 ** ...
102204 ** flag = 1
102205 ** end
102206 ** if flag==0 then
102207 ** move the row2 cursor to a null row
102208 ** goto start
102209 ** fi
102210 ** end
102212 ** ORDER BY CLAUSE PROCESSING
102214 ** *ppOrderBy is a pointer to the ORDER BY clause of a SELECT statement,
102215 ** if there is one. If there is no ORDER BY clause or if this routine
102216 ** is called from an UPDATE or DELETE statement, then ppOrderBy is NULL.
102218 ** If an index can be used so that the natural output order of the table
102219 ** scan is correct for the ORDER BY clause, then that index is used and
102220 ** *ppOrderBy is set to NULL. This is an optimization that prevents an
102221 ** unnecessary sort of the result set if an index appropriate for the
102222 ** ORDER BY clause already exists.
102224 ** If the where clause loops cannot be arranged to provide the correct
102225 ** output order, then the *ppOrderBy is unchanged.
102227 SQLITE_PRIVATE WhereInfo *sqlite3WhereBegin(
102228 Parse *pParse, /* The parser context */
102229 SrcList *pTabList, /* A list of all tables to be scanned */
102230 Expr *pWhere, /* The WHERE clause */
102231 ExprList **ppOrderBy, /* An ORDER BY clause, or NULL */
102232 u16 wctrlFlags /* One of the WHERE_* flags defined in sqliteInt.h */
102234 int i; /* Loop counter */
102235 int nByteWInfo; /* Num. bytes allocated for WhereInfo struct */
102236 int nTabList; /* Number of elements in pTabList */
102237 WhereInfo *pWInfo; /* Will become the return value of this function */
102238 Vdbe *v = pParse->pVdbe; /* The virtual database engine */
102239 Bitmask notReady; /* Cursors that are not yet positioned */
102240 WhereMaskSet *pMaskSet; /* The expression mask set */
102241 WhereClause *pWC; /* Decomposition of the WHERE clause */
102242 struct SrcList_item *pTabItem; /* A single entry from pTabList */
102243 WhereLevel *pLevel; /* A single level in the pWInfo list */
102244 int iFrom; /* First unused FROM clause element */
102245 int andFlags; /* AND-ed combination of all pWC->a[].wtFlags */
102246 sqlite3 *db; /* Database connection */
102248 /* The number of tables in the FROM clause is limited by the number of
102249 ** bits in a Bitmask
102251 testcase( pTabList->nSrc==BMS );
102252 if( pTabList->nSrc>BMS ){
102253 sqlite3ErrorMsg(pParse, "at most %d tables in a join", BMS);
102254 return 0;
102257 /* This function normally generates a nested loop for all tables in
102258 ** pTabList. But if the WHERE_ONETABLE_ONLY flag is set, then we should
102259 ** only generate code for the first table in pTabList and assume that
102260 ** any cursors associated with subsequent tables are uninitialized.
102262 nTabList = (wctrlFlags & WHERE_ONETABLE_ONLY) ? 1 : pTabList->nSrc;
102264 /* Allocate and initialize the WhereInfo structure that will become the
102265 ** return value. A single allocation is used to store the WhereInfo
102266 ** struct, the contents of WhereInfo.a[], the WhereClause structure
102267 ** and the WhereMaskSet structure. Since WhereClause contains an 8-byte
102268 ** field (type Bitmask) it must be aligned on an 8-byte boundary on
102269 ** some architectures. Hence the ROUND8() below.
102271 db = pParse->db;
102272 nByteWInfo = ROUND8(sizeof(WhereInfo)+(nTabList-1)*sizeof(WhereLevel));
102273 pWInfo = sqlite3DbMallocZero(db,
102274 nByteWInfo +
102275 sizeof(WhereClause) +
102276 sizeof(WhereMaskSet)
102278 if( db->mallocFailed ){
102279 sqlite3DbFree(db, pWInfo);
102280 pWInfo = 0;
102281 goto whereBeginError;
102283 pWInfo->nLevel = nTabList;
102284 pWInfo->pParse = pParse;
102285 pWInfo->pTabList = pTabList;
102286 pWInfo->iBreak = sqlite3VdbeMakeLabel(v);
102287 pWInfo->pWC = pWC = (WhereClause *)&((u8 *)pWInfo)[nByteWInfo];
102288 pWInfo->wctrlFlags = wctrlFlags;
102289 pWInfo->savedNQueryLoop = pParse->nQueryLoop;
102290 pMaskSet = (WhereMaskSet*)&pWC[1];
102292 /* Split the WHERE clause into separate subexpressions where each
102293 ** subexpression is separated by an AND operator.
102295 initMaskSet(pMaskSet);
102296 whereClauseInit(pWC, pParse, pMaskSet);
102297 sqlite3ExprCodeConstants(pParse, pWhere);
102298 whereSplit(pWC, pWhere, TK_AND); /* IMP: R-15842-53296 */
102300 /* Special case: a WHERE clause that is constant. Evaluate the
102301 ** expression and either jump over all of the code or fall thru.
102303 if( pWhere && (nTabList==0 || sqlite3ExprIsConstantNotJoin(pWhere)) ){
102304 sqlite3ExprIfFalse(pParse, pWhere, pWInfo->iBreak, SQLITE_JUMPIFNULL);
102305 pWhere = 0;
102308 /* Assign a bit from the bitmask to every term in the FROM clause.
102310 ** When assigning bitmask values to FROM clause cursors, it must be
102311 ** the case that if X is the bitmask for the N-th FROM clause term then
102312 ** the bitmask for all FROM clause terms to the left of the N-th term
102313 ** is (X-1). An expression from the ON clause of a LEFT JOIN can use
102314 ** its Expr.iRightJoinTable value to find the bitmask of the right table
102315 ** of the join. Subtracting one from the right table bitmask gives a
102316 ** bitmask for all tables to the left of the join. Knowing the bitmask
102317 ** for all tables to the left of a left join is important. Ticket #3015.
102319 ** Configure the WhereClause.vmask variable so that bits that correspond
102320 ** to virtual table cursors are set. This is used to selectively disable
102321 ** the OR-to-IN transformation in exprAnalyzeOrTerm(). It is not helpful
102322 ** with virtual tables.
102324 ** Note that bitmasks are created for all pTabList->nSrc tables in
102325 ** pTabList, not just the first nTabList tables. nTabList is normally
102326 ** equal to pTabList->nSrc but might be shortened to 1 if the
102327 ** WHERE_ONETABLE_ONLY flag is set.
102329 assert( pWC->vmask==0 && pMaskSet->n==0 );
102330 for(i=0; i<pTabList->nSrc; i++){
102331 createMask(pMaskSet, pTabList->a[i].iCursor);
102332 #ifndef SQLITE_OMIT_VIRTUALTABLE
102333 if( ALWAYS(pTabList->a[i].pTab) && IsVirtual(pTabList->a[i].pTab) ){
102334 pWC->vmask |= ((Bitmask)1 << i);
102336 #endif
102338 #ifndef NDEBUG
102340 Bitmask toTheLeft = 0;
102341 for(i=0; i<pTabList->nSrc; i++){
102342 Bitmask m = getMask(pMaskSet, pTabList->a[i].iCursor);
102343 assert( (m-1)==toTheLeft );
102344 toTheLeft |= m;
102347 #endif
102349 /* Analyze all of the subexpressions. Note that exprAnalyze() might
102350 ** add new virtual terms onto the end of the WHERE clause. We do not
102351 ** want to analyze these virtual terms, so start analyzing at the end
102352 ** and work forward so that the added virtual terms are never processed.
102354 exprAnalyzeAll(pTabList, pWC);
102355 if( db->mallocFailed ){
102356 goto whereBeginError;
102359 /* Chose the best index to use for each table in the FROM clause.
102361 ** This loop fills in the following fields:
102363 ** pWInfo->a[].pIdx The index to use for this level of the loop.
102364 ** pWInfo->a[].wsFlags WHERE_xxx flags associated with pIdx
102365 ** pWInfo->a[].nEq The number of == and IN constraints
102366 ** pWInfo->a[].iFrom Which term of the FROM clause is being coded
102367 ** pWInfo->a[].iTabCur The VDBE cursor for the database table
102368 ** pWInfo->a[].iIdxCur The VDBE cursor for the index
102369 ** pWInfo->a[].pTerm When wsFlags==WO_OR, the OR-clause term
102371 ** This loop also figures out the nesting order of tables in the FROM
102372 ** clause.
102374 notReady = ~(Bitmask)0;
102375 andFlags = ~0;
102376 WHERETRACE(("*** Optimizer Start ***\n"));
102377 for(i=iFrom=0, pLevel=pWInfo->a; i<nTabList; i++, pLevel++){
102378 WhereCost bestPlan; /* Most efficient plan seen so far */
102379 Index *pIdx; /* Index for FROM table at pTabItem */
102380 int j; /* For looping over FROM tables */
102381 int bestJ = -1; /* The value of j */
102382 Bitmask m; /* Bitmask value for j or bestJ */
102383 int isOptimal; /* Iterator for optimal/non-optimal search */
102384 int nUnconstrained; /* Number tables without INDEXED BY */
102385 Bitmask notIndexed; /* Mask of tables that cannot use an index */
102387 memset(&bestPlan, 0, sizeof(bestPlan));
102388 bestPlan.rCost = SQLITE_BIG_DBL;
102389 WHERETRACE(("*** Begin search for loop %d ***\n", i));
102391 /* Loop through the remaining entries in the FROM clause to find the
102392 ** next nested loop. The loop tests all FROM clause entries
102393 ** either once or twice.
102395 ** The first test is always performed if there are two or more entries
102396 ** remaining and never performed if there is only one FROM clause entry
102397 ** to choose from. The first test looks for an "optimal" scan. In
102398 ** this context an optimal scan is one that uses the same strategy
102399 ** for the given FROM clause entry as would be selected if the entry
102400 ** were used as the innermost nested loop. In other words, a table
102401 ** is chosen such that the cost of running that table cannot be reduced
102402 ** by waiting for other tables to run first. This "optimal" test works
102403 ** by first assuming that the FROM clause is on the inner loop and finding
102404 ** its query plan, then checking to see if that query plan uses any
102405 ** other FROM clause terms that are notReady. If no notReady terms are
102406 ** used then the "optimal" query plan works.
102408 ** Note that the WhereCost.nRow parameter for an optimal scan might
102409 ** not be as small as it would be if the table really were the innermost
102410 ** join. The nRow value can be reduced by WHERE clause constraints
102411 ** that do not use indices. But this nRow reduction only happens if the
102412 ** table really is the innermost join.
102414 ** The second loop iteration is only performed if no optimal scan
102415 ** strategies were found by the first iteration. This second iteration
102416 ** is used to search for the lowest cost scan overall.
102418 ** Previous versions of SQLite performed only the second iteration -
102419 ** the next outermost loop was always that with the lowest overall
102420 ** cost. However, this meant that SQLite could select the wrong plan
102421 ** for scripts such as the following:
102423 ** CREATE TABLE t1(a, b);
102424 ** CREATE TABLE t2(c, d);
102425 ** SELECT * FROM t2, t1 WHERE t2.rowid = t1.a;
102427 ** The best strategy is to iterate through table t1 first. However it
102428 ** is not possible to determine this with a simple greedy algorithm.
102429 ** Since the cost of a linear scan through table t2 is the same
102430 ** as the cost of a linear scan through table t1, a simple greedy
102431 ** algorithm may choose to use t2 for the outer loop, which is a much
102432 ** costlier approach.
102434 nUnconstrained = 0;
102435 notIndexed = 0;
102436 for(isOptimal=(iFrom<nTabList-1); isOptimal>=0 && bestJ<0; isOptimal--){
102437 Bitmask mask; /* Mask of tables not yet ready */
102438 for(j=iFrom, pTabItem=&pTabList->a[j]; j<nTabList; j++, pTabItem++){
102439 int doNotReorder; /* True if this table should not be reordered */
102440 WhereCost sCost; /* Cost information from best[Virtual]Index() */
102441 ExprList *pOrderBy; /* ORDER BY clause for index to optimize */
102443 doNotReorder = (pTabItem->jointype & (JT_LEFT|JT_CROSS))!=0;
102444 if( j!=iFrom && doNotReorder ) break;
102445 m = getMask(pMaskSet, pTabItem->iCursor);
102446 if( (m & notReady)==0 ){
102447 if( j==iFrom ) iFrom++;
102448 continue;
102450 mask = (isOptimal ? m : notReady);
102451 pOrderBy = ((i==0 && ppOrderBy )?*ppOrderBy:0);
102452 if( pTabItem->pIndex==0 ) nUnconstrained++;
102454 WHERETRACE(("=== trying table %d with isOptimal=%d ===\n",
102455 j, isOptimal));
102456 assert( pTabItem->pTab );
102457 #ifndef SQLITE_OMIT_VIRTUALTABLE
102458 if( IsVirtual(pTabItem->pTab) ){
102459 sqlite3_index_info **pp = &pWInfo->a[j].pIdxInfo;
102460 bestVirtualIndex(pParse, pWC, pTabItem, mask, notReady, pOrderBy,
102461 &sCost, pp);
102462 }else
102463 #endif
102465 bestBtreeIndex(pParse, pWC, pTabItem, mask, notReady, pOrderBy,
102466 &sCost);
102468 assert( isOptimal || (sCost.used&notReady)==0 );
102470 /* If an INDEXED BY clause is present, then the plan must use that
102471 ** index if it uses any index at all */
102472 assert( pTabItem->pIndex==0
102473 || (sCost.plan.wsFlags & WHERE_NOT_FULLSCAN)==0
102474 || sCost.plan.u.pIdx==pTabItem->pIndex );
102476 if( isOptimal && (sCost.plan.wsFlags & WHERE_NOT_FULLSCAN)==0 ){
102477 notIndexed |= m;
102480 /* Conditions under which this table becomes the best so far:
102482 ** (1) The table must not depend on other tables that have not
102483 ** yet run.
102485 ** (2) A full-table-scan plan cannot supercede indexed plan unless
102486 ** the full-table-scan is an "optimal" plan as defined above.
102488 ** (3) All tables have an INDEXED BY clause or this table lacks an
102489 ** INDEXED BY clause or this table uses the specific
102490 ** index specified by its INDEXED BY clause. This rule ensures
102491 ** that a best-so-far is always selected even if an impossible
102492 ** combination of INDEXED BY clauses are given. The error
102493 ** will be detected and relayed back to the application later.
102494 ** The NEVER() comes about because rule (2) above prevents
102495 ** An indexable full-table-scan from reaching rule (3).
102497 ** (4) The plan cost must be lower than prior plans or else the
102498 ** cost must be the same and the number of rows must be lower.
102500 if( (sCost.used&notReady)==0 /* (1) */
102501 && (bestJ<0 || (notIndexed&m)!=0 /* (2) */
102502 || (bestPlan.plan.wsFlags & WHERE_NOT_FULLSCAN)==0
102503 || (sCost.plan.wsFlags & WHERE_NOT_FULLSCAN)!=0)
102504 && (nUnconstrained==0 || pTabItem->pIndex==0 /* (3) */
102505 || NEVER((sCost.plan.wsFlags & WHERE_NOT_FULLSCAN)!=0))
102506 && (bestJ<0 || sCost.rCost<bestPlan.rCost /* (4) */
102507 || (sCost.rCost<=bestPlan.rCost
102508 && sCost.plan.nRow<bestPlan.plan.nRow))
102510 WHERETRACE(("=== table %d is best so far"
102511 " with cost=%g and nRow=%g\n",
102512 j, sCost.rCost, sCost.plan.nRow));
102513 bestPlan = sCost;
102514 bestJ = j;
102516 if( doNotReorder ) break;
102519 assert( bestJ>=0 );
102520 assert( notReady & getMask(pMaskSet, pTabList->a[bestJ].iCursor) );
102521 WHERETRACE(("*** Optimizer selects table %d for loop %d"
102522 " with cost=%g and nRow=%g\n",
102523 bestJ, pLevel-pWInfo->a, bestPlan.rCost, bestPlan.plan.nRow));
102524 if( (bestPlan.plan.wsFlags & WHERE_ORDERBY)!=0 ){
102525 *ppOrderBy = 0;
102527 andFlags &= bestPlan.plan.wsFlags;
102528 pLevel->plan = bestPlan.plan;
102529 testcase( bestPlan.plan.wsFlags & WHERE_INDEXED );
102530 testcase( bestPlan.plan.wsFlags & WHERE_TEMP_INDEX );
102531 if( bestPlan.plan.wsFlags & (WHERE_INDEXED|WHERE_TEMP_INDEX) ){
102532 pLevel->iIdxCur = pParse->nTab++;
102533 }else{
102534 pLevel->iIdxCur = -1;
102536 notReady &= ~getMask(pMaskSet, pTabList->a[bestJ].iCursor);
102537 pLevel->iFrom = (u8)bestJ;
102538 if( bestPlan.plan.nRow>=(double)1 ){
102539 pParse->nQueryLoop *= bestPlan.plan.nRow;
102542 /* Check that if the table scanned by this loop iteration had an
102543 ** INDEXED BY clause attached to it, that the named index is being
102544 ** used for the scan. If not, then query compilation has failed.
102545 ** Return an error.
102547 pIdx = pTabList->a[bestJ].pIndex;
102548 if( pIdx ){
102549 if( (bestPlan.plan.wsFlags & WHERE_INDEXED)==0 ){
102550 sqlite3ErrorMsg(pParse, "cannot use index: %s", pIdx->zName);
102551 goto whereBeginError;
102552 }else{
102553 /* If an INDEXED BY clause is used, the bestIndex() function is
102554 ** guaranteed to find the index specified in the INDEXED BY clause
102555 ** if it find an index at all. */
102556 assert( bestPlan.plan.u.pIdx==pIdx );
102560 WHERETRACE(("*** Optimizer Finished ***\n"));
102561 if( pParse->nErr || db->mallocFailed ){
102562 goto whereBeginError;
102565 /* If the total query only selects a single row, then the ORDER BY
102566 ** clause is irrelevant.
102568 if( (andFlags & WHERE_UNIQUE)!=0 && ppOrderBy ){
102569 *ppOrderBy = 0;
102572 /* If the caller is an UPDATE or DELETE statement that is requesting
102573 ** to use a one-pass algorithm, determine if this is appropriate.
102574 ** The one-pass algorithm only works if the WHERE clause constraints
102575 ** the statement to update a single row.
102577 assert( (wctrlFlags & WHERE_ONEPASS_DESIRED)==0 || pWInfo->nLevel==1 );
102578 if( (wctrlFlags & WHERE_ONEPASS_DESIRED)!=0 && (andFlags & WHERE_UNIQUE)!=0 ){
102579 pWInfo->okOnePass = 1;
102580 pWInfo->a[0].plan.wsFlags &= ~WHERE_IDX_ONLY;
102583 /* Open all tables in the pTabList and any indices selected for
102584 ** searching those tables.
102586 sqlite3CodeVerifySchema(pParse, -1); /* Insert the cookie verifier Goto */
102587 notReady = ~(Bitmask)0;
102588 pWInfo->nRowOut = (double)1;
102589 for(i=0, pLevel=pWInfo->a; i<nTabList; i++, pLevel++){
102590 Table *pTab; /* Table to open */
102591 int iDb; /* Index of database containing table/index */
102593 pTabItem = &pTabList->a[pLevel->iFrom];
102594 pTab = pTabItem->pTab;
102595 pLevel->iTabCur = pTabItem->iCursor;
102596 pWInfo->nRowOut *= pLevel->plan.nRow;
102597 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
102598 if( (pTab->tabFlags & TF_Ephemeral)!=0 || pTab->pSelect ){
102599 /* Do nothing */
102600 }else
102601 #ifndef SQLITE_OMIT_VIRTUALTABLE
102602 if( (pLevel->plan.wsFlags & WHERE_VIRTUALTABLE)!=0 ){
102603 const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
102604 int iCur = pTabItem->iCursor;
102605 sqlite3VdbeAddOp4(v, OP_VOpen, iCur, 0, 0, pVTab, P4_VTAB);
102606 }else
102607 #endif
102608 if( (pLevel->plan.wsFlags & WHERE_IDX_ONLY)==0
102609 && (wctrlFlags & WHERE_OMIT_OPEN)==0 ){
102610 int op = pWInfo->okOnePass ? OP_OpenWrite : OP_OpenRead;
102611 sqlite3OpenTable(pParse, pTabItem->iCursor, iDb, pTab, op);
102612 testcase( pTab->nCol==BMS-1 );
102613 testcase( pTab->nCol==BMS );
102614 if( !pWInfo->okOnePass && pTab->nCol<BMS ){
102615 Bitmask b = pTabItem->colUsed;
102616 int n = 0;
102617 for(; b; b=b>>1, n++){}
102618 sqlite3VdbeChangeP4(v, sqlite3VdbeCurrentAddr(v)-1,
102619 SQLITE_INT_TO_PTR(n), P4_INT32);
102620 assert( n<=pTab->nCol );
102622 }else{
102623 sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
102625 #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
102626 if( (pLevel->plan.wsFlags & WHERE_TEMP_INDEX)!=0 ){
102627 constructAutomaticIndex(pParse, pWC, pTabItem, notReady, pLevel);
102628 }else
102629 #endif
102630 if( (pLevel->plan.wsFlags & WHERE_INDEXED)!=0 ){
102631 Index *pIx = pLevel->plan.u.pIdx;
102632 KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIx);
102633 int iIdxCur = pLevel->iIdxCur;
102634 assert( pIx->pSchema==pTab->pSchema );
102635 assert( iIdxCur>=0 );
102636 sqlite3VdbeAddOp4(v, OP_OpenRead, iIdxCur, pIx->tnum, iDb,
102637 (char*)pKey, P4_KEYINFO_HANDOFF);
102638 VdbeComment((v, "%s", pIx->zName));
102640 sqlite3CodeVerifySchema(pParse, iDb);
102641 notReady &= ~getMask(pWC->pMaskSet, pTabItem->iCursor);
102643 pWInfo->iTop = sqlite3VdbeCurrentAddr(v);
102644 if( db->mallocFailed ) goto whereBeginError;
102646 /* Generate the code to do the search. Each iteration of the for
102647 ** loop below generates code for a single nested loop of the VM
102648 ** program.
102650 notReady = ~(Bitmask)0;
102651 for(i=0; i<nTabList; i++){
102652 pLevel = &pWInfo->a[i];
102653 explainOneScan(pParse, pTabList, pLevel, i, pLevel->iFrom, wctrlFlags);
102654 notReady = codeOneLoopStart(pWInfo, i, wctrlFlags, notReady);
102655 pWInfo->iContinue = pLevel->addrCont;
102658 #ifdef SQLITE_TEST /* For testing and debugging use only */
102659 /* Record in the query plan information about the current table
102660 ** and the index used to access it (if any). If the table itself
102661 ** is not used, its name is just '{}'. If no index is used
102662 ** the index is listed as "{}". If the primary key is used the
102663 ** index name is '*'.
102665 for(i=0; i<nTabList; i++){
102666 char *z;
102667 int n;
102668 pLevel = &pWInfo->a[i];
102669 pTabItem = &pTabList->a[pLevel->iFrom];
102670 z = pTabItem->zAlias;
102671 if( z==0 ) z = pTabItem->pTab->zName;
102672 n = sqlite3Strlen30(z);
102673 if( n+nQPlan < sizeof(sqlite3_query_plan)-10 ){
102674 if( pLevel->plan.wsFlags & WHERE_IDX_ONLY ){
102675 memcpy(&sqlite3_query_plan[nQPlan], "{}", 2);
102676 nQPlan += 2;
102677 }else{
102678 memcpy(&sqlite3_query_plan[nQPlan], z, n);
102679 nQPlan += n;
102681 sqlite3_query_plan[nQPlan++] = ' ';
102683 testcase( pLevel->plan.wsFlags & WHERE_ROWID_EQ );
102684 testcase( pLevel->plan.wsFlags & WHERE_ROWID_RANGE );
102685 if( pLevel->plan.wsFlags & (WHERE_ROWID_EQ|WHERE_ROWID_RANGE) ){
102686 memcpy(&sqlite3_query_plan[nQPlan], "* ", 2);
102687 nQPlan += 2;
102688 }else if( (pLevel->plan.wsFlags & WHERE_INDEXED)!=0 ){
102689 n = sqlite3Strlen30(pLevel->plan.u.pIdx->zName);
102690 if( n+nQPlan < sizeof(sqlite3_query_plan)-2 ){
102691 memcpy(&sqlite3_query_plan[nQPlan], pLevel->plan.u.pIdx->zName, n);
102692 nQPlan += n;
102693 sqlite3_query_plan[nQPlan++] = ' ';
102695 }else{
102696 memcpy(&sqlite3_query_plan[nQPlan], "{} ", 3);
102697 nQPlan += 3;
102700 while( nQPlan>0 && sqlite3_query_plan[nQPlan-1]==' ' ){
102701 sqlite3_query_plan[--nQPlan] = 0;
102703 sqlite3_query_plan[nQPlan] = 0;
102704 nQPlan = 0;
102705 #endif /* SQLITE_TEST // Testing and debugging use only */
102707 /* Record the continuation address in the WhereInfo structure. Then
102708 ** clean up and return.
102710 return pWInfo;
102712 /* Jump here if malloc fails */
102713 whereBeginError:
102714 if( pWInfo ){
102715 pParse->nQueryLoop = pWInfo->savedNQueryLoop;
102716 whereInfoFree(db, pWInfo);
102718 return 0;
102722 ** Generate the end of the WHERE loop. See comments on
102723 ** sqlite3WhereBegin() for additional information.
102725 SQLITE_PRIVATE void sqlite3WhereEnd(WhereInfo *pWInfo){
102726 Parse *pParse = pWInfo->pParse;
102727 Vdbe *v = pParse->pVdbe;
102728 int i;
102729 WhereLevel *pLevel;
102730 SrcList *pTabList = pWInfo->pTabList;
102731 sqlite3 *db = pParse->db;
102733 /* Generate loop termination code.
102735 sqlite3ExprCacheClear(pParse);
102736 for(i=pWInfo->nLevel-1; i>=0; i--){
102737 pLevel = &pWInfo->a[i];
102738 sqlite3VdbeResolveLabel(v, pLevel->addrCont);
102739 if( pLevel->op!=OP_Noop ){
102740 sqlite3VdbeAddOp2(v, pLevel->op, pLevel->p1, pLevel->p2);
102741 sqlite3VdbeChangeP5(v, pLevel->p5);
102743 if( pLevel->plan.wsFlags & WHERE_IN_ABLE && pLevel->u.in.nIn>0 ){
102744 struct InLoop *pIn;
102745 int j;
102746 sqlite3VdbeResolveLabel(v, pLevel->addrNxt);
102747 for(j=pLevel->u.in.nIn, pIn=&pLevel->u.in.aInLoop[j-1]; j>0; j--, pIn--){
102748 sqlite3VdbeJumpHere(v, pIn->addrInTop+1);
102749 sqlite3VdbeAddOp2(v, OP_Next, pIn->iCur, pIn->addrInTop);
102750 sqlite3VdbeJumpHere(v, pIn->addrInTop-1);
102752 sqlite3DbFree(db, pLevel->u.in.aInLoop);
102754 sqlite3VdbeResolveLabel(v, pLevel->addrBrk);
102755 if( pLevel->iLeftJoin ){
102756 int addr;
102757 addr = sqlite3VdbeAddOp1(v, OP_IfPos, pLevel->iLeftJoin);
102758 assert( (pLevel->plan.wsFlags & WHERE_IDX_ONLY)==0
102759 || (pLevel->plan.wsFlags & WHERE_INDEXED)!=0 );
102760 if( (pLevel->plan.wsFlags & WHERE_IDX_ONLY)==0 ){
102761 sqlite3VdbeAddOp1(v, OP_NullRow, pTabList->a[i].iCursor);
102763 if( pLevel->iIdxCur>=0 ){
102764 sqlite3VdbeAddOp1(v, OP_NullRow, pLevel->iIdxCur);
102766 if( pLevel->op==OP_Return ){
102767 sqlite3VdbeAddOp2(v, OP_Gosub, pLevel->p1, pLevel->addrFirst);
102768 }else{
102769 sqlite3VdbeAddOp2(v, OP_Goto, 0, pLevel->addrFirst);
102771 sqlite3VdbeJumpHere(v, addr);
102775 /* The "break" point is here, just past the end of the outer loop.
102776 ** Set it.
102778 sqlite3VdbeResolveLabel(v, pWInfo->iBreak);
102780 /* Close all of the cursors that were opened by sqlite3WhereBegin.
102782 assert( pWInfo->nLevel==1 || pWInfo->nLevel==pTabList->nSrc );
102783 for(i=0, pLevel=pWInfo->a; i<pWInfo->nLevel; i++, pLevel++){
102784 struct SrcList_item *pTabItem = &pTabList->a[pLevel->iFrom];
102785 Table *pTab = pTabItem->pTab;
102786 assert( pTab!=0 );
102787 if( (pTab->tabFlags & TF_Ephemeral)==0
102788 && pTab->pSelect==0
102789 && (pWInfo->wctrlFlags & WHERE_OMIT_CLOSE)==0
102791 int ws = pLevel->plan.wsFlags;
102792 if( !pWInfo->okOnePass && (ws & WHERE_IDX_ONLY)==0 ){
102793 sqlite3VdbeAddOp1(v, OP_Close, pTabItem->iCursor);
102795 if( (ws & WHERE_INDEXED)!=0 && (ws & WHERE_TEMP_INDEX)==0 ){
102796 sqlite3VdbeAddOp1(v, OP_Close, pLevel->iIdxCur);
102800 /* If this scan uses an index, make code substitutions to read data
102801 ** from the index in preference to the table. Sometimes, this means
102802 ** the table need never be read from. This is a performance boost,
102803 ** as the vdbe level waits until the table is read before actually
102804 ** seeking the table cursor to the record corresponding to the current
102805 ** position in the index.
102807 ** Calls to the code generator in between sqlite3WhereBegin and
102808 ** sqlite3WhereEnd will have created code that references the table
102809 ** directly. This loop scans all that code looking for opcodes
102810 ** that reference the table and converts them into opcodes that
102811 ** reference the index.
102813 if( (pLevel->plan.wsFlags & WHERE_INDEXED)!=0 && !db->mallocFailed){
102814 int k, j, last;
102815 VdbeOp *pOp;
102816 Index *pIdx = pLevel->plan.u.pIdx;
102818 assert( pIdx!=0 );
102819 pOp = sqlite3VdbeGetOp(v, pWInfo->iTop);
102820 last = sqlite3VdbeCurrentAddr(v);
102821 for(k=pWInfo->iTop; k<last; k++, pOp++){
102822 if( pOp->p1!=pLevel->iTabCur ) continue;
102823 if( pOp->opcode==OP_Column ){
102824 for(j=0; j<pIdx->nColumn; j++){
102825 if( pOp->p2==pIdx->aiColumn[j] ){
102826 pOp->p2 = j;
102827 pOp->p1 = pLevel->iIdxCur;
102828 break;
102831 assert( (pLevel->plan.wsFlags & WHERE_IDX_ONLY)==0
102832 || j<pIdx->nColumn );
102833 }else if( pOp->opcode==OP_Rowid ){
102834 pOp->p1 = pLevel->iIdxCur;
102835 pOp->opcode = OP_IdxRowid;
102841 /* Final cleanup
102843 pParse->nQueryLoop = pWInfo->savedNQueryLoop;
102844 whereInfoFree(db, pWInfo);
102845 return;
102848 /************** End of where.c ***********************************************/
102849 /************** Begin file parse.c *******************************************/
102850 /* Driver template for the LEMON parser generator.
102851 ** The author disclaims copyright to this source code.
102853 ** This version of "lempar.c" is modified, slightly, for use by SQLite.
102854 ** The only modifications are the addition of a couple of NEVER()
102855 ** macros to disable tests that are needed in the case of a general
102856 ** LALR(1) grammar but which are always false in the
102857 ** specific grammar used by SQLite.
102859 /* First off, code is included that follows the "include" declaration
102860 ** in the input grammar file. */
102864 ** Disable all error recovery processing in the parser push-down
102865 ** automaton.
102867 #define YYNOERRORRECOVERY 1
102870 ** Make yytestcase() the same as testcase()
102872 #define yytestcase(X) testcase(X)
102875 ** An instance of this structure holds information about the
102876 ** LIMIT clause of a SELECT statement.
102878 struct LimitVal {
102879 Expr *pLimit; /* The LIMIT expression. NULL if there is no limit */
102880 Expr *pOffset; /* The OFFSET expression. NULL if there is none */
102884 ** An instance of this structure is used to store the LIKE,
102885 ** GLOB, NOT LIKE, and NOT GLOB operators.
102887 struct LikeOp {
102888 Token eOperator; /* "like" or "glob" or "regexp" */
102889 int not; /* True if the NOT keyword is present */
102893 ** An instance of the following structure describes the event of a
102894 ** TRIGGER. "a" is the event type, one of TK_UPDATE, TK_INSERT,
102895 ** TK_DELETE, or TK_INSTEAD. If the event is of the form
102897 ** UPDATE ON (a,b,c)
102899 ** Then the "b" IdList records the list "a,b,c".
102901 struct TrigEvent { int a; IdList * b; };
102904 ** An instance of this structure holds the ATTACH key and the key type.
102906 struct AttachKey { int type; Token key; };
102909 /* This is a utility routine used to set the ExprSpan.zStart and
102910 ** ExprSpan.zEnd values of pOut so that the span covers the complete
102911 ** range of text beginning with pStart and going to the end of pEnd.
102913 static void spanSet(ExprSpan *pOut, Token *pStart, Token *pEnd){
102914 pOut->zStart = pStart->z;
102915 pOut->zEnd = &pEnd->z[pEnd->n];
102918 /* Construct a new Expr object from a single identifier. Use the
102919 ** new Expr to populate pOut. Set the span of pOut to be the identifier
102920 ** that created the expression.
102922 static void spanExpr(ExprSpan *pOut, Parse *pParse, int op, Token *pValue){
102923 pOut->pExpr = sqlite3PExpr(pParse, op, 0, 0, pValue);
102924 pOut->zStart = pValue->z;
102925 pOut->zEnd = &pValue->z[pValue->n];
102928 /* This routine constructs a binary expression node out of two ExprSpan
102929 ** objects and uses the result to populate a new ExprSpan object.
102931 static void spanBinaryExpr(
102932 ExprSpan *pOut, /* Write the result here */
102933 Parse *pParse, /* The parsing context. Errors accumulate here */
102934 int op, /* The binary operation */
102935 ExprSpan *pLeft, /* The left operand */
102936 ExprSpan *pRight /* The right operand */
102938 pOut->pExpr = sqlite3PExpr(pParse, op, pLeft->pExpr, pRight->pExpr, 0);
102939 pOut->zStart = pLeft->zStart;
102940 pOut->zEnd = pRight->zEnd;
102943 /* Construct an expression node for a unary postfix operator
102945 static void spanUnaryPostfix(
102946 ExprSpan *pOut, /* Write the new expression node here */
102947 Parse *pParse, /* Parsing context to record errors */
102948 int op, /* The operator */
102949 ExprSpan *pOperand, /* The operand */
102950 Token *pPostOp /* The operand token for setting the span */
102952 pOut->pExpr = sqlite3PExpr(pParse, op, pOperand->pExpr, 0, 0);
102953 pOut->zStart = pOperand->zStart;
102954 pOut->zEnd = &pPostOp->z[pPostOp->n];
102957 /* A routine to convert a binary TK_IS or TK_ISNOT expression into a
102958 ** unary TK_ISNULL or TK_NOTNULL expression. */
102959 static void binaryToUnaryIfNull(Parse *pParse, Expr *pY, Expr *pA, int op){
102960 sqlite3 *db = pParse->db;
102961 if( db->mallocFailed==0 && pY->op==TK_NULL ){
102962 pA->op = (u8)op;
102963 sqlite3ExprDelete(db, pA->pRight);
102964 pA->pRight = 0;
102968 /* Construct an expression node for a unary prefix operator
102970 static void spanUnaryPrefix(
102971 ExprSpan *pOut, /* Write the new expression node here */
102972 Parse *pParse, /* Parsing context to record errors */
102973 int op, /* The operator */
102974 ExprSpan *pOperand, /* The operand */
102975 Token *pPreOp /* The operand token for setting the span */
102977 pOut->pExpr = sqlite3PExpr(pParse, op, pOperand->pExpr, 0, 0);
102978 pOut->zStart = pPreOp->z;
102979 pOut->zEnd = pOperand->zEnd;
102981 /* Next is all token values, in a form suitable for use by makeheaders.
102982 ** This section will be null unless lemon is run with the -m switch.
102985 ** These constants (all generated automatically by the parser generator)
102986 ** specify the various kinds of tokens (terminals) that the parser
102987 ** understands.
102989 ** Each symbol here is a terminal symbol in the grammar.
102991 /* Make sure the INTERFACE macro is defined.
102993 #ifndef INTERFACE
102994 # define INTERFACE 1
102995 #endif
102996 /* The next thing included is series of defines which control
102997 ** various aspects of the generated parser.
102998 ** YYCODETYPE is the data type used for storing terminal
102999 ** and nonterminal numbers. "unsigned char" is
103000 ** used if there are fewer than 250 terminals
103001 ** and nonterminals. "int" is used otherwise.
103002 ** YYNOCODE is a number of type YYCODETYPE which corresponds
103003 ** to no legal terminal or nonterminal number. This
103004 ** number is used to fill in empty slots of the hash
103005 ** table.
103006 ** YYFALLBACK If defined, this indicates that one or more tokens
103007 ** have fall-back values which should be used if the
103008 ** original value of the token will not parse.
103009 ** YYACTIONTYPE is the data type used for storing terminal
103010 ** and nonterminal numbers. "unsigned char" is
103011 ** used if there are fewer than 250 rules and
103012 ** states combined. "int" is used otherwise.
103013 ** sqlite3ParserTOKENTYPE is the data type used for minor tokens given
103014 ** directly to the parser from the tokenizer.
103015 ** YYMINORTYPE is the data type used for all minor tokens.
103016 ** This is typically a union of many types, one of
103017 ** which is sqlite3ParserTOKENTYPE. The entry in the union
103018 ** for base tokens is called "yy0".
103019 ** YYSTACKDEPTH is the maximum depth of the parser's stack. If
103020 ** zero the stack is dynamically sized using realloc()
103021 ** sqlite3ParserARG_SDECL A static variable declaration for the %extra_argument
103022 ** sqlite3ParserARG_PDECL A parameter declaration for the %extra_argument
103023 ** sqlite3ParserARG_STORE Code to store %extra_argument into yypParser
103024 ** sqlite3ParserARG_FETCH Code to extract %extra_argument from yypParser
103025 ** YYNSTATE the combined number of states.
103026 ** YYNRULE the number of rules in the grammar
103027 ** YYERRORSYMBOL is the code number of the error symbol. If not
103028 ** defined, then do no error processing.
103030 #define YYCODETYPE unsigned char
103031 #define YYNOCODE 253
103032 #define YYACTIONTYPE unsigned short int
103033 #define YYWILDCARD 67
103034 #define sqlite3ParserTOKENTYPE Token
103035 typedef union {
103036 int yyinit;
103037 sqlite3ParserTOKENTYPE yy0;
103038 int yy4;
103039 struct TrigEvent yy90;
103040 ExprSpan yy118;
103041 TriggerStep* yy203;
103042 u8 yy210;
103043 struct {int value; int mask;} yy215;
103044 SrcList* yy259;
103045 struct LimitVal yy292;
103046 Expr* yy314;
103047 ExprList* yy322;
103048 struct LikeOp yy342;
103049 IdList* yy384;
103050 Select* yy387;
103051 } YYMINORTYPE;
103052 #ifndef YYSTACKDEPTH
103053 #define YYSTACKDEPTH 100
103054 #endif
103055 #define sqlite3ParserARG_SDECL Parse *pParse;
103056 #define sqlite3ParserARG_PDECL ,Parse *pParse
103057 #define sqlite3ParserARG_FETCH Parse *pParse = yypParser->pParse
103058 #define sqlite3ParserARG_STORE yypParser->pParse = pParse
103059 #define YYNSTATE 630
103060 #define YYNRULE 329
103061 #define YYFALLBACK 1
103062 #define YY_NO_ACTION (YYNSTATE+YYNRULE+2)
103063 #define YY_ACCEPT_ACTION (YYNSTATE+YYNRULE+1)
103064 #define YY_ERROR_ACTION (YYNSTATE+YYNRULE)
103066 /* The yyzerominor constant is used to initialize instances of
103067 ** YYMINORTYPE objects to zero. */
103068 static const YYMINORTYPE yyzerominor = { 0 };
103070 /* Define the yytestcase() macro to be a no-op if is not already defined
103071 ** otherwise.
103073 ** Applications can choose to define yytestcase() in the %include section
103074 ** to a macro that can assist in verifying code coverage. For production
103075 ** code the yytestcase() macro should be turned off. But it is useful
103076 ** for testing.
103078 #ifndef yytestcase
103079 # define yytestcase(X)
103080 #endif
103083 /* Next are the tables used to determine what action to take based on the
103084 ** current state and lookahead token. These tables are used to implement
103085 ** functions that take a state number and lookahead value and return an
103086 ** action integer.
103088 ** Suppose the action integer is N. Then the action is determined as
103089 ** follows
103091 ** 0 <= N < YYNSTATE Shift N. That is, push the lookahead
103092 ** token onto the stack and goto state N.
103094 ** YYNSTATE <= N < YYNSTATE+YYNRULE Reduce by rule N-YYNSTATE.
103096 ** N == YYNSTATE+YYNRULE A syntax error has occurred.
103098 ** N == YYNSTATE+YYNRULE+1 The parser accepts its input.
103100 ** N == YYNSTATE+YYNRULE+2 No such action. Denotes unused
103101 ** slots in the yy_action[] table.
103103 ** The action table is constructed as a single large table named yy_action[].
103104 ** Given state S and lookahead X, the action is computed as
103106 ** yy_action[ yy_shift_ofst[S] + X ]
103108 ** If the index value yy_shift_ofst[S]+X is out of range or if the value
103109 ** yy_lookahead[yy_shift_ofst[S]+X] is not equal to X or if yy_shift_ofst[S]
103110 ** is equal to YY_SHIFT_USE_DFLT, it means that the action is not in the table
103111 ** and that yy_default[S] should be used instead.
103113 ** The formula above is for computing the action when the lookahead is
103114 ** a terminal symbol. If the lookahead is a non-terminal (as occurs after
103115 ** a reduce action) then the yy_reduce_ofst[] array is used in place of
103116 ** the yy_shift_ofst[] array and YY_REDUCE_USE_DFLT is used in place of
103117 ** YY_SHIFT_USE_DFLT.
103119 ** The following are the tables generated in this section:
103121 ** yy_action[] A single table containing all actions.
103122 ** yy_lookahead[] A table containing the lookahead for each entry in
103123 ** yy_action. Used to detect hash collisions.
103124 ** yy_shift_ofst[] For each state, the offset into yy_action for
103125 ** shifting terminals.
103126 ** yy_reduce_ofst[] For each state, the offset into yy_action for
103127 ** shifting non-terminals after a reduce.
103128 ** yy_default[] Default action for each state.
103130 #define YY_ACTTAB_COUNT (1557)
103131 static const YYACTIONTYPE yy_action[] = {
103132 /* 0 */ 313, 960, 186, 419, 2, 172, 627, 597, 55, 55,
103133 /* 10 */ 55, 55, 48, 53, 53, 53, 53, 52, 52, 51,
103134 /* 20 */ 51, 51, 50, 238, 302, 283, 623, 622, 516, 515,
103135 /* 30 */ 590, 584, 55, 55, 55, 55, 282, 53, 53, 53,
103136 /* 40 */ 53, 52, 52, 51, 51, 51, 50, 238, 6, 56,
103137 /* 50 */ 57, 47, 582, 581, 583, 583, 54, 54, 55, 55,
103138 /* 60 */ 55, 55, 608, 53, 53, 53, 53, 52, 52, 51,
103139 /* 70 */ 51, 51, 50, 238, 313, 597, 409, 330, 579, 579,
103140 /* 80 */ 32, 53, 53, 53, 53, 52, 52, 51, 51, 51,
103141 /* 90 */ 50, 238, 330, 217, 620, 619, 166, 411, 624, 382,
103142 /* 100 */ 379, 378, 7, 491, 590, 584, 200, 199, 198, 58,
103143 /* 110 */ 377, 300, 414, 621, 481, 66, 623, 622, 621, 580,
103144 /* 120 */ 254, 601, 94, 56, 57, 47, 582, 581, 583, 583,
103145 /* 130 */ 54, 54, 55, 55, 55, 55, 671, 53, 53, 53,
103146 /* 140 */ 53, 52, 52, 51, 51, 51, 50, 238, 313, 532,
103147 /* 150 */ 226, 506, 507, 133, 177, 139, 284, 385, 279, 384,
103148 /* 160 */ 169, 197, 342, 398, 251, 226, 253, 275, 388, 167,
103149 /* 170 */ 139, 284, 385, 279, 384, 169, 570, 236, 590, 584,
103150 /* 180 */ 672, 240, 275, 157, 620, 619, 554, 437, 51, 51,
103151 /* 190 */ 51, 50, 238, 343, 439, 553, 438, 56, 57, 47,
103152 /* 200 */ 582, 581, 583, 583, 54, 54, 55, 55, 55, 55,
103153 /* 210 */ 465, 53, 53, 53, 53, 52, 52, 51, 51, 51,
103154 /* 220 */ 50, 238, 313, 390, 52, 52, 51, 51, 51, 50,
103155 /* 230 */ 238, 391, 166, 491, 566, 382, 379, 378, 409, 440,
103156 /* 240 */ 579, 579, 252, 440, 607, 66, 377, 513, 621, 49,
103157 /* 250 */ 46, 147, 590, 584, 621, 16, 466, 189, 621, 441,
103158 /* 260 */ 442, 673, 526, 441, 340, 577, 595, 64, 194, 482,
103159 /* 270 */ 434, 56, 57, 47, 582, 581, 583, 583, 54, 54,
103160 /* 280 */ 55, 55, 55, 55, 30, 53, 53, 53, 53, 52,
103161 /* 290 */ 52, 51, 51, 51, 50, 238, 313, 593, 593, 593,
103162 /* 300 */ 387, 578, 606, 493, 259, 351, 258, 411, 1, 623,
103163 /* 310 */ 622, 496, 623, 622, 65, 240, 623, 622, 597, 443,
103164 /* 320 */ 237, 239, 414, 341, 237, 602, 590, 584, 18, 603,
103165 /* 330 */ 166, 601, 87, 382, 379, 378, 67, 623, 622, 38,
103166 /* 340 */ 623, 622, 176, 270, 377, 56, 57, 47, 582, 581,
103167 /* 350 */ 583, 583, 54, 54, 55, 55, 55, 55, 175, 53,
103168 /* 360 */ 53, 53, 53, 52, 52, 51, 51, 51, 50, 238,
103169 /* 370 */ 313, 396, 233, 411, 531, 565, 317, 620, 619, 44,
103170 /* 380 */ 620, 619, 240, 206, 620, 619, 597, 266, 414, 268,
103171 /* 390 */ 409, 597, 579, 579, 352, 184, 505, 601, 73, 533,
103172 /* 400 */ 590, 584, 466, 548, 190, 620, 619, 576, 620, 619,
103173 /* 410 */ 547, 383, 551, 35, 332, 575, 574, 600, 504, 56,
103174 /* 420 */ 57, 47, 582, 581, 583, 583, 54, 54, 55, 55,
103175 /* 430 */ 55, 55, 567, 53, 53, 53, 53, 52, 52, 51,
103176 /* 440 */ 51, 51, 50, 238, 313, 411, 561, 561, 528, 364,
103177 /* 450 */ 259, 351, 258, 183, 361, 549, 524, 374, 411, 597,
103178 /* 460 */ 414, 240, 560, 560, 409, 604, 579, 579, 328, 601,
103179 /* 470 */ 93, 623, 622, 414, 590, 584, 237, 564, 559, 559,
103180 /* 480 */ 520, 402, 601, 87, 409, 210, 579, 579, 168, 421,
103181 /* 490 */ 950, 519, 950, 56, 57, 47, 582, 581, 583, 583,
103182 /* 500 */ 54, 54, 55, 55, 55, 55, 192, 53, 53, 53,
103183 /* 510 */ 53, 52, 52, 51, 51, 51, 50, 238, 313, 600,
103184 /* 520 */ 293, 563, 511, 234, 357, 146, 475, 475, 367, 411,
103185 /* 530 */ 562, 411, 358, 542, 425, 171, 411, 215, 144, 620,
103186 /* 540 */ 619, 544, 318, 353, 414, 203, 414, 275, 590, 584,
103187 /* 550 */ 549, 414, 174, 601, 94, 601, 79, 558, 471, 61,
103188 /* 560 */ 601, 79, 421, 949, 350, 949, 34, 56, 57, 47,
103189 /* 570 */ 582, 581, 583, 583, 54, 54, 55, 55, 55, 55,
103190 /* 580 */ 535, 53, 53, 53, 53, 52, 52, 51, 51, 51,
103191 /* 590 */ 50, 238, 313, 307, 424, 394, 272, 49, 46, 147,
103192 /* 600 */ 349, 322, 4, 411, 491, 312, 321, 425, 568, 492,
103193 /* 610 */ 216, 264, 407, 575, 574, 429, 66, 549, 414, 621,
103194 /* 620 */ 540, 602, 590, 584, 13, 603, 621, 601, 72, 12,
103195 /* 630 */ 618, 617, 616, 202, 210, 621, 546, 469, 422, 319,
103196 /* 640 */ 148, 56, 57, 47, 582, 581, 583, 583, 54, 54,
103197 /* 650 */ 55, 55, 55, 55, 338, 53, 53, 53, 53, 52,
103198 /* 660 */ 52, 51, 51, 51, 50, 238, 313, 600, 600, 411,
103199 /* 670 */ 39, 21, 37, 170, 237, 875, 411, 572, 572, 201,
103200 /* 680 */ 144, 473, 538, 331, 414, 474, 143, 146, 630, 628,
103201 /* 690 */ 334, 414, 353, 601, 68, 168, 590, 584, 132, 365,
103202 /* 700 */ 601, 96, 307, 423, 530, 336, 49, 46, 147, 568,
103203 /* 710 */ 406, 216, 549, 360, 529, 56, 57, 47, 582, 581,
103204 /* 720 */ 583, 583, 54, 54, 55, 55, 55, 55, 411, 53,
103205 /* 730 */ 53, 53, 53, 52, 52, 51, 51, 51, 50, 238,
103206 /* 740 */ 313, 411, 605, 414, 484, 510, 172, 422, 597, 318,
103207 /* 750 */ 496, 485, 601, 99, 411, 142, 414, 411, 231, 411,
103208 /* 760 */ 540, 411, 359, 629, 2, 601, 97, 426, 308, 414,
103209 /* 770 */ 590, 584, 414, 20, 414, 621, 414, 621, 601, 106,
103210 /* 780 */ 503, 601, 105, 601, 108, 601, 109, 204, 28, 56,
103211 /* 790 */ 57, 47, 582, 581, 583, 583, 54, 54, 55, 55,
103212 /* 800 */ 55, 55, 411, 53, 53, 53, 53, 52, 52, 51,
103213 /* 810 */ 51, 51, 50, 238, 313, 411, 597, 414, 411, 276,
103214 /* 820 */ 214, 600, 411, 366, 213, 381, 601, 134, 274, 500,
103215 /* 830 */ 414, 167, 130, 414, 621, 411, 354, 414, 376, 601,
103216 /* 840 */ 135, 129, 601, 100, 590, 584, 601, 104, 522, 521,
103217 /* 850 */ 414, 621, 224, 273, 600, 167, 327, 282, 600, 601,
103218 /* 860 */ 103, 468, 521, 56, 57, 47, 582, 581, 583, 583,
103219 /* 870 */ 54, 54, 55, 55, 55, 55, 411, 53, 53, 53,
103220 /* 880 */ 53, 52, 52, 51, 51, 51, 50, 238, 313, 411,
103221 /* 890 */ 27, 414, 411, 375, 276, 167, 359, 544, 50, 238,
103222 /* 900 */ 601, 95, 128, 223, 414, 411, 165, 414, 411, 621,
103223 /* 910 */ 411, 621, 612, 601, 102, 372, 601, 76, 590, 584,
103224 /* 920 */ 414, 570, 236, 414, 470, 414, 167, 621, 188, 601,
103225 /* 930 */ 98, 225, 601, 138, 601, 137, 232, 56, 45, 47,
103226 /* 940 */ 582, 581, 583, 583, 54, 54, 55, 55, 55, 55,
103227 /* 950 */ 411, 53, 53, 53, 53, 52, 52, 51, 51, 51,
103228 /* 960 */ 50, 238, 313, 276, 276, 414, 411, 276, 544, 459,
103229 /* 970 */ 359, 171, 209, 479, 601, 136, 628, 334, 621, 621,
103230 /* 980 */ 125, 414, 621, 368, 411, 621, 257, 540, 589, 588,
103231 /* 990 */ 601, 75, 590, 584, 458, 446, 23, 23, 124, 414,
103232 /* 1000 */ 326, 325, 621, 427, 324, 309, 600, 288, 601, 92,
103233 /* 1010 */ 586, 585, 57, 47, 582, 581, 583, 583, 54, 54,
103234 /* 1020 */ 55, 55, 55, 55, 411, 53, 53, 53, 53, 52,
103235 /* 1030 */ 52, 51, 51, 51, 50, 238, 313, 587, 411, 414,
103236 /* 1040 */ 411, 207, 611, 476, 171, 472, 160, 123, 601, 91,
103237 /* 1050 */ 323, 261, 15, 414, 464, 414, 411, 621, 411, 354,
103238 /* 1060 */ 222, 411, 601, 74, 601, 90, 590, 584, 159, 264,
103239 /* 1070 */ 158, 414, 461, 414, 621, 600, 414, 121, 120, 25,
103240 /* 1080 */ 601, 89, 601, 101, 621, 601, 88, 47, 582, 581,
103241 /* 1090 */ 583, 583, 54, 54, 55, 55, 55, 55, 544, 53,
103242 /* 1100 */ 53, 53, 53, 52, 52, 51, 51, 51, 50, 238,
103243 /* 1110 */ 43, 405, 263, 3, 610, 264, 140, 415, 622, 24,
103244 /* 1120 */ 410, 11, 456, 594, 118, 155, 219, 452, 408, 621,
103245 /* 1130 */ 621, 621, 156, 43, 405, 621, 3, 286, 621, 113,
103246 /* 1140 */ 415, 622, 111, 445, 411, 400, 557, 403, 545, 10,
103247 /* 1150 */ 411, 408, 264, 110, 205, 436, 541, 566, 453, 414,
103248 /* 1160 */ 621, 621, 63, 621, 435, 414, 411, 621, 601, 94,
103249 /* 1170 */ 403, 621, 411, 337, 601, 86, 150, 40, 41, 534,
103250 /* 1180 */ 566, 414, 242, 264, 42, 413, 412, 414, 600, 595,
103251 /* 1190 */ 601, 85, 191, 333, 107, 451, 601, 84, 621, 539,
103252 /* 1200 */ 40, 41, 420, 230, 411, 149, 316, 42, 413, 412,
103253 /* 1210 */ 398, 127, 595, 315, 621, 399, 278, 625, 181, 414,
103254 /* 1220 */ 593, 593, 593, 592, 591, 14, 450, 411, 601, 71,
103255 /* 1230 */ 240, 621, 43, 405, 264, 3, 615, 180, 264, 415,
103256 /* 1240 */ 622, 614, 414, 593, 593, 593, 592, 591, 14, 621,
103257 /* 1250 */ 408, 601, 70, 621, 417, 33, 405, 613, 3, 411,
103258 /* 1260 */ 264, 411, 415, 622, 418, 626, 178, 509, 8, 403,
103259 /* 1270 */ 241, 416, 126, 408, 414, 621, 414, 449, 208, 566,
103260 /* 1280 */ 240, 221, 621, 601, 83, 601, 82, 599, 297, 277,
103261 /* 1290 */ 296, 30, 403, 31, 395, 264, 295, 397, 489, 40,
103262 /* 1300 */ 41, 411, 566, 220, 621, 294, 42, 413, 412, 271,
103263 /* 1310 */ 621, 595, 600, 621, 59, 60, 414, 269, 267, 623,
103264 /* 1320 */ 622, 36, 40, 41, 621, 601, 81, 598, 235, 42,
103265 /* 1330 */ 413, 412, 621, 621, 595, 265, 344, 411, 248, 556,
103266 /* 1340 */ 173, 185, 593, 593, 593, 592, 591, 14, 218, 29,
103267 /* 1350 */ 621, 543, 414, 305, 304, 303, 179, 301, 411, 566,
103268 /* 1360 */ 454, 601, 80, 289, 335, 593, 593, 593, 592, 591,
103269 /* 1370 */ 14, 411, 287, 414, 151, 392, 246, 260, 411, 196,
103270 /* 1380 */ 195, 523, 601, 69, 411, 245, 414, 526, 537, 285,
103271 /* 1390 */ 389, 595, 621, 414, 536, 601, 17, 362, 153, 414,
103272 /* 1400 */ 466, 463, 601, 78, 154, 414, 462, 152, 601, 77,
103273 /* 1410 */ 355, 255, 621, 455, 601, 9, 621, 386, 444, 517,
103274 /* 1420 */ 247, 621, 593, 593, 593, 621, 621, 244, 621, 243,
103275 /* 1430 */ 430, 518, 292, 621, 329, 621, 145, 393, 280, 513,
103276 /* 1440 */ 291, 131, 621, 514, 621, 621, 311, 621, 259, 346,
103277 /* 1450 */ 249, 621, 621, 229, 314, 621, 228, 512, 227, 240,
103278 /* 1460 */ 494, 488, 310, 164, 487, 486, 373, 480, 163, 262,
103279 /* 1470 */ 369, 371, 162, 26, 212, 478, 477, 161, 141, 363,
103280 /* 1480 */ 467, 122, 339, 187, 119, 348, 347, 117, 116, 115,
103281 /* 1490 */ 114, 112, 182, 457, 320, 22, 433, 432, 448, 19,
103282 /* 1500 */ 609, 431, 428, 62, 193, 596, 573, 298, 555, 552,
103283 /* 1510 */ 571, 404, 290, 380, 498, 510, 495, 306, 281, 499,
103284 /* 1520 */ 250, 5, 497, 460, 345, 447, 569, 550, 238, 299,
103285 /* 1530 */ 527, 525, 508, 961, 502, 501, 961, 401, 961, 211,
103286 /* 1540 */ 490, 356, 256, 961, 483, 961, 961, 961, 961, 961,
103287 /* 1550 */ 961, 961, 961, 961, 961, 961, 370,
103289 static const YYCODETYPE yy_lookahead[] = {
103290 /* 0 */ 19, 142, 143, 144, 145, 24, 1, 26, 77, 78,
103291 /* 10 */ 79, 80, 81, 82, 83, 84, 85, 86, 87, 88,
103292 /* 20 */ 89, 90, 91, 92, 15, 98, 26, 27, 7, 8,
103293 /* 30 */ 49, 50, 77, 78, 79, 80, 109, 82, 83, 84,
103294 /* 40 */ 85, 86, 87, 88, 89, 90, 91, 92, 22, 68,
103295 /* 50 */ 69, 70, 71, 72, 73, 74, 75, 76, 77, 78,
103296 /* 60 */ 79, 80, 23, 82, 83, 84, 85, 86, 87, 88,
103297 /* 70 */ 89, 90, 91, 92, 19, 94, 112, 19, 114, 115,
103298 /* 80 */ 25, 82, 83, 84, 85, 86, 87, 88, 89, 90,
103299 /* 90 */ 91, 92, 19, 22, 94, 95, 96, 150, 150, 99,
103300 /* 100 */ 100, 101, 76, 150, 49, 50, 105, 106, 107, 54,
103301 /* 110 */ 110, 158, 165, 165, 161, 162, 26, 27, 165, 113,
103302 /* 120 */ 16, 174, 175, 68, 69, 70, 71, 72, 73, 74,
103303 /* 130 */ 75, 76, 77, 78, 79, 80, 118, 82, 83, 84,
103304 /* 140 */ 85, 86, 87, 88, 89, 90, 91, 92, 19, 23,
103305 /* 150 */ 92, 97, 98, 24, 96, 97, 98, 99, 100, 101,
103306 /* 160 */ 102, 25, 97, 216, 60, 92, 62, 109, 221, 25,
103307 /* 170 */ 97, 98, 99, 100, 101, 102, 86, 87, 49, 50,
103308 /* 180 */ 118, 116, 109, 25, 94, 95, 32, 97, 88, 89,
103309 /* 190 */ 90, 91, 92, 128, 104, 41, 106, 68, 69, 70,
103310 /* 200 */ 71, 72, 73, 74, 75, 76, 77, 78, 79, 80,
103311 /* 210 */ 11, 82, 83, 84, 85, 86, 87, 88, 89, 90,
103312 /* 220 */ 91, 92, 19, 19, 86, 87, 88, 89, 90, 91,
103313 /* 230 */ 92, 27, 96, 150, 66, 99, 100, 101, 112, 150,
103314 /* 240 */ 114, 115, 138, 150, 161, 162, 110, 103, 165, 222,
103315 /* 250 */ 223, 224, 49, 50, 165, 22, 57, 24, 165, 170,
103316 /* 260 */ 171, 118, 94, 170, 171, 23, 98, 25, 185, 186,
103317 /* 270 */ 243, 68, 69, 70, 71, 72, 73, 74, 75, 76,
103318 /* 280 */ 77, 78, 79, 80, 126, 82, 83, 84, 85, 86,
103319 /* 290 */ 87, 88, 89, 90, 91, 92, 19, 129, 130, 131,
103320 /* 300 */ 88, 23, 172, 173, 105, 106, 107, 150, 22, 26,
103321 /* 310 */ 27, 181, 26, 27, 22, 116, 26, 27, 26, 230,
103322 /* 320 */ 231, 197, 165, 230, 231, 113, 49, 50, 204, 117,
103323 /* 330 */ 96, 174, 175, 99, 100, 101, 22, 26, 27, 136,
103324 /* 340 */ 26, 27, 118, 16, 110, 68, 69, 70, 71, 72,
103325 /* 350 */ 73, 74, 75, 76, 77, 78, 79, 80, 118, 82,
103326 /* 360 */ 83, 84, 85, 86, 87, 88, 89, 90, 91, 92,
103327 /* 370 */ 19, 214, 215, 150, 23, 23, 155, 94, 95, 22,
103328 /* 380 */ 94, 95, 116, 160, 94, 95, 94, 60, 165, 62,
103329 /* 390 */ 112, 26, 114, 115, 128, 23, 36, 174, 175, 88,
103330 /* 400 */ 49, 50, 57, 120, 22, 94, 95, 23, 94, 95,
103331 /* 410 */ 120, 51, 25, 136, 169, 170, 171, 194, 58, 68,
103332 /* 420 */ 69, 70, 71, 72, 73, 74, 75, 76, 77, 78,
103333 /* 430 */ 79, 80, 23, 82, 83, 84, 85, 86, 87, 88,
103334 /* 440 */ 89, 90, 91, 92, 19, 150, 12, 12, 23, 228,
103335 /* 450 */ 105, 106, 107, 23, 233, 25, 165, 19, 150, 94,
103336 /* 460 */ 165, 116, 28, 28, 112, 174, 114, 115, 108, 174,
103337 /* 470 */ 175, 26, 27, 165, 49, 50, 231, 11, 44, 44,
103338 /* 480 */ 46, 46, 174, 175, 112, 160, 114, 115, 50, 22,
103339 /* 490 */ 23, 57, 25, 68, 69, 70, 71, 72, 73, 74,
103340 /* 500 */ 75, 76, 77, 78, 79, 80, 119, 82, 83, 84,
103341 /* 510 */ 85, 86, 87, 88, 89, 90, 91, 92, 19, 194,
103342 /* 520 */ 225, 23, 23, 215, 19, 95, 105, 106, 107, 150,
103343 /* 530 */ 23, 150, 27, 23, 67, 25, 150, 206, 207, 94,
103344 /* 540 */ 95, 166, 104, 218, 165, 22, 165, 109, 49, 50,
103345 /* 550 */ 120, 165, 25, 174, 175, 174, 175, 23, 21, 234,
103346 /* 560 */ 174, 175, 22, 23, 239, 25, 25, 68, 69, 70,
103347 /* 570 */ 71, 72, 73, 74, 75, 76, 77, 78, 79, 80,
103348 /* 580 */ 205, 82, 83, 84, 85, 86, 87, 88, 89, 90,
103349 /* 590 */ 91, 92, 19, 22, 23, 216, 23, 222, 223, 224,
103350 /* 600 */ 63, 220, 35, 150, 150, 163, 220, 67, 166, 167,
103351 /* 610 */ 168, 150, 169, 170, 171, 161, 162, 25, 165, 165,
103352 /* 620 */ 150, 113, 49, 50, 25, 117, 165, 174, 175, 35,
103353 /* 630 */ 7, 8, 9, 160, 160, 165, 120, 100, 67, 247,
103354 /* 640 */ 248, 68, 69, 70, 71, 72, 73, 74, 75, 76,
103355 /* 650 */ 77, 78, 79, 80, 193, 82, 83, 84, 85, 86,
103356 /* 660 */ 87, 88, 89, 90, 91, 92, 19, 194, 194, 150,
103357 /* 670 */ 135, 24, 137, 35, 231, 138, 150, 129, 130, 206,
103358 /* 680 */ 207, 30, 27, 213, 165, 34, 118, 95, 0, 1,
103359 /* 690 */ 2, 165, 218, 174, 175, 50, 49, 50, 22, 48,
103360 /* 700 */ 174, 175, 22, 23, 23, 244, 222, 223, 224, 166,
103361 /* 710 */ 167, 168, 120, 239, 23, 68, 69, 70, 71, 72,
103362 /* 720 */ 73, 74, 75, 76, 77, 78, 79, 80, 150, 82,
103363 /* 730 */ 83, 84, 85, 86, 87, 88, 89, 90, 91, 92,
103364 /* 740 */ 19, 150, 173, 165, 181, 182, 24, 67, 26, 104,
103365 /* 750 */ 181, 188, 174, 175, 150, 39, 165, 150, 52, 150,
103366 /* 760 */ 150, 150, 150, 144, 145, 174, 175, 249, 250, 165,
103367 /* 770 */ 49, 50, 165, 52, 165, 165, 165, 165, 174, 175,
103368 /* 780 */ 29, 174, 175, 174, 175, 174, 175, 160, 22, 68,
103369 /* 790 */ 69, 70, 71, 72, 73, 74, 75, 76, 77, 78,
103370 /* 800 */ 79, 80, 150, 82, 83, 84, 85, 86, 87, 88,
103371 /* 810 */ 89, 90, 91, 92, 19, 150, 94, 165, 150, 150,
103372 /* 820 */ 160, 194, 150, 213, 160, 52, 174, 175, 23, 23,
103373 /* 830 */ 165, 25, 22, 165, 165, 150, 150, 165, 52, 174,
103374 /* 840 */ 175, 22, 174, 175, 49, 50, 174, 175, 190, 191,
103375 /* 850 */ 165, 165, 240, 23, 194, 25, 187, 109, 194, 174,
103376 /* 860 */ 175, 190, 191, 68, 69, 70, 71, 72, 73, 74,
103377 /* 870 */ 75, 76, 77, 78, 79, 80, 150, 82, 83, 84,
103378 /* 880 */ 85, 86, 87, 88, 89, 90, 91, 92, 19, 150,
103379 /* 890 */ 22, 165, 150, 23, 150, 25, 150, 166, 91, 92,
103380 /* 900 */ 174, 175, 22, 217, 165, 150, 102, 165, 150, 165,
103381 /* 910 */ 150, 165, 150, 174, 175, 19, 174, 175, 49, 50,
103382 /* 920 */ 165, 86, 87, 165, 23, 165, 25, 165, 24, 174,
103383 /* 930 */ 175, 187, 174, 175, 174, 175, 205, 68, 69, 70,
103384 /* 940 */ 71, 72, 73, 74, 75, 76, 77, 78, 79, 80,
103385 /* 950 */ 150, 82, 83, 84, 85, 86, 87, 88, 89, 90,
103386 /* 960 */ 91, 92, 19, 150, 150, 165, 150, 150, 166, 23,
103387 /* 970 */ 150, 25, 160, 20, 174, 175, 1, 2, 165, 165,
103388 /* 980 */ 104, 165, 165, 43, 150, 165, 240, 150, 49, 50,
103389 /* 990 */ 174, 175, 49, 50, 23, 23, 25, 25, 53, 165,
103390 /* 1000 */ 187, 187, 165, 23, 187, 25, 194, 205, 174, 175,
103391 /* 1010 */ 71, 72, 69, 70, 71, 72, 73, 74, 75, 76,
103392 /* 1020 */ 77, 78, 79, 80, 150, 82, 83, 84, 85, 86,
103393 /* 1030 */ 87, 88, 89, 90, 91, 92, 19, 98, 150, 165,
103394 /* 1040 */ 150, 160, 150, 59, 25, 53, 104, 22, 174, 175,
103395 /* 1050 */ 213, 138, 5, 165, 1, 165, 150, 165, 150, 150,
103396 /* 1060 */ 240, 150, 174, 175, 174, 175, 49, 50, 118, 150,
103397 /* 1070 */ 35, 165, 27, 165, 165, 194, 165, 108, 127, 76,
103398 /* 1080 */ 174, 175, 174, 175, 165, 174, 175, 70, 71, 72,
103399 /* 1090 */ 73, 74, 75, 76, 77, 78, 79, 80, 166, 82,
103400 /* 1100 */ 83, 84, 85, 86, 87, 88, 89, 90, 91, 92,
103401 /* 1110 */ 19, 20, 193, 22, 150, 150, 150, 26, 27, 76,
103402 /* 1120 */ 150, 22, 1, 150, 119, 121, 217, 20, 37, 165,
103403 /* 1130 */ 165, 165, 16, 19, 20, 165, 22, 205, 165, 119,
103404 /* 1140 */ 26, 27, 108, 128, 150, 150, 150, 56, 150, 22,
103405 /* 1150 */ 150, 37, 150, 127, 160, 23, 150, 66, 193, 165,
103406 /* 1160 */ 165, 165, 16, 165, 23, 165, 150, 165, 174, 175,
103407 /* 1170 */ 56, 165, 150, 65, 174, 175, 15, 86, 87, 88,
103408 /* 1180 */ 66, 165, 140, 150, 93, 94, 95, 165, 194, 98,
103409 /* 1190 */ 174, 175, 22, 3, 164, 193, 174, 175, 165, 150,
103410 /* 1200 */ 86, 87, 4, 180, 150, 248, 251, 93, 94, 95,
103411 /* 1210 */ 216, 180, 98, 251, 165, 221, 150, 149, 6, 165,
103412 /* 1220 */ 129, 130, 131, 132, 133, 134, 193, 150, 174, 175,
103413 /* 1230 */ 116, 165, 19, 20, 150, 22, 149, 151, 150, 26,
103414 /* 1240 */ 27, 149, 165, 129, 130, 131, 132, 133, 134, 165,
103415 /* 1250 */ 37, 174, 175, 165, 149, 19, 20, 13, 22, 150,
103416 /* 1260 */ 150, 150, 26, 27, 146, 147, 151, 150, 25, 56,
103417 /* 1270 */ 152, 159, 154, 37, 165, 165, 165, 193, 160, 66,
103418 /* 1280 */ 116, 193, 165, 174, 175, 174, 175, 194, 199, 150,
103419 /* 1290 */ 200, 126, 56, 124, 123, 150, 201, 122, 150, 86,
103420 /* 1300 */ 87, 150, 66, 193, 165, 202, 93, 94, 95, 150,
103421 /* 1310 */ 165, 98, 194, 165, 125, 22, 165, 150, 150, 26,
103422 /* 1320 */ 27, 135, 86, 87, 165, 174, 175, 203, 226, 93,
103423 /* 1330 */ 94, 95, 165, 165, 98, 150, 218, 150, 193, 157,
103424 /* 1340 */ 118, 157, 129, 130, 131, 132, 133, 134, 5, 104,
103425 /* 1350 */ 165, 211, 165, 10, 11, 12, 13, 14, 150, 66,
103426 /* 1360 */ 17, 174, 175, 210, 246, 129, 130, 131, 132, 133,
103427 /* 1370 */ 134, 150, 210, 165, 31, 121, 33, 150, 150, 86,
103428 /* 1380 */ 87, 176, 174, 175, 150, 42, 165, 94, 211, 210,
103429 /* 1390 */ 150, 98, 165, 165, 211, 174, 175, 150, 55, 165,
103430 /* 1400 */ 57, 150, 174, 175, 61, 165, 150, 64, 174, 175,
103431 /* 1410 */ 150, 150, 165, 150, 174, 175, 165, 104, 150, 184,
103432 /* 1420 */ 150, 165, 129, 130, 131, 165, 165, 150, 165, 150,
103433 /* 1430 */ 150, 176, 150, 165, 47, 165, 150, 150, 176, 103,
103434 /* 1440 */ 150, 22, 165, 178, 165, 165, 179, 165, 105, 106,
103435 /* 1450 */ 107, 165, 165, 229, 111, 165, 92, 176, 229, 116,
103436 /* 1460 */ 184, 176, 179, 156, 176, 176, 18, 157, 156, 237,
103437 /* 1470 */ 45, 157, 156, 135, 157, 157, 238, 156, 68, 157,
103438 /* 1480 */ 189, 189, 139, 219, 22, 157, 18, 192, 192, 192,
103439 /* 1490 */ 192, 189, 219, 199, 157, 242, 40, 157, 199, 242,
103440 /* 1500 */ 153, 157, 38, 245, 196, 166, 232, 198, 177, 177,
103441 /* 1510 */ 232, 227, 209, 178, 166, 182, 166, 148, 177, 177,
103442 /* 1520 */ 209, 196, 177, 199, 209, 199, 166, 208, 92, 195,
103443 /* 1530 */ 174, 174, 183, 252, 183, 183, 252, 191, 252, 235,
103444 /* 1540 */ 186, 241, 241, 252, 186, 252, 252, 252, 252, 252,
103445 /* 1550 */ 252, 252, 252, 252, 252, 252, 236,
103447 #define YY_SHIFT_USE_DFLT (-74)
103448 #define YY_SHIFT_COUNT (418)
103449 #define YY_SHIFT_MIN (-73)
103450 #define YY_SHIFT_MAX (1468)
103451 static const short yy_shift_ofst[] = {
103452 /* 0 */ 975, 1114, 1343, 1114, 1213, 1213, 90, 90, 0, -19,
103453 /* 10 */ 1213, 1213, 1213, 1213, 1213, 345, 445, 721, 1091, 1213,
103454 /* 20 */ 1213, 1213, 1213, 1213, 1213, 1213, 1213, 1213, 1213, 1213,
103455 /* 30 */ 1213, 1213, 1213, 1213, 1213, 1213, 1213, 1213, 1213, 1213,
103456 /* 40 */ 1213, 1213, 1213, 1213, 1213, 1213, 1213, 1236, 1213, 1213,
103457 /* 50 */ 1213, 1213, 1213, 1213, 1213, 1213, 1213, 1213, 1213, 1213,
103458 /* 60 */ 1213, 199, 445, 445, 835, 835, 365, 1164, 55, 647,
103459 /* 70 */ 573, 499, 425, 351, 277, 203, 129, 795, 795, 795,
103460 /* 80 */ 795, 795, 795, 795, 795, 795, 795, 795, 795, 795,
103461 /* 90 */ 795, 795, 795, 795, 795, 869, 795, 943, 1017, 1017,
103462 /* 100 */ -69, -45, -45, -45, -45, -45, -1, 58, 138, 100,
103463 /* 110 */ 445, 445, 445, 445, 445, 445, 445, 445, 445, 445,
103464 /* 120 */ 445, 445, 445, 445, 445, 445, 537, 438, 445, 445,
103465 /* 130 */ 445, 445, 445, 365, 807, 1436, -74, -74, -74, 1293,
103466 /* 140 */ 73, 434, 434, 311, 314, 290, 283, 286, 540, 467,
103467 /* 150 */ 445, 445, 445, 445, 445, 445, 445, 445, 445, 445,
103468 /* 160 */ 445, 445, 445, 445, 445, 445, 445, 445, 445, 445,
103469 /* 170 */ 445, 445, 445, 445, 445, 445, 445, 445, 445, 445,
103470 /* 180 */ 445, 445, 65, 722, 722, 722, 688, 266, 1164, 1164,
103471 /* 190 */ 1164, -74, -74, -74, 136, 168, 168, 234, 360, 360,
103472 /* 200 */ 360, 430, 372, 435, 352, 278, 126, -36, -36, -36,
103473 /* 210 */ -36, 421, 651, -36, -36, 592, 292, 212, 623, 158,
103474 /* 220 */ 204, 204, 505, 158, 505, 144, 365, 154, 365, 154,
103475 /* 230 */ 645, 154, 204, 154, 154, 535, 548, 548, 365, 387,
103476 /* 240 */ 508, 233, 1464, 1222, 1222, 1456, 1456, 1222, 1462, 1410,
103477 /* 250 */ 1165, 1468, 1468, 1468, 1468, 1222, 1165, 1462, 1410, 1410,
103478 /* 260 */ 1222, 1448, 1338, 1425, 1222, 1222, 1448, 1222, 1448, 1222,
103479 /* 270 */ 1448, 1419, 1313, 1313, 1313, 1387, 1364, 1364, 1419, 1313,
103480 /* 280 */ 1336, 1313, 1387, 1313, 1313, 1254, 1245, 1254, 1245, 1254,
103481 /* 290 */ 1245, 1222, 1222, 1186, 1189, 1175, 1169, 1171, 1165, 1164,
103482 /* 300 */ 1243, 1244, 1244, 1212, 1212, 1212, 1212, -74, -74, -74,
103483 /* 310 */ -74, -74, -74, 939, 104, 680, 571, 327, 1, 980,
103484 /* 320 */ 26, 972, 971, 946, 901, 870, 830, 806, 54, 21,
103485 /* 330 */ -73, 510, 242, 1198, 1190, 1170, 1042, 1161, 1108, 1146,
103486 /* 340 */ 1141, 1132, 1015, 1127, 1026, 1034, 1020, 1107, 1004, 1116,
103487 /* 350 */ 1121, 1005, 1099, 951, 1043, 1003, 969, 1045, 1035, 950,
103488 /* 360 */ 1053, 1047, 1025, 942, 913, 992, 1019, 945, 984, 940,
103489 /* 370 */ 876, 904, 953, 896, 748, 804, 880, 786, 868, 819,
103490 /* 380 */ 805, 810, 773, 751, 766, 706, 716, 691, 681, 568,
103491 /* 390 */ 655, 638, 676, 516, 541, 594, 599, 567, 541, 534,
103492 /* 400 */ 507, 527, 498, 523, 466, 382, 409, 384, 357, 6,
103493 /* 410 */ 240, 224, 143, 62, 18, 71, 39, 9, 5,
103495 #define YY_REDUCE_USE_DFLT (-142)
103496 #define YY_REDUCE_COUNT (312)
103497 #define YY_REDUCE_MIN (-141)
103498 #define YY_REDUCE_MAX (1369)
103499 static const short yy_reduce_ofst[] = {
103500 /* 0 */ -141, 994, 1118, 223, 157, -53, 93, 89, 83, 375,
103501 /* 10 */ 386, 381, 379, 308, 295, 325, -47, 27, 1240, 1234,
103502 /* 20 */ 1228, 1221, 1208, 1187, 1151, 1111, 1109, 1077, 1054, 1022,
103503 /* 30 */ 1016, 1000, 911, 908, 906, 890, 888, 874, 834, 816,
103504 /* 40 */ 800, 760, 758, 755, 742, 739, 726, 685, 672, 668,
103505 /* 50 */ 665, 652, 611, 609, 607, 604, 591, 578, 526, 519,
103506 /* 60 */ 453, 474, 454, 461, 443, 245, 442, 473, 484, 484,
103507 /* 70 */ 484, 484, 484, 484, 484, 484, 484, 484, 484, 484,
103508 /* 80 */ 484, 484, 484, 484, 484, 484, 484, 484, 484, 484,
103509 /* 90 */ 484, 484, 484, 484, 484, 484, 484, 484, 484, 484,
103510 /* 100 */ 484, 484, 484, 484, 484, 484, 484, 130, 484, 484,
103511 /* 110 */ 1145, 909, 1110, 1088, 1084, 1033, 1002, 965, 820, 837,
103512 /* 120 */ 746, 686, 612, 817, 610, 919, 221, 563, 814, 813,
103513 /* 130 */ 744, 669, 470, 543, 484, 484, 484, 484, 484, 291,
103514 /* 140 */ 569, 671, 658, 970, 1290, 1287, 1286, 1282, 518, 518,
103515 /* 150 */ 1280, 1279, 1277, 1270, 1268, 1263, 1261, 1260, 1256, 1251,
103516 /* 160 */ 1247, 1227, 1185, 1168, 1167, 1159, 1148, 1139, 1117, 1066,
103517 /* 170 */ 1049, 1006, 998, 996, 995, 973, 970, 966, 964, 892,
103518 /* 180 */ 762, -52, 881, 932, 802, 731, 619, 812, 664, 660,
103519 /* 190 */ 627, 392, 331, 124, 1358, 1357, 1356, 1354, 1352, 1351,
103520 /* 200 */ 1349, 1319, 1334, 1346, 1334, 1334, 1334, 1334, 1334, 1334,
103521 /* 210 */ 1334, 1320, 1304, 1334, 1334, 1319, 1360, 1325, 1369, 1326,
103522 /* 220 */ 1315, 1311, 1301, 1324, 1300, 1335, 1350, 1345, 1348, 1342,
103523 /* 230 */ 1333, 1341, 1303, 1332, 1331, 1284, 1278, 1274, 1339, 1309,
103524 /* 240 */ 1308, 1347, 1258, 1344, 1340, 1257, 1253, 1337, 1273, 1302,
103525 /* 250 */ 1299, 1298, 1297, 1296, 1295, 1328, 1294, 1264, 1292, 1291,
103526 /* 260 */ 1322, 1321, 1238, 1232, 1318, 1317, 1316, 1314, 1312, 1310,
103527 /* 270 */ 1307, 1283, 1289, 1288, 1285, 1276, 1229, 1224, 1267, 1281,
103528 /* 280 */ 1265, 1262, 1235, 1255, 1205, 1183, 1179, 1177, 1162, 1140,
103529 /* 290 */ 1153, 1184, 1182, 1102, 1124, 1103, 1095, 1090, 1089, 1093,
103530 /* 300 */ 1112, 1115, 1086, 1105, 1092, 1087, 1068, 962, 955, 957,
103531 /* 310 */ 1031, 1023, 1030,
103533 static const YYACTIONTYPE yy_default[] = {
103534 /* 0 */ 635, 870, 959, 959, 959, 870, 899, 899, 959, 759,
103535 /* 10 */ 959, 959, 959, 959, 868, 959, 959, 933, 959, 959,
103536 /* 20 */ 959, 959, 959, 959, 959, 959, 959, 959, 959, 959,
103537 /* 30 */ 959, 959, 959, 959, 959, 959, 959, 959, 959, 959,
103538 /* 40 */ 959, 959, 959, 959, 959, 959, 959, 959, 959, 959,
103539 /* 50 */ 959, 959, 959, 959, 959, 959, 959, 959, 959, 959,
103540 /* 60 */ 959, 959, 959, 959, 899, 899, 674, 763, 794, 959,
103541 /* 70 */ 959, 959, 959, 959, 959, 959, 959, 932, 934, 809,
103542 /* 80 */ 808, 802, 801, 912, 774, 799, 792, 785, 796, 871,
103543 /* 90 */ 864, 865, 863, 867, 872, 959, 795, 831, 848, 830,
103544 /* 100 */ 842, 847, 854, 846, 843, 833, 832, 666, 834, 835,
103545 /* 110 */ 959, 959, 959, 959, 959, 959, 959, 959, 959, 959,
103546 /* 120 */ 959, 959, 959, 959, 959, 959, 661, 728, 959, 959,
103547 /* 130 */ 959, 959, 959, 959, 836, 837, 851, 850, 849, 959,
103548 /* 140 */ 959, 959, 959, 959, 959, 959, 959, 959, 959, 959,
103549 /* 150 */ 959, 939, 937, 959, 883, 959, 959, 959, 959, 959,
103550 /* 160 */ 959, 959, 959, 959, 959, 959, 959, 959, 959, 959,
103551 /* 170 */ 959, 959, 959, 959, 959, 959, 959, 959, 959, 959,
103552 /* 180 */ 959, 641, 959, 759, 759, 759, 635, 959, 959, 959,
103553 /* 190 */ 959, 951, 763, 753, 719, 959, 959, 959, 959, 959,
103554 /* 200 */ 959, 959, 959, 959, 959, 959, 959, 804, 742, 922,
103555 /* 210 */ 924, 959, 905, 740, 663, 761, 676, 751, 643, 798,
103556 /* 220 */ 776, 776, 917, 798, 917, 700, 959, 788, 959, 788,
103557 /* 230 */ 697, 788, 776, 788, 788, 866, 959, 959, 959, 760,
103558 /* 240 */ 751, 959, 944, 767, 767, 936, 936, 767, 810, 732,
103559 /* 250 */ 798, 739, 739, 739, 739, 767, 798, 810, 732, 732,
103560 /* 260 */ 767, 658, 911, 909, 767, 767, 658, 767, 658, 767,
103561 /* 270 */ 658, 876, 730, 730, 730, 715, 880, 880, 876, 730,
103562 /* 280 */ 700, 730, 715, 730, 730, 780, 775, 780, 775, 780,
103563 /* 290 */ 775, 767, 767, 959, 793, 781, 791, 789, 798, 959,
103564 /* 300 */ 718, 651, 651, 640, 640, 640, 640, 956, 956, 951,
103565 /* 310 */ 702, 702, 684, 959, 959, 959, 959, 959, 959, 959,
103566 /* 320 */ 885, 959, 959, 959, 959, 959, 959, 959, 959, 959,
103567 /* 330 */ 959, 959, 959, 959, 636, 946, 959, 959, 943, 959,
103568 /* 340 */ 959, 959, 959, 959, 959, 959, 959, 959, 959, 959,
103569 /* 350 */ 959, 959, 959, 959, 959, 959, 959, 959, 959, 915,
103570 /* 360 */ 959, 959, 959, 959, 959, 959, 908, 907, 959, 959,
103571 /* 370 */ 959, 959, 959, 959, 959, 959, 959, 959, 959, 959,
103572 /* 380 */ 959, 959, 959, 959, 959, 959, 959, 959, 959, 959,
103573 /* 390 */ 959, 959, 959, 959, 790, 959, 782, 959, 869, 959,
103574 /* 400 */ 959, 959, 959, 959, 959, 959, 959, 959, 959, 745,
103575 /* 410 */ 819, 959, 818, 822, 817, 668, 959, 649, 959, 632,
103576 /* 420 */ 637, 955, 958, 957, 954, 953, 952, 947, 945, 942,
103577 /* 430 */ 941, 940, 938, 935, 931, 889, 887, 894, 893, 892,
103578 /* 440 */ 891, 890, 888, 886, 884, 805, 803, 800, 797, 930,
103579 /* 450 */ 882, 741, 738, 737, 657, 948, 914, 923, 921, 811,
103580 /* 460 */ 920, 919, 918, 916, 913, 900, 807, 806, 733, 874,
103581 /* 470 */ 873, 660, 904, 903, 902, 906, 910, 901, 769, 659,
103582 /* 480 */ 656, 665, 722, 721, 729, 727, 726, 725, 724, 723,
103583 /* 490 */ 720, 667, 675, 686, 714, 699, 698, 879, 881, 878,
103584 /* 500 */ 877, 707, 706, 712, 711, 710, 709, 708, 705, 704,
103585 /* 510 */ 703, 696, 695, 701, 694, 717, 716, 713, 693, 736,
103586 /* 520 */ 735, 734, 731, 692, 691, 690, 822, 689, 688, 828,
103587 /* 530 */ 827, 815, 858, 756, 755, 754, 766, 765, 778, 777,
103588 /* 540 */ 813, 812, 779, 764, 758, 757, 773, 772, 771, 770,
103589 /* 550 */ 762, 752, 784, 787, 786, 783, 860, 768, 857, 929,
103590 /* 560 */ 928, 927, 926, 925, 862, 861, 829, 826, 679, 680,
103591 /* 570 */ 898, 896, 897, 895, 682, 681, 678, 677, 859, 747,
103592 /* 580 */ 746, 855, 852, 844, 840, 856, 853, 845, 841, 839,
103593 /* 590 */ 838, 824, 823, 821, 820, 816, 825, 670, 748, 744,
103594 /* 600 */ 743, 814, 750, 749, 687, 685, 683, 664, 662, 655,
103595 /* 610 */ 653, 652, 654, 650, 648, 647, 646, 645, 644, 673,
103596 /* 620 */ 672, 671, 669, 668, 642, 639, 638, 634, 633, 631,
103599 /* The next table maps tokens into fallback tokens. If a construct
103600 ** like the following:
103602 ** %fallback ID X Y Z.
103604 ** appears in the grammar, then ID becomes a fallback token for X, Y,
103605 ** and Z. Whenever one of the tokens X, Y, or Z is input to the parser
103606 ** but it does not parse, the type of the token is changed to ID and
103607 ** the parse is retried before an error is thrown.
103609 #ifdef YYFALLBACK
103610 static const YYCODETYPE yyFallback[] = {
103611 0, /* $ => nothing */
103612 0, /* SEMI => nothing */
103613 26, /* EXPLAIN => ID */
103614 26, /* QUERY => ID */
103615 26, /* PLAN => ID */
103616 26, /* BEGIN => ID */
103617 0, /* TRANSACTION => nothing */
103618 26, /* DEFERRED => ID */
103619 26, /* IMMEDIATE => ID */
103620 26, /* EXCLUSIVE => ID */
103621 0, /* COMMIT => nothing */
103622 26, /* END => ID */
103623 26, /* ROLLBACK => ID */
103624 26, /* SAVEPOINT => ID */
103625 26, /* RELEASE => ID */
103626 0, /* TO => nothing */
103627 0, /* TABLE => nothing */
103628 0, /* CREATE => nothing */
103629 26, /* IF => ID */
103630 0, /* NOT => nothing */
103631 0, /* EXISTS => nothing */
103632 26, /* TEMP => ID */
103633 0, /* LP => nothing */
103634 0, /* RP => nothing */
103635 0, /* AS => nothing */
103636 0, /* COMMA => nothing */
103637 0, /* ID => nothing */
103638 0, /* INDEXED => nothing */
103639 26, /* ABORT => ID */
103640 26, /* ACTION => ID */
103641 26, /* AFTER => ID */
103642 26, /* ANALYZE => ID */
103643 26, /* ASC => ID */
103644 26, /* ATTACH => ID */
103645 26, /* BEFORE => ID */
103646 26, /* BY => ID */
103647 26, /* CASCADE => ID */
103648 26, /* CAST => ID */
103649 26, /* COLUMNKW => ID */
103650 26, /* CONFLICT => ID */
103651 26, /* DATABASE => ID */
103652 26, /* DESC => ID */
103653 26, /* DETACH => ID */
103654 26, /* EACH => ID */
103655 26, /* FAIL => ID */
103656 26, /* FOR => ID */
103657 26, /* IGNORE => ID */
103658 26, /* INITIALLY => ID */
103659 26, /* INSTEAD => ID */
103660 26, /* LIKE_KW => ID */
103661 26, /* MATCH => ID */
103662 26, /* NO => ID */
103663 26, /* KEY => ID */
103664 26, /* OF => ID */
103665 26, /* OFFSET => ID */
103666 26, /* PRAGMA => ID */
103667 26, /* RAISE => ID */
103668 26, /* REPLACE => ID */
103669 26, /* RESTRICT => ID */
103670 26, /* ROW => ID */
103671 26, /* TRIGGER => ID */
103672 26, /* VACUUM => ID */
103673 26, /* VIEW => ID */
103674 26, /* VIRTUAL => ID */
103675 26, /* REINDEX => ID */
103676 26, /* RENAME => ID */
103677 26, /* CTIME_KW => ID */
103679 #endif /* YYFALLBACK */
103681 /* The following structure represents a single element of the
103682 ** parser's stack. Information stored includes:
103684 ** + The state number for the parser at this level of the stack.
103686 ** + The value of the token stored at this level of the stack.
103687 ** (In other words, the "major" token.)
103689 ** + The semantic value stored at this level of the stack. This is
103690 ** the information used by the action routines in the grammar.
103691 ** It is sometimes called the "minor" token.
103693 struct yyStackEntry {
103694 YYACTIONTYPE stateno; /* The state-number */
103695 YYCODETYPE major; /* The major token value. This is the code
103696 ** number for the token at this stack level */
103697 YYMINORTYPE minor; /* The user-supplied minor token value. This
103698 ** is the value of the token */
103700 typedef struct yyStackEntry yyStackEntry;
103702 /* The state of the parser is completely contained in an instance of
103703 ** the following structure */
103704 struct yyParser {
103705 int yyidx; /* Index of top element in stack */
103706 #ifdef YYTRACKMAXSTACKDEPTH
103707 int yyidxMax; /* Maximum value of yyidx */
103708 #endif
103709 int yyerrcnt; /* Shifts left before out of the error */
103710 sqlite3ParserARG_SDECL /* A place to hold %extra_argument */
103711 #if YYSTACKDEPTH<=0
103712 int yystksz; /* Current side of the stack */
103713 yyStackEntry *yystack; /* The parser's stack */
103714 #else
103715 yyStackEntry yystack[YYSTACKDEPTH]; /* The parser's stack */
103716 #endif
103718 typedef struct yyParser yyParser;
103720 #ifndef NDEBUG
103721 static FILE *yyTraceFILE = 0;
103722 static char *yyTracePrompt = 0;
103723 #endif /* NDEBUG */
103725 #ifndef NDEBUG
103727 ** Turn parser tracing on by giving a stream to which to write the trace
103728 ** and a prompt to preface each trace message. Tracing is turned off
103729 ** by making either argument NULL
103731 ** Inputs:
103732 ** <ul>
103733 ** <li> A FILE* to which trace output should be written.
103734 ** If NULL, then tracing is turned off.
103735 ** <li> A prefix string written at the beginning of every
103736 ** line of trace output. If NULL, then tracing is
103737 ** turned off.
103738 ** </ul>
103740 ** Outputs:
103741 ** None.
103743 SQLITE_PRIVATE void sqlite3ParserTrace(FILE *TraceFILE, char *zTracePrompt){
103744 yyTraceFILE = TraceFILE;
103745 yyTracePrompt = zTracePrompt;
103746 if( yyTraceFILE==0 ) yyTracePrompt = 0;
103747 else if( yyTracePrompt==0 ) yyTraceFILE = 0;
103749 #endif /* NDEBUG */
103751 #ifndef NDEBUG
103752 /* For tracing shifts, the names of all terminals and nonterminals
103753 ** are required. The following table supplies these names */
103754 static const char *const yyTokenName[] = {
103755 "$", "SEMI", "EXPLAIN", "QUERY",
103756 "PLAN", "BEGIN", "TRANSACTION", "DEFERRED",
103757 "IMMEDIATE", "EXCLUSIVE", "COMMIT", "END",
103758 "ROLLBACK", "SAVEPOINT", "RELEASE", "TO",
103759 "TABLE", "CREATE", "IF", "NOT",
103760 "EXISTS", "TEMP", "LP", "RP",
103761 "AS", "COMMA", "ID", "INDEXED",
103762 "ABORT", "ACTION", "AFTER", "ANALYZE",
103763 "ASC", "ATTACH", "BEFORE", "BY",
103764 "CASCADE", "CAST", "COLUMNKW", "CONFLICT",
103765 "DATABASE", "DESC", "DETACH", "EACH",
103766 "FAIL", "FOR", "IGNORE", "INITIALLY",
103767 "INSTEAD", "LIKE_KW", "MATCH", "NO",
103768 "KEY", "OF", "OFFSET", "PRAGMA",
103769 "RAISE", "REPLACE", "RESTRICT", "ROW",
103770 "TRIGGER", "VACUUM", "VIEW", "VIRTUAL",
103771 "REINDEX", "RENAME", "CTIME_KW", "ANY",
103772 "OR", "AND", "IS", "BETWEEN",
103773 "IN", "ISNULL", "NOTNULL", "NE",
103774 "EQ", "GT", "LE", "LT",
103775 "GE", "ESCAPE", "BITAND", "BITOR",
103776 "LSHIFT", "RSHIFT", "PLUS", "MINUS",
103777 "STAR", "SLASH", "REM", "CONCAT",
103778 "COLLATE", "BITNOT", "STRING", "JOIN_KW",
103779 "CONSTRAINT", "DEFAULT", "NULL", "PRIMARY",
103780 "UNIQUE", "CHECK", "REFERENCES", "AUTOINCR",
103781 "ON", "INSERT", "DELETE", "UPDATE",
103782 "SET", "DEFERRABLE", "FOREIGN", "DROP",
103783 "UNION", "ALL", "EXCEPT", "INTERSECT",
103784 "SELECT", "DISTINCT", "DOT", "FROM",
103785 "JOIN", "USING", "ORDER", "GROUP",
103786 "HAVING", "LIMIT", "WHERE", "INTO",
103787 "VALUES", "INTEGER", "FLOAT", "BLOB",
103788 "REGISTER", "VARIABLE", "CASE", "WHEN",
103789 "THEN", "ELSE", "INDEX", "ALTER",
103790 "ADD", "error", "input", "cmdlist",
103791 "ecmd", "explain", "cmdx", "cmd",
103792 "transtype", "trans_opt", "nm", "savepoint_opt",
103793 "create_table", "create_table_args", "createkw", "temp",
103794 "ifnotexists", "dbnm", "columnlist", "conslist_opt",
103795 "select", "column", "columnid", "type",
103796 "carglist", "id", "ids", "typetoken",
103797 "typename", "signed", "plus_num", "minus_num",
103798 "carg", "ccons", "term", "expr",
103799 "onconf", "sortorder", "autoinc", "idxlist_opt",
103800 "refargs", "defer_subclause", "refarg", "refact",
103801 "init_deferred_pred_opt", "conslist", "tcons", "idxlist",
103802 "defer_subclause_opt", "orconf", "resolvetype", "raisetype",
103803 "ifexists", "fullname", "oneselect", "multiselect_op",
103804 "distinct", "selcollist", "from", "where_opt",
103805 "groupby_opt", "having_opt", "orderby_opt", "limit_opt",
103806 "sclp", "as", "seltablist", "stl_prefix",
103807 "joinop", "indexed_opt", "on_opt", "using_opt",
103808 "joinop2", "inscollist", "sortlist", "sortitem",
103809 "nexprlist", "setlist", "insert_cmd", "inscollist_opt",
103810 "itemlist", "exprlist", "likeop", "between_op",
103811 "in_op", "case_operand", "case_exprlist", "case_else",
103812 "uniqueflag", "collate", "nmnum", "plus_opt",
103813 "number", "trigger_decl", "trigger_cmd_list", "trigger_time",
103814 "trigger_event", "foreach_clause", "when_clause", "trigger_cmd",
103815 "trnm", "tridxby", "database_kw_opt", "key_opt",
103816 "add_column_fullname", "kwcolumn_opt", "create_vtab", "vtabarglist",
103817 "vtabarg", "vtabargtoken", "lp", "anylist",
103819 #endif /* NDEBUG */
103821 #ifndef NDEBUG
103822 /* For tracing reduce actions, the names of all rules are required.
103824 static const char *const yyRuleName[] = {
103825 /* 0 */ "input ::= cmdlist",
103826 /* 1 */ "cmdlist ::= cmdlist ecmd",
103827 /* 2 */ "cmdlist ::= ecmd",
103828 /* 3 */ "ecmd ::= SEMI",
103829 /* 4 */ "ecmd ::= explain cmdx SEMI",
103830 /* 5 */ "explain ::=",
103831 /* 6 */ "explain ::= EXPLAIN",
103832 /* 7 */ "explain ::= EXPLAIN QUERY PLAN",
103833 /* 8 */ "cmdx ::= cmd",
103834 /* 9 */ "cmd ::= BEGIN transtype trans_opt",
103835 /* 10 */ "trans_opt ::=",
103836 /* 11 */ "trans_opt ::= TRANSACTION",
103837 /* 12 */ "trans_opt ::= TRANSACTION nm",
103838 /* 13 */ "transtype ::=",
103839 /* 14 */ "transtype ::= DEFERRED",
103840 /* 15 */ "transtype ::= IMMEDIATE",
103841 /* 16 */ "transtype ::= EXCLUSIVE",
103842 /* 17 */ "cmd ::= COMMIT trans_opt",
103843 /* 18 */ "cmd ::= END trans_opt",
103844 /* 19 */ "cmd ::= ROLLBACK trans_opt",
103845 /* 20 */ "savepoint_opt ::= SAVEPOINT",
103846 /* 21 */ "savepoint_opt ::=",
103847 /* 22 */ "cmd ::= SAVEPOINT nm",
103848 /* 23 */ "cmd ::= RELEASE savepoint_opt nm",
103849 /* 24 */ "cmd ::= ROLLBACK trans_opt TO savepoint_opt nm",
103850 /* 25 */ "cmd ::= create_table create_table_args",
103851 /* 26 */ "create_table ::= createkw temp TABLE ifnotexists nm dbnm",
103852 /* 27 */ "createkw ::= CREATE",
103853 /* 28 */ "ifnotexists ::=",
103854 /* 29 */ "ifnotexists ::= IF NOT EXISTS",
103855 /* 30 */ "temp ::= TEMP",
103856 /* 31 */ "temp ::=",
103857 /* 32 */ "create_table_args ::= LP columnlist conslist_opt RP",
103858 /* 33 */ "create_table_args ::= AS select",
103859 /* 34 */ "columnlist ::= columnlist COMMA column",
103860 /* 35 */ "columnlist ::= column",
103861 /* 36 */ "column ::= columnid type carglist",
103862 /* 37 */ "columnid ::= nm",
103863 /* 38 */ "id ::= ID",
103864 /* 39 */ "id ::= INDEXED",
103865 /* 40 */ "ids ::= ID|STRING",
103866 /* 41 */ "nm ::= id",
103867 /* 42 */ "nm ::= STRING",
103868 /* 43 */ "nm ::= JOIN_KW",
103869 /* 44 */ "type ::=",
103870 /* 45 */ "type ::= typetoken",
103871 /* 46 */ "typetoken ::= typename",
103872 /* 47 */ "typetoken ::= typename LP signed RP",
103873 /* 48 */ "typetoken ::= typename LP signed COMMA signed RP",
103874 /* 49 */ "typename ::= ids",
103875 /* 50 */ "typename ::= typename ids",
103876 /* 51 */ "signed ::= plus_num",
103877 /* 52 */ "signed ::= minus_num",
103878 /* 53 */ "carglist ::= carglist carg",
103879 /* 54 */ "carglist ::=",
103880 /* 55 */ "carg ::= CONSTRAINT nm ccons",
103881 /* 56 */ "carg ::= ccons",
103882 /* 57 */ "ccons ::= DEFAULT term",
103883 /* 58 */ "ccons ::= DEFAULT LP expr RP",
103884 /* 59 */ "ccons ::= DEFAULT PLUS term",
103885 /* 60 */ "ccons ::= DEFAULT MINUS term",
103886 /* 61 */ "ccons ::= DEFAULT id",
103887 /* 62 */ "ccons ::= NULL onconf",
103888 /* 63 */ "ccons ::= NOT NULL onconf",
103889 /* 64 */ "ccons ::= PRIMARY KEY sortorder onconf autoinc",
103890 /* 65 */ "ccons ::= UNIQUE onconf",
103891 /* 66 */ "ccons ::= CHECK LP expr RP",
103892 /* 67 */ "ccons ::= REFERENCES nm idxlist_opt refargs",
103893 /* 68 */ "ccons ::= defer_subclause",
103894 /* 69 */ "ccons ::= COLLATE ids",
103895 /* 70 */ "autoinc ::=",
103896 /* 71 */ "autoinc ::= AUTOINCR",
103897 /* 72 */ "refargs ::=",
103898 /* 73 */ "refargs ::= refargs refarg",
103899 /* 74 */ "refarg ::= MATCH nm",
103900 /* 75 */ "refarg ::= ON INSERT refact",
103901 /* 76 */ "refarg ::= ON DELETE refact",
103902 /* 77 */ "refarg ::= ON UPDATE refact",
103903 /* 78 */ "refact ::= SET NULL",
103904 /* 79 */ "refact ::= SET DEFAULT",
103905 /* 80 */ "refact ::= CASCADE",
103906 /* 81 */ "refact ::= RESTRICT",
103907 /* 82 */ "refact ::= NO ACTION",
103908 /* 83 */ "defer_subclause ::= NOT DEFERRABLE init_deferred_pred_opt",
103909 /* 84 */ "defer_subclause ::= DEFERRABLE init_deferred_pred_opt",
103910 /* 85 */ "init_deferred_pred_opt ::=",
103911 /* 86 */ "init_deferred_pred_opt ::= INITIALLY DEFERRED",
103912 /* 87 */ "init_deferred_pred_opt ::= INITIALLY IMMEDIATE",
103913 /* 88 */ "conslist_opt ::=",
103914 /* 89 */ "conslist_opt ::= COMMA conslist",
103915 /* 90 */ "conslist ::= conslist COMMA tcons",
103916 /* 91 */ "conslist ::= conslist tcons",
103917 /* 92 */ "conslist ::= tcons",
103918 /* 93 */ "tcons ::= CONSTRAINT nm",
103919 /* 94 */ "tcons ::= PRIMARY KEY LP idxlist autoinc RP onconf",
103920 /* 95 */ "tcons ::= UNIQUE LP idxlist RP onconf",
103921 /* 96 */ "tcons ::= CHECK LP expr RP onconf",
103922 /* 97 */ "tcons ::= FOREIGN KEY LP idxlist RP REFERENCES nm idxlist_opt refargs defer_subclause_opt",
103923 /* 98 */ "defer_subclause_opt ::=",
103924 /* 99 */ "defer_subclause_opt ::= defer_subclause",
103925 /* 100 */ "onconf ::=",
103926 /* 101 */ "onconf ::= ON CONFLICT resolvetype",
103927 /* 102 */ "orconf ::=",
103928 /* 103 */ "orconf ::= OR resolvetype",
103929 /* 104 */ "resolvetype ::= raisetype",
103930 /* 105 */ "resolvetype ::= IGNORE",
103931 /* 106 */ "resolvetype ::= REPLACE",
103932 /* 107 */ "cmd ::= DROP TABLE ifexists fullname",
103933 /* 108 */ "ifexists ::= IF EXISTS",
103934 /* 109 */ "ifexists ::=",
103935 /* 110 */ "cmd ::= createkw temp VIEW ifnotexists nm dbnm AS select",
103936 /* 111 */ "cmd ::= DROP VIEW ifexists fullname",
103937 /* 112 */ "cmd ::= select",
103938 /* 113 */ "select ::= oneselect",
103939 /* 114 */ "select ::= select multiselect_op oneselect",
103940 /* 115 */ "multiselect_op ::= UNION",
103941 /* 116 */ "multiselect_op ::= UNION ALL",
103942 /* 117 */ "multiselect_op ::= EXCEPT|INTERSECT",
103943 /* 118 */ "oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt orderby_opt limit_opt",
103944 /* 119 */ "distinct ::= DISTINCT",
103945 /* 120 */ "distinct ::= ALL",
103946 /* 121 */ "distinct ::=",
103947 /* 122 */ "sclp ::= selcollist COMMA",
103948 /* 123 */ "sclp ::=",
103949 /* 124 */ "selcollist ::= sclp expr as",
103950 /* 125 */ "selcollist ::= sclp STAR",
103951 /* 126 */ "selcollist ::= sclp nm DOT STAR",
103952 /* 127 */ "as ::= AS nm",
103953 /* 128 */ "as ::= ids",
103954 /* 129 */ "as ::=",
103955 /* 130 */ "from ::=",
103956 /* 131 */ "from ::= FROM seltablist",
103957 /* 132 */ "stl_prefix ::= seltablist joinop",
103958 /* 133 */ "stl_prefix ::=",
103959 /* 134 */ "seltablist ::= stl_prefix nm dbnm as indexed_opt on_opt using_opt",
103960 /* 135 */ "seltablist ::= stl_prefix LP select RP as on_opt using_opt",
103961 /* 136 */ "seltablist ::= stl_prefix LP seltablist RP as on_opt using_opt",
103962 /* 137 */ "dbnm ::=",
103963 /* 138 */ "dbnm ::= DOT nm",
103964 /* 139 */ "fullname ::= nm dbnm",
103965 /* 140 */ "joinop ::= COMMA|JOIN",
103966 /* 141 */ "joinop ::= JOIN_KW JOIN",
103967 /* 142 */ "joinop ::= JOIN_KW nm JOIN",
103968 /* 143 */ "joinop ::= JOIN_KW nm nm JOIN",
103969 /* 144 */ "on_opt ::= ON expr",
103970 /* 145 */ "on_opt ::=",
103971 /* 146 */ "indexed_opt ::=",
103972 /* 147 */ "indexed_opt ::= INDEXED BY nm",
103973 /* 148 */ "indexed_opt ::= NOT INDEXED",
103974 /* 149 */ "using_opt ::= USING LP inscollist RP",
103975 /* 150 */ "using_opt ::=",
103976 /* 151 */ "orderby_opt ::=",
103977 /* 152 */ "orderby_opt ::= ORDER BY sortlist",
103978 /* 153 */ "sortlist ::= sortlist COMMA sortitem sortorder",
103979 /* 154 */ "sortlist ::= sortitem sortorder",
103980 /* 155 */ "sortitem ::= expr",
103981 /* 156 */ "sortorder ::= ASC",
103982 /* 157 */ "sortorder ::= DESC",
103983 /* 158 */ "sortorder ::=",
103984 /* 159 */ "groupby_opt ::=",
103985 /* 160 */ "groupby_opt ::= GROUP BY nexprlist",
103986 /* 161 */ "having_opt ::=",
103987 /* 162 */ "having_opt ::= HAVING expr",
103988 /* 163 */ "limit_opt ::=",
103989 /* 164 */ "limit_opt ::= LIMIT expr",
103990 /* 165 */ "limit_opt ::= LIMIT expr OFFSET expr",
103991 /* 166 */ "limit_opt ::= LIMIT expr COMMA expr",
103992 /* 167 */ "cmd ::= DELETE FROM fullname indexed_opt where_opt",
103993 /* 168 */ "where_opt ::=",
103994 /* 169 */ "where_opt ::= WHERE expr",
103995 /* 170 */ "cmd ::= UPDATE orconf fullname indexed_opt SET setlist where_opt",
103996 /* 171 */ "setlist ::= setlist COMMA nm EQ expr",
103997 /* 172 */ "setlist ::= nm EQ expr",
103998 /* 173 */ "cmd ::= insert_cmd INTO fullname inscollist_opt VALUES LP itemlist RP",
103999 /* 174 */ "cmd ::= insert_cmd INTO fullname inscollist_opt select",
104000 /* 175 */ "cmd ::= insert_cmd INTO fullname inscollist_opt DEFAULT VALUES",
104001 /* 176 */ "insert_cmd ::= INSERT orconf",
104002 /* 177 */ "insert_cmd ::= REPLACE",
104003 /* 178 */ "itemlist ::= itemlist COMMA expr",
104004 /* 179 */ "itemlist ::= expr",
104005 /* 180 */ "inscollist_opt ::=",
104006 /* 181 */ "inscollist_opt ::= LP inscollist RP",
104007 /* 182 */ "inscollist ::= inscollist COMMA nm",
104008 /* 183 */ "inscollist ::= nm",
104009 /* 184 */ "expr ::= term",
104010 /* 185 */ "expr ::= LP expr RP",
104011 /* 186 */ "term ::= NULL",
104012 /* 187 */ "expr ::= id",
104013 /* 188 */ "expr ::= JOIN_KW",
104014 /* 189 */ "expr ::= nm DOT nm",
104015 /* 190 */ "expr ::= nm DOT nm DOT nm",
104016 /* 191 */ "term ::= INTEGER|FLOAT|BLOB",
104017 /* 192 */ "term ::= STRING",
104018 /* 193 */ "expr ::= REGISTER",
104019 /* 194 */ "expr ::= VARIABLE",
104020 /* 195 */ "expr ::= expr COLLATE ids",
104021 /* 196 */ "expr ::= CAST LP expr AS typetoken RP",
104022 /* 197 */ "expr ::= ID LP distinct exprlist RP",
104023 /* 198 */ "expr ::= ID LP STAR RP",
104024 /* 199 */ "term ::= CTIME_KW",
104025 /* 200 */ "expr ::= expr AND expr",
104026 /* 201 */ "expr ::= expr OR expr",
104027 /* 202 */ "expr ::= expr LT|GT|GE|LE expr",
104028 /* 203 */ "expr ::= expr EQ|NE expr",
104029 /* 204 */ "expr ::= expr BITAND|BITOR|LSHIFT|RSHIFT expr",
104030 /* 205 */ "expr ::= expr PLUS|MINUS expr",
104031 /* 206 */ "expr ::= expr STAR|SLASH|REM expr",
104032 /* 207 */ "expr ::= expr CONCAT expr",
104033 /* 208 */ "likeop ::= LIKE_KW",
104034 /* 209 */ "likeop ::= NOT LIKE_KW",
104035 /* 210 */ "likeop ::= MATCH",
104036 /* 211 */ "likeop ::= NOT MATCH",
104037 /* 212 */ "expr ::= expr likeop expr",
104038 /* 213 */ "expr ::= expr likeop expr ESCAPE expr",
104039 /* 214 */ "expr ::= expr ISNULL|NOTNULL",
104040 /* 215 */ "expr ::= expr NOT NULL",
104041 /* 216 */ "expr ::= expr IS expr",
104042 /* 217 */ "expr ::= expr IS NOT expr",
104043 /* 218 */ "expr ::= NOT expr",
104044 /* 219 */ "expr ::= BITNOT expr",
104045 /* 220 */ "expr ::= MINUS expr",
104046 /* 221 */ "expr ::= PLUS expr",
104047 /* 222 */ "between_op ::= BETWEEN",
104048 /* 223 */ "between_op ::= NOT BETWEEN",
104049 /* 224 */ "expr ::= expr between_op expr AND expr",
104050 /* 225 */ "in_op ::= IN",
104051 /* 226 */ "in_op ::= NOT IN",
104052 /* 227 */ "expr ::= expr in_op LP exprlist RP",
104053 /* 228 */ "expr ::= LP select RP",
104054 /* 229 */ "expr ::= expr in_op LP select RP",
104055 /* 230 */ "expr ::= expr in_op nm dbnm",
104056 /* 231 */ "expr ::= EXISTS LP select RP",
104057 /* 232 */ "expr ::= CASE case_operand case_exprlist case_else END",
104058 /* 233 */ "case_exprlist ::= case_exprlist WHEN expr THEN expr",
104059 /* 234 */ "case_exprlist ::= WHEN expr THEN expr",
104060 /* 235 */ "case_else ::= ELSE expr",
104061 /* 236 */ "case_else ::=",
104062 /* 237 */ "case_operand ::= expr",
104063 /* 238 */ "case_operand ::=",
104064 /* 239 */ "exprlist ::= nexprlist",
104065 /* 240 */ "exprlist ::=",
104066 /* 241 */ "nexprlist ::= nexprlist COMMA expr",
104067 /* 242 */ "nexprlist ::= expr",
104068 /* 243 */ "cmd ::= createkw uniqueflag INDEX ifnotexists nm dbnm ON nm LP idxlist RP",
104069 /* 244 */ "uniqueflag ::= UNIQUE",
104070 /* 245 */ "uniqueflag ::=",
104071 /* 246 */ "idxlist_opt ::=",
104072 /* 247 */ "idxlist_opt ::= LP idxlist RP",
104073 /* 248 */ "idxlist ::= idxlist COMMA nm collate sortorder",
104074 /* 249 */ "idxlist ::= nm collate sortorder",
104075 /* 250 */ "collate ::=",
104076 /* 251 */ "collate ::= COLLATE ids",
104077 /* 252 */ "cmd ::= DROP INDEX ifexists fullname",
104078 /* 253 */ "cmd ::= VACUUM",
104079 /* 254 */ "cmd ::= VACUUM nm",
104080 /* 255 */ "cmd ::= PRAGMA nm dbnm",
104081 /* 256 */ "cmd ::= PRAGMA nm dbnm EQ nmnum",
104082 /* 257 */ "cmd ::= PRAGMA nm dbnm LP nmnum RP",
104083 /* 258 */ "cmd ::= PRAGMA nm dbnm EQ minus_num",
104084 /* 259 */ "cmd ::= PRAGMA nm dbnm LP minus_num RP",
104085 /* 260 */ "nmnum ::= plus_num",
104086 /* 261 */ "nmnum ::= nm",
104087 /* 262 */ "nmnum ::= ON",
104088 /* 263 */ "nmnum ::= DELETE",
104089 /* 264 */ "nmnum ::= DEFAULT",
104090 /* 265 */ "plus_num ::= plus_opt number",
104091 /* 266 */ "minus_num ::= MINUS number",
104092 /* 267 */ "number ::= INTEGER|FLOAT",
104093 /* 268 */ "plus_opt ::= PLUS",
104094 /* 269 */ "plus_opt ::=",
104095 /* 270 */ "cmd ::= createkw trigger_decl BEGIN trigger_cmd_list END",
104096 /* 271 */ "trigger_decl ::= temp TRIGGER ifnotexists nm dbnm trigger_time trigger_event ON fullname foreach_clause when_clause",
104097 /* 272 */ "trigger_time ::= BEFORE",
104098 /* 273 */ "trigger_time ::= AFTER",
104099 /* 274 */ "trigger_time ::= INSTEAD OF",
104100 /* 275 */ "trigger_time ::=",
104101 /* 276 */ "trigger_event ::= DELETE|INSERT",
104102 /* 277 */ "trigger_event ::= UPDATE",
104103 /* 278 */ "trigger_event ::= UPDATE OF inscollist",
104104 /* 279 */ "foreach_clause ::=",
104105 /* 280 */ "foreach_clause ::= FOR EACH ROW",
104106 /* 281 */ "when_clause ::=",
104107 /* 282 */ "when_clause ::= WHEN expr",
104108 /* 283 */ "trigger_cmd_list ::= trigger_cmd_list trigger_cmd SEMI",
104109 /* 284 */ "trigger_cmd_list ::= trigger_cmd SEMI",
104110 /* 285 */ "trnm ::= nm",
104111 /* 286 */ "trnm ::= nm DOT nm",
104112 /* 287 */ "tridxby ::=",
104113 /* 288 */ "tridxby ::= INDEXED BY nm",
104114 /* 289 */ "tridxby ::= NOT INDEXED",
104115 /* 290 */ "trigger_cmd ::= UPDATE orconf trnm tridxby SET setlist where_opt",
104116 /* 291 */ "trigger_cmd ::= insert_cmd INTO trnm inscollist_opt VALUES LP itemlist RP",
104117 /* 292 */ "trigger_cmd ::= insert_cmd INTO trnm inscollist_opt select",
104118 /* 293 */ "trigger_cmd ::= DELETE FROM trnm tridxby where_opt",
104119 /* 294 */ "trigger_cmd ::= select",
104120 /* 295 */ "expr ::= RAISE LP IGNORE RP",
104121 /* 296 */ "expr ::= RAISE LP raisetype COMMA nm RP",
104122 /* 297 */ "raisetype ::= ROLLBACK",
104123 /* 298 */ "raisetype ::= ABORT",
104124 /* 299 */ "raisetype ::= FAIL",
104125 /* 300 */ "cmd ::= DROP TRIGGER ifexists fullname",
104126 /* 301 */ "cmd ::= ATTACH database_kw_opt expr AS expr key_opt",
104127 /* 302 */ "cmd ::= DETACH database_kw_opt expr",
104128 /* 303 */ "key_opt ::=",
104129 /* 304 */ "key_opt ::= KEY expr",
104130 /* 305 */ "database_kw_opt ::= DATABASE",
104131 /* 306 */ "database_kw_opt ::=",
104132 /* 307 */ "cmd ::= REINDEX",
104133 /* 308 */ "cmd ::= REINDEX nm dbnm",
104134 /* 309 */ "cmd ::= ANALYZE",
104135 /* 310 */ "cmd ::= ANALYZE nm dbnm",
104136 /* 311 */ "cmd ::= ALTER TABLE fullname RENAME TO nm",
104137 /* 312 */ "cmd ::= ALTER TABLE add_column_fullname ADD kwcolumn_opt column",
104138 /* 313 */ "add_column_fullname ::= fullname",
104139 /* 314 */ "kwcolumn_opt ::=",
104140 /* 315 */ "kwcolumn_opt ::= COLUMNKW",
104141 /* 316 */ "cmd ::= create_vtab",
104142 /* 317 */ "cmd ::= create_vtab LP vtabarglist RP",
104143 /* 318 */ "create_vtab ::= createkw VIRTUAL TABLE nm dbnm USING nm",
104144 /* 319 */ "vtabarglist ::= vtabarg",
104145 /* 320 */ "vtabarglist ::= vtabarglist COMMA vtabarg",
104146 /* 321 */ "vtabarg ::=",
104147 /* 322 */ "vtabarg ::= vtabarg vtabargtoken",
104148 /* 323 */ "vtabargtoken ::= ANY",
104149 /* 324 */ "vtabargtoken ::= lp anylist RP",
104150 /* 325 */ "lp ::= LP",
104151 /* 326 */ "anylist ::=",
104152 /* 327 */ "anylist ::= anylist LP anylist RP",
104153 /* 328 */ "anylist ::= anylist ANY",
104155 #endif /* NDEBUG */
104158 #if YYSTACKDEPTH<=0
104160 ** Try to increase the size of the parser stack.
104162 static void yyGrowStack(yyParser *p){
104163 int newSize;
104164 yyStackEntry *pNew;
104166 newSize = p->yystksz*2 + 100;
104167 pNew = realloc(p->yystack, newSize*sizeof(pNew[0]));
104168 if( pNew ){
104169 p->yystack = pNew;
104170 p->yystksz = newSize;
104171 #ifndef NDEBUG
104172 if( yyTraceFILE ){
104173 fprintf(yyTraceFILE,"%sStack grows to %d entries!\n",
104174 yyTracePrompt, p->yystksz);
104176 #endif
104179 #endif
104182 ** This function allocates a new parser.
104183 ** The only argument is a pointer to a function which works like
104184 ** malloc.
104186 ** Inputs:
104187 ** A pointer to the function used to allocate memory.
104189 ** Outputs:
104190 ** A pointer to a parser. This pointer is used in subsequent calls
104191 ** to sqlite3Parser and sqlite3ParserFree.
104193 SQLITE_PRIVATE void *sqlite3ParserAlloc(void *(*mallocProc)(size_t)){
104194 yyParser *pParser;
104195 pParser = (yyParser*)(*mallocProc)( (size_t)sizeof(yyParser) );
104196 if( pParser ){
104197 pParser->yyidx = -1;
104198 #ifdef YYTRACKMAXSTACKDEPTH
104199 pParser->yyidxMax = 0;
104200 #endif
104201 #if YYSTACKDEPTH<=0
104202 pParser->yystack = NULL;
104203 pParser->yystksz = 0;
104204 yyGrowStack(pParser);
104205 #endif
104207 return pParser;
104210 /* The following function deletes the value associated with a
104211 ** symbol. The symbol can be either a terminal or nonterminal.
104212 ** "yymajor" is the symbol code, and "yypminor" is a pointer to
104213 ** the value.
104215 static void yy_destructor(
104216 yyParser *yypParser, /* The parser */
104217 YYCODETYPE yymajor, /* Type code for object to destroy */
104218 YYMINORTYPE *yypminor /* The object to be destroyed */
104220 sqlite3ParserARG_FETCH;
104221 switch( yymajor ){
104222 /* Here is inserted the actions which take place when a
104223 ** terminal or non-terminal is destroyed. This can happen
104224 ** when the symbol is popped from the stack during a
104225 ** reduce or during error processing or when a parser is
104226 ** being destroyed before it is finished parsing.
104228 ** Note: during a reduce, the only symbols destroyed are those
104229 ** which appear on the RHS of the rule, but which are not used
104230 ** inside the C code.
104232 case 160: /* select */
104233 case 194: /* oneselect */
104235 sqlite3SelectDelete(pParse->db, (yypminor->yy387));
104237 break;
104238 case 174: /* term */
104239 case 175: /* expr */
104241 sqlite3ExprDelete(pParse->db, (yypminor->yy118).pExpr);
104243 break;
104244 case 179: /* idxlist_opt */
104245 case 187: /* idxlist */
104246 case 197: /* selcollist */
104247 case 200: /* groupby_opt */
104248 case 202: /* orderby_opt */
104249 case 204: /* sclp */
104250 case 214: /* sortlist */
104251 case 216: /* nexprlist */
104252 case 217: /* setlist */
104253 case 220: /* itemlist */
104254 case 221: /* exprlist */
104255 case 226: /* case_exprlist */
104257 sqlite3ExprListDelete(pParse->db, (yypminor->yy322));
104259 break;
104260 case 193: /* fullname */
104261 case 198: /* from */
104262 case 206: /* seltablist */
104263 case 207: /* stl_prefix */
104265 sqlite3SrcListDelete(pParse->db, (yypminor->yy259));
104267 break;
104268 case 199: /* where_opt */
104269 case 201: /* having_opt */
104270 case 210: /* on_opt */
104271 case 215: /* sortitem */
104272 case 225: /* case_operand */
104273 case 227: /* case_else */
104274 case 238: /* when_clause */
104275 case 243: /* key_opt */
104277 sqlite3ExprDelete(pParse->db, (yypminor->yy314));
104279 break;
104280 case 211: /* using_opt */
104281 case 213: /* inscollist */
104282 case 219: /* inscollist_opt */
104284 sqlite3IdListDelete(pParse->db, (yypminor->yy384));
104286 break;
104287 case 234: /* trigger_cmd_list */
104288 case 239: /* trigger_cmd */
104290 sqlite3DeleteTriggerStep(pParse->db, (yypminor->yy203));
104292 break;
104293 case 236: /* trigger_event */
104295 sqlite3IdListDelete(pParse->db, (yypminor->yy90).b);
104297 break;
104298 default: break; /* If no destructor action specified: do nothing */
104303 ** Pop the parser's stack once.
104305 ** If there is a destructor routine associated with the token which
104306 ** is popped from the stack, then call it.
104308 ** Return the major token number for the symbol popped.
104310 static int yy_pop_parser_stack(yyParser *pParser){
104311 YYCODETYPE yymajor;
104312 yyStackEntry *yytos = &pParser->yystack[pParser->yyidx];
104314 /* There is no mechanism by which the parser stack can be popped below
104315 ** empty in SQLite. */
104316 if( NEVER(pParser->yyidx<0) ) return 0;
104317 #ifndef NDEBUG
104318 if( yyTraceFILE && pParser->yyidx>=0 ){
104319 fprintf(yyTraceFILE,"%sPopping %s\n",
104320 yyTracePrompt,
104321 yyTokenName[yytos->major]);
104323 #endif
104324 yymajor = yytos->major;
104325 yy_destructor(pParser, yymajor, &yytos->minor);
104326 pParser->yyidx--;
104327 return yymajor;
104331 ** Deallocate and destroy a parser. Destructors are all called for
104332 ** all stack elements before shutting the parser down.
104334 ** Inputs:
104335 ** <ul>
104336 ** <li> A pointer to the parser. This should be a pointer
104337 ** obtained from sqlite3ParserAlloc.
104338 ** <li> A pointer to a function used to reclaim memory obtained
104339 ** from malloc.
104340 ** </ul>
104342 SQLITE_PRIVATE void sqlite3ParserFree(
104343 void *p, /* The parser to be deleted */
104344 void (*freeProc)(void*) /* Function used to reclaim memory */
104346 yyParser *pParser = (yyParser*)p;
104347 /* In SQLite, we never try to destroy a parser that was not successfully
104348 ** created in the first place. */
104349 if( NEVER(pParser==0) ) return;
104350 while( pParser->yyidx>=0 ) yy_pop_parser_stack(pParser);
104351 #if YYSTACKDEPTH<=0
104352 free(pParser->yystack);
104353 #endif
104354 (*freeProc)((void*)pParser);
104358 ** Return the peak depth of the stack for a parser.
104360 #ifdef YYTRACKMAXSTACKDEPTH
104361 SQLITE_PRIVATE int sqlite3ParserStackPeak(void *p){
104362 yyParser *pParser = (yyParser*)p;
104363 return pParser->yyidxMax;
104365 #endif
104368 ** Find the appropriate action for a parser given the terminal
104369 ** look-ahead token iLookAhead.
104371 ** If the look-ahead token is YYNOCODE, then check to see if the action is
104372 ** independent of the look-ahead. If it is, return the action, otherwise
104373 ** return YY_NO_ACTION.
104375 static int yy_find_shift_action(
104376 yyParser *pParser, /* The parser */
104377 YYCODETYPE iLookAhead /* The look-ahead token */
104379 int i;
104380 int stateno = pParser->yystack[pParser->yyidx].stateno;
104382 if( stateno>YY_SHIFT_COUNT
104383 || (i = yy_shift_ofst[stateno])==YY_SHIFT_USE_DFLT ){
104384 return yy_default[stateno];
104386 assert( iLookAhead!=YYNOCODE );
104387 i += iLookAhead;
104388 if( i<0 || i>=YY_ACTTAB_COUNT || yy_lookahead[i]!=iLookAhead ){
104389 if( iLookAhead>0 ){
104390 #ifdef YYFALLBACK
104391 YYCODETYPE iFallback; /* Fallback token */
104392 if( iLookAhead<sizeof(yyFallback)/sizeof(yyFallback[0])
104393 && (iFallback = yyFallback[iLookAhead])!=0 ){
104394 #ifndef NDEBUG
104395 if( yyTraceFILE ){
104396 fprintf(yyTraceFILE, "%sFALLBACK %s => %s\n",
104397 yyTracePrompt, yyTokenName[iLookAhead], yyTokenName[iFallback]);
104399 #endif
104400 return yy_find_shift_action(pParser, iFallback);
104402 #endif
104403 #ifdef YYWILDCARD
104405 int j = i - iLookAhead + YYWILDCARD;
104407 #if YY_SHIFT_MIN+YYWILDCARD<0
104408 j>=0 &&
104409 #endif
104410 #if YY_SHIFT_MAX+YYWILDCARD>=YY_ACTTAB_COUNT
104411 j<YY_ACTTAB_COUNT &&
104412 #endif
104413 yy_lookahead[j]==YYWILDCARD
104415 #ifndef NDEBUG
104416 if( yyTraceFILE ){
104417 fprintf(yyTraceFILE, "%sWILDCARD %s => %s\n",
104418 yyTracePrompt, yyTokenName[iLookAhead], yyTokenName[YYWILDCARD]);
104420 #endif /* NDEBUG */
104421 return yy_action[j];
104424 #endif /* YYWILDCARD */
104426 return yy_default[stateno];
104427 }else{
104428 return yy_action[i];
104433 ** Find the appropriate action for a parser given the non-terminal
104434 ** look-ahead token iLookAhead.
104436 ** If the look-ahead token is YYNOCODE, then check to see if the action is
104437 ** independent of the look-ahead. If it is, return the action, otherwise
104438 ** return YY_NO_ACTION.
104440 static int yy_find_reduce_action(
104441 int stateno, /* Current state number */
104442 YYCODETYPE iLookAhead /* The look-ahead token */
104444 int i;
104445 #ifdef YYERRORSYMBOL
104446 if( stateno>YY_REDUCE_COUNT ){
104447 return yy_default[stateno];
104449 #else
104450 assert( stateno<=YY_REDUCE_COUNT );
104451 #endif
104452 i = yy_reduce_ofst[stateno];
104453 assert( i!=YY_REDUCE_USE_DFLT );
104454 assert( iLookAhead!=YYNOCODE );
104455 i += iLookAhead;
104456 #ifdef YYERRORSYMBOL
104457 if( i<0 || i>=YY_ACTTAB_COUNT || yy_lookahead[i]!=iLookAhead ){
104458 return yy_default[stateno];
104460 #else
104461 assert( i>=0 && i<YY_ACTTAB_COUNT );
104462 assert( yy_lookahead[i]==iLookAhead );
104463 #endif
104464 return yy_action[i];
104468 ** The following routine is called if the stack overflows.
104470 static void yyStackOverflow(yyParser *yypParser, YYMINORTYPE *yypMinor){
104471 sqlite3ParserARG_FETCH;
104472 yypParser->yyidx--;
104473 #ifndef NDEBUG
104474 if( yyTraceFILE ){
104475 fprintf(yyTraceFILE,"%sStack Overflow!\n",yyTracePrompt);
104477 #endif
104478 while( yypParser->yyidx>=0 ) yy_pop_parser_stack(yypParser);
104479 /* Here code is inserted which will execute if the parser
104480 ** stack every overflows */
104482 UNUSED_PARAMETER(yypMinor); /* Silence some compiler warnings */
104483 sqlite3ErrorMsg(pParse, "parser stack overflow");
104484 pParse->parseError = 1;
104485 sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument var */
104489 ** Perform a shift action.
104491 static void yy_shift(
104492 yyParser *yypParser, /* The parser to be shifted */
104493 int yyNewState, /* The new state to shift in */
104494 int yyMajor, /* The major token to shift in */
104495 YYMINORTYPE *yypMinor /* Pointer to the minor token to shift in */
104497 yyStackEntry *yytos;
104498 yypParser->yyidx++;
104499 #ifdef YYTRACKMAXSTACKDEPTH
104500 if( yypParser->yyidx>yypParser->yyidxMax ){
104501 yypParser->yyidxMax = yypParser->yyidx;
104503 #endif
104504 #if YYSTACKDEPTH>0
104505 if( yypParser->yyidx>=YYSTACKDEPTH ){
104506 yyStackOverflow(yypParser, yypMinor);
104507 return;
104509 #else
104510 if( yypParser->yyidx>=yypParser->yystksz ){
104511 yyGrowStack(yypParser);
104512 if( yypParser->yyidx>=yypParser->yystksz ){
104513 yyStackOverflow(yypParser, yypMinor);
104514 return;
104517 #endif
104518 yytos = &yypParser->yystack[yypParser->yyidx];
104519 yytos->stateno = (YYACTIONTYPE)yyNewState;
104520 yytos->major = (YYCODETYPE)yyMajor;
104521 yytos->minor = *yypMinor;
104522 #ifndef NDEBUG
104523 if( yyTraceFILE && yypParser->yyidx>0 ){
104524 int i;
104525 fprintf(yyTraceFILE,"%sShift %d\n",yyTracePrompt,yyNewState);
104526 fprintf(yyTraceFILE,"%sStack:",yyTracePrompt);
104527 for(i=1; i<=yypParser->yyidx; i++)
104528 fprintf(yyTraceFILE," %s",yyTokenName[yypParser->yystack[i].major]);
104529 fprintf(yyTraceFILE,"\n");
104531 #endif
104534 /* The following table contains information about every rule that
104535 ** is used during the reduce.
104537 static const struct {
104538 YYCODETYPE lhs; /* Symbol on the left-hand side of the rule */
104539 unsigned char nrhs; /* Number of right-hand side symbols in the rule */
104540 } yyRuleInfo[] = {
104541 { 142, 1 },
104542 { 143, 2 },
104543 { 143, 1 },
104544 { 144, 1 },
104545 { 144, 3 },
104546 { 145, 0 },
104547 { 145, 1 },
104548 { 145, 3 },
104549 { 146, 1 },
104550 { 147, 3 },
104551 { 149, 0 },
104552 { 149, 1 },
104553 { 149, 2 },
104554 { 148, 0 },
104555 { 148, 1 },
104556 { 148, 1 },
104557 { 148, 1 },
104558 { 147, 2 },
104559 { 147, 2 },
104560 { 147, 2 },
104561 { 151, 1 },
104562 { 151, 0 },
104563 { 147, 2 },
104564 { 147, 3 },
104565 { 147, 5 },
104566 { 147, 2 },
104567 { 152, 6 },
104568 { 154, 1 },
104569 { 156, 0 },
104570 { 156, 3 },
104571 { 155, 1 },
104572 { 155, 0 },
104573 { 153, 4 },
104574 { 153, 2 },
104575 { 158, 3 },
104576 { 158, 1 },
104577 { 161, 3 },
104578 { 162, 1 },
104579 { 165, 1 },
104580 { 165, 1 },
104581 { 166, 1 },
104582 { 150, 1 },
104583 { 150, 1 },
104584 { 150, 1 },
104585 { 163, 0 },
104586 { 163, 1 },
104587 { 167, 1 },
104588 { 167, 4 },
104589 { 167, 6 },
104590 { 168, 1 },
104591 { 168, 2 },
104592 { 169, 1 },
104593 { 169, 1 },
104594 { 164, 2 },
104595 { 164, 0 },
104596 { 172, 3 },
104597 { 172, 1 },
104598 { 173, 2 },
104599 { 173, 4 },
104600 { 173, 3 },
104601 { 173, 3 },
104602 { 173, 2 },
104603 { 173, 2 },
104604 { 173, 3 },
104605 { 173, 5 },
104606 { 173, 2 },
104607 { 173, 4 },
104608 { 173, 4 },
104609 { 173, 1 },
104610 { 173, 2 },
104611 { 178, 0 },
104612 { 178, 1 },
104613 { 180, 0 },
104614 { 180, 2 },
104615 { 182, 2 },
104616 { 182, 3 },
104617 { 182, 3 },
104618 { 182, 3 },
104619 { 183, 2 },
104620 { 183, 2 },
104621 { 183, 1 },
104622 { 183, 1 },
104623 { 183, 2 },
104624 { 181, 3 },
104625 { 181, 2 },
104626 { 184, 0 },
104627 { 184, 2 },
104628 { 184, 2 },
104629 { 159, 0 },
104630 { 159, 2 },
104631 { 185, 3 },
104632 { 185, 2 },
104633 { 185, 1 },
104634 { 186, 2 },
104635 { 186, 7 },
104636 { 186, 5 },
104637 { 186, 5 },
104638 { 186, 10 },
104639 { 188, 0 },
104640 { 188, 1 },
104641 { 176, 0 },
104642 { 176, 3 },
104643 { 189, 0 },
104644 { 189, 2 },
104645 { 190, 1 },
104646 { 190, 1 },
104647 { 190, 1 },
104648 { 147, 4 },
104649 { 192, 2 },
104650 { 192, 0 },
104651 { 147, 8 },
104652 { 147, 4 },
104653 { 147, 1 },
104654 { 160, 1 },
104655 { 160, 3 },
104656 { 195, 1 },
104657 { 195, 2 },
104658 { 195, 1 },
104659 { 194, 9 },
104660 { 196, 1 },
104661 { 196, 1 },
104662 { 196, 0 },
104663 { 204, 2 },
104664 { 204, 0 },
104665 { 197, 3 },
104666 { 197, 2 },
104667 { 197, 4 },
104668 { 205, 2 },
104669 { 205, 1 },
104670 { 205, 0 },
104671 { 198, 0 },
104672 { 198, 2 },
104673 { 207, 2 },
104674 { 207, 0 },
104675 { 206, 7 },
104676 { 206, 7 },
104677 { 206, 7 },
104678 { 157, 0 },
104679 { 157, 2 },
104680 { 193, 2 },
104681 { 208, 1 },
104682 { 208, 2 },
104683 { 208, 3 },
104684 { 208, 4 },
104685 { 210, 2 },
104686 { 210, 0 },
104687 { 209, 0 },
104688 { 209, 3 },
104689 { 209, 2 },
104690 { 211, 4 },
104691 { 211, 0 },
104692 { 202, 0 },
104693 { 202, 3 },
104694 { 214, 4 },
104695 { 214, 2 },
104696 { 215, 1 },
104697 { 177, 1 },
104698 { 177, 1 },
104699 { 177, 0 },
104700 { 200, 0 },
104701 { 200, 3 },
104702 { 201, 0 },
104703 { 201, 2 },
104704 { 203, 0 },
104705 { 203, 2 },
104706 { 203, 4 },
104707 { 203, 4 },
104708 { 147, 5 },
104709 { 199, 0 },
104710 { 199, 2 },
104711 { 147, 7 },
104712 { 217, 5 },
104713 { 217, 3 },
104714 { 147, 8 },
104715 { 147, 5 },
104716 { 147, 6 },
104717 { 218, 2 },
104718 { 218, 1 },
104719 { 220, 3 },
104720 { 220, 1 },
104721 { 219, 0 },
104722 { 219, 3 },
104723 { 213, 3 },
104724 { 213, 1 },
104725 { 175, 1 },
104726 { 175, 3 },
104727 { 174, 1 },
104728 { 175, 1 },
104729 { 175, 1 },
104730 { 175, 3 },
104731 { 175, 5 },
104732 { 174, 1 },
104733 { 174, 1 },
104734 { 175, 1 },
104735 { 175, 1 },
104736 { 175, 3 },
104737 { 175, 6 },
104738 { 175, 5 },
104739 { 175, 4 },
104740 { 174, 1 },
104741 { 175, 3 },
104742 { 175, 3 },
104743 { 175, 3 },
104744 { 175, 3 },
104745 { 175, 3 },
104746 { 175, 3 },
104747 { 175, 3 },
104748 { 175, 3 },
104749 { 222, 1 },
104750 { 222, 2 },
104751 { 222, 1 },
104752 { 222, 2 },
104753 { 175, 3 },
104754 { 175, 5 },
104755 { 175, 2 },
104756 { 175, 3 },
104757 { 175, 3 },
104758 { 175, 4 },
104759 { 175, 2 },
104760 { 175, 2 },
104761 { 175, 2 },
104762 { 175, 2 },
104763 { 223, 1 },
104764 { 223, 2 },
104765 { 175, 5 },
104766 { 224, 1 },
104767 { 224, 2 },
104768 { 175, 5 },
104769 { 175, 3 },
104770 { 175, 5 },
104771 { 175, 4 },
104772 { 175, 4 },
104773 { 175, 5 },
104774 { 226, 5 },
104775 { 226, 4 },
104776 { 227, 2 },
104777 { 227, 0 },
104778 { 225, 1 },
104779 { 225, 0 },
104780 { 221, 1 },
104781 { 221, 0 },
104782 { 216, 3 },
104783 { 216, 1 },
104784 { 147, 11 },
104785 { 228, 1 },
104786 { 228, 0 },
104787 { 179, 0 },
104788 { 179, 3 },
104789 { 187, 5 },
104790 { 187, 3 },
104791 { 229, 0 },
104792 { 229, 2 },
104793 { 147, 4 },
104794 { 147, 1 },
104795 { 147, 2 },
104796 { 147, 3 },
104797 { 147, 5 },
104798 { 147, 6 },
104799 { 147, 5 },
104800 { 147, 6 },
104801 { 230, 1 },
104802 { 230, 1 },
104803 { 230, 1 },
104804 { 230, 1 },
104805 { 230, 1 },
104806 { 170, 2 },
104807 { 171, 2 },
104808 { 232, 1 },
104809 { 231, 1 },
104810 { 231, 0 },
104811 { 147, 5 },
104812 { 233, 11 },
104813 { 235, 1 },
104814 { 235, 1 },
104815 { 235, 2 },
104816 { 235, 0 },
104817 { 236, 1 },
104818 { 236, 1 },
104819 { 236, 3 },
104820 { 237, 0 },
104821 { 237, 3 },
104822 { 238, 0 },
104823 { 238, 2 },
104824 { 234, 3 },
104825 { 234, 2 },
104826 { 240, 1 },
104827 { 240, 3 },
104828 { 241, 0 },
104829 { 241, 3 },
104830 { 241, 2 },
104831 { 239, 7 },
104832 { 239, 8 },
104833 { 239, 5 },
104834 { 239, 5 },
104835 { 239, 1 },
104836 { 175, 4 },
104837 { 175, 6 },
104838 { 191, 1 },
104839 { 191, 1 },
104840 { 191, 1 },
104841 { 147, 4 },
104842 { 147, 6 },
104843 { 147, 3 },
104844 { 243, 0 },
104845 { 243, 2 },
104846 { 242, 1 },
104847 { 242, 0 },
104848 { 147, 1 },
104849 { 147, 3 },
104850 { 147, 1 },
104851 { 147, 3 },
104852 { 147, 6 },
104853 { 147, 6 },
104854 { 244, 1 },
104855 { 245, 0 },
104856 { 245, 1 },
104857 { 147, 1 },
104858 { 147, 4 },
104859 { 246, 7 },
104860 { 247, 1 },
104861 { 247, 3 },
104862 { 248, 0 },
104863 { 248, 2 },
104864 { 249, 1 },
104865 { 249, 3 },
104866 { 250, 1 },
104867 { 251, 0 },
104868 { 251, 4 },
104869 { 251, 2 },
104872 static void yy_accept(yyParser*); /* Forward Declaration */
104875 ** Perform a reduce action and the shift that must immediately
104876 ** follow the reduce.
104878 static void yy_reduce(
104879 yyParser *yypParser, /* The parser */
104880 int yyruleno /* Number of the rule by which to reduce */
104882 int yygoto; /* The next state */
104883 int yyact; /* The next action */
104884 YYMINORTYPE yygotominor; /* The LHS of the rule reduced */
104885 yyStackEntry *yymsp; /* The top of the parser's stack */
104886 int yysize; /* Amount to pop the stack */
104887 sqlite3ParserARG_FETCH;
104888 yymsp = &yypParser->yystack[yypParser->yyidx];
104889 #ifndef NDEBUG
104890 if( yyTraceFILE && yyruleno>=0
104891 && yyruleno<(int)(sizeof(yyRuleName)/sizeof(yyRuleName[0])) ){
104892 fprintf(yyTraceFILE, "%sReduce [%s].\n", yyTracePrompt,
104893 yyRuleName[yyruleno]);
104895 #endif /* NDEBUG */
104897 /* Silence complaints from purify about yygotominor being uninitialized
104898 ** in some cases when it is copied into the stack after the following
104899 ** switch. yygotominor is uninitialized when a rule reduces that does
104900 ** not set the value of its left-hand side nonterminal. Leaving the
104901 ** value of the nonterminal uninitialized is utterly harmless as long
104902 ** as the value is never used. So really the only thing this code
104903 ** accomplishes is to quieten purify.
104905 ** 2007-01-16: The wireshark project (www.wireshark.org) reports that
104906 ** without this code, their parser segfaults. I'm not sure what there
104907 ** parser is doing to make this happen. This is the second bug report
104908 ** from wireshark this week. Clearly they are stressing Lemon in ways
104909 ** that it has not been previously stressed... (SQLite ticket #2172)
104911 /*memset(&yygotominor, 0, sizeof(yygotominor));*/
104912 yygotominor = yyzerominor;
104915 switch( yyruleno ){
104916 /* Beginning here are the reduction cases. A typical example
104917 ** follows:
104918 ** case 0:
104919 ** #line <lineno> <grammarfile>
104920 ** { ... } // User supplied code
104921 ** #line <lineno> <thisfile>
104922 ** break;
104924 case 5: /* explain ::= */
104925 { sqlite3BeginParse(pParse, 0); }
104926 break;
104927 case 6: /* explain ::= EXPLAIN */
104928 { sqlite3BeginParse(pParse, 1); }
104929 break;
104930 case 7: /* explain ::= EXPLAIN QUERY PLAN */
104931 { sqlite3BeginParse(pParse, 2); }
104932 break;
104933 case 8: /* cmdx ::= cmd */
104934 { sqlite3FinishCoding(pParse); }
104935 break;
104936 case 9: /* cmd ::= BEGIN transtype trans_opt */
104937 {sqlite3BeginTransaction(pParse, yymsp[-1].minor.yy4);}
104938 break;
104939 case 13: /* transtype ::= */
104940 {yygotominor.yy4 = TK_DEFERRED;}
104941 break;
104942 case 14: /* transtype ::= DEFERRED */
104943 case 15: /* transtype ::= IMMEDIATE */ yytestcase(yyruleno==15);
104944 case 16: /* transtype ::= EXCLUSIVE */ yytestcase(yyruleno==16);
104945 case 115: /* multiselect_op ::= UNION */ yytestcase(yyruleno==115);
104946 case 117: /* multiselect_op ::= EXCEPT|INTERSECT */ yytestcase(yyruleno==117);
104947 {yygotominor.yy4 = yymsp[0].major;}
104948 break;
104949 case 17: /* cmd ::= COMMIT trans_opt */
104950 case 18: /* cmd ::= END trans_opt */ yytestcase(yyruleno==18);
104951 {sqlite3CommitTransaction(pParse);}
104952 break;
104953 case 19: /* cmd ::= ROLLBACK trans_opt */
104954 {sqlite3RollbackTransaction(pParse);}
104955 break;
104956 case 22: /* cmd ::= SAVEPOINT nm */
104958 sqlite3Savepoint(pParse, SAVEPOINT_BEGIN, &yymsp[0].minor.yy0);
104960 break;
104961 case 23: /* cmd ::= RELEASE savepoint_opt nm */
104963 sqlite3Savepoint(pParse, SAVEPOINT_RELEASE, &yymsp[0].minor.yy0);
104965 break;
104966 case 24: /* cmd ::= ROLLBACK trans_opt TO savepoint_opt nm */
104968 sqlite3Savepoint(pParse, SAVEPOINT_ROLLBACK, &yymsp[0].minor.yy0);
104970 break;
104971 case 26: /* create_table ::= createkw temp TABLE ifnotexists nm dbnm */
104973 sqlite3StartTable(pParse,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0,yymsp[-4].minor.yy4,0,0,yymsp[-2].minor.yy4);
104975 break;
104976 case 27: /* createkw ::= CREATE */
104978 pParse->db->lookaside.bEnabled = 0;
104979 yygotominor.yy0 = yymsp[0].minor.yy0;
104981 break;
104982 case 28: /* ifnotexists ::= */
104983 case 31: /* temp ::= */ yytestcase(yyruleno==31);
104984 case 70: /* autoinc ::= */ yytestcase(yyruleno==70);
104985 case 83: /* defer_subclause ::= NOT DEFERRABLE init_deferred_pred_opt */ yytestcase(yyruleno==83);
104986 case 85: /* init_deferred_pred_opt ::= */ yytestcase(yyruleno==85);
104987 case 87: /* init_deferred_pred_opt ::= INITIALLY IMMEDIATE */ yytestcase(yyruleno==87);
104988 case 98: /* defer_subclause_opt ::= */ yytestcase(yyruleno==98);
104989 case 109: /* ifexists ::= */ yytestcase(yyruleno==109);
104990 case 120: /* distinct ::= ALL */ yytestcase(yyruleno==120);
104991 case 121: /* distinct ::= */ yytestcase(yyruleno==121);
104992 case 222: /* between_op ::= BETWEEN */ yytestcase(yyruleno==222);
104993 case 225: /* in_op ::= IN */ yytestcase(yyruleno==225);
104994 {yygotominor.yy4 = 0;}
104995 break;
104996 case 29: /* ifnotexists ::= IF NOT EXISTS */
104997 case 30: /* temp ::= TEMP */ yytestcase(yyruleno==30);
104998 case 71: /* autoinc ::= AUTOINCR */ yytestcase(yyruleno==71);
104999 case 86: /* init_deferred_pred_opt ::= INITIALLY DEFERRED */ yytestcase(yyruleno==86);
105000 case 108: /* ifexists ::= IF EXISTS */ yytestcase(yyruleno==108);
105001 case 119: /* distinct ::= DISTINCT */ yytestcase(yyruleno==119);
105002 case 223: /* between_op ::= NOT BETWEEN */ yytestcase(yyruleno==223);
105003 case 226: /* in_op ::= NOT IN */ yytestcase(yyruleno==226);
105004 {yygotominor.yy4 = 1;}
105005 break;
105006 case 32: /* create_table_args ::= LP columnlist conslist_opt RP */
105008 sqlite3EndTable(pParse,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0,0);
105010 break;
105011 case 33: /* create_table_args ::= AS select */
105013 sqlite3EndTable(pParse,0,0,yymsp[0].minor.yy387);
105014 sqlite3SelectDelete(pParse->db, yymsp[0].minor.yy387);
105016 break;
105017 case 36: /* column ::= columnid type carglist */
105019 yygotominor.yy0.z = yymsp[-2].minor.yy0.z;
105020 yygotominor.yy0.n = (int)(pParse->sLastToken.z-yymsp[-2].minor.yy0.z) + pParse->sLastToken.n;
105022 break;
105023 case 37: /* columnid ::= nm */
105025 sqlite3AddColumn(pParse,&yymsp[0].minor.yy0);
105026 yygotominor.yy0 = yymsp[0].minor.yy0;
105028 break;
105029 case 38: /* id ::= ID */
105030 case 39: /* id ::= INDEXED */ yytestcase(yyruleno==39);
105031 case 40: /* ids ::= ID|STRING */ yytestcase(yyruleno==40);
105032 case 41: /* nm ::= id */ yytestcase(yyruleno==41);
105033 case 42: /* nm ::= STRING */ yytestcase(yyruleno==42);
105034 case 43: /* nm ::= JOIN_KW */ yytestcase(yyruleno==43);
105035 case 46: /* typetoken ::= typename */ yytestcase(yyruleno==46);
105036 case 49: /* typename ::= ids */ yytestcase(yyruleno==49);
105037 case 127: /* as ::= AS nm */ yytestcase(yyruleno==127);
105038 case 128: /* as ::= ids */ yytestcase(yyruleno==128);
105039 case 138: /* dbnm ::= DOT nm */ yytestcase(yyruleno==138);
105040 case 147: /* indexed_opt ::= INDEXED BY nm */ yytestcase(yyruleno==147);
105041 case 251: /* collate ::= COLLATE ids */ yytestcase(yyruleno==251);
105042 case 260: /* nmnum ::= plus_num */ yytestcase(yyruleno==260);
105043 case 261: /* nmnum ::= nm */ yytestcase(yyruleno==261);
105044 case 262: /* nmnum ::= ON */ yytestcase(yyruleno==262);
105045 case 263: /* nmnum ::= DELETE */ yytestcase(yyruleno==263);
105046 case 264: /* nmnum ::= DEFAULT */ yytestcase(yyruleno==264);
105047 case 265: /* plus_num ::= plus_opt number */ yytestcase(yyruleno==265);
105048 case 266: /* minus_num ::= MINUS number */ yytestcase(yyruleno==266);
105049 case 267: /* number ::= INTEGER|FLOAT */ yytestcase(yyruleno==267);
105050 case 285: /* trnm ::= nm */ yytestcase(yyruleno==285);
105051 {yygotominor.yy0 = yymsp[0].minor.yy0;}
105052 break;
105053 case 45: /* type ::= typetoken */
105054 {sqlite3AddColumnType(pParse,&yymsp[0].minor.yy0);}
105055 break;
105056 case 47: /* typetoken ::= typename LP signed RP */
105058 yygotominor.yy0.z = yymsp[-3].minor.yy0.z;
105059 yygotominor.yy0.n = (int)(&yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n] - yymsp[-3].minor.yy0.z);
105061 break;
105062 case 48: /* typetoken ::= typename LP signed COMMA signed RP */
105064 yygotominor.yy0.z = yymsp[-5].minor.yy0.z;
105065 yygotominor.yy0.n = (int)(&yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n] - yymsp[-5].minor.yy0.z);
105067 break;
105068 case 50: /* typename ::= typename ids */
105069 {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);}
105070 break;
105071 case 57: /* ccons ::= DEFAULT term */
105072 case 59: /* ccons ::= DEFAULT PLUS term */ yytestcase(yyruleno==59);
105073 {sqlite3AddDefaultValue(pParse,&yymsp[0].minor.yy118);}
105074 break;
105075 case 58: /* ccons ::= DEFAULT LP expr RP */
105076 {sqlite3AddDefaultValue(pParse,&yymsp[-1].minor.yy118);}
105077 break;
105078 case 60: /* ccons ::= DEFAULT MINUS term */
105080 ExprSpan v;
105081 v.pExpr = sqlite3PExpr(pParse, TK_UMINUS, yymsp[0].minor.yy118.pExpr, 0, 0);
105082 v.zStart = yymsp[-1].minor.yy0.z;
105083 v.zEnd = yymsp[0].minor.yy118.zEnd;
105084 sqlite3AddDefaultValue(pParse,&v);
105086 break;
105087 case 61: /* ccons ::= DEFAULT id */
105089 ExprSpan v;
105090 spanExpr(&v, pParse, TK_STRING, &yymsp[0].minor.yy0);
105091 sqlite3AddDefaultValue(pParse,&v);
105093 break;
105094 case 63: /* ccons ::= NOT NULL onconf */
105095 {sqlite3AddNotNull(pParse, yymsp[0].minor.yy4);}
105096 break;
105097 case 64: /* ccons ::= PRIMARY KEY sortorder onconf autoinc */
105098 {sqlite3AddPrimaryKey(pParse,0,yymsp[-1].minor.yy4,yymsp[0].minor.yy4,yymsp[-2].minor.yy4);}
105099 break;
105100 case 65: /* ccons ::= UNIQUE onconf */
105101 {sqlite3CreateIndex(pParse,0,0,0,0,yymsp[0].minor.yy4,0,0,0,0);}
105102 break;
105103 case 66: /* ccons ::= CHECK LP expr RP */
105104 {sqlite3AddCheckConstraint(pParse,yymsp[-1].minor.yy118.pExpr);}
105105 break;
105106 case 67: /* ccons ::= REFERENCES nm idxlist_opt refargs */
105107 {sqlite3CreateForeignKey(pParse,0,&yymsp[-2].minor.yy0,yymsp[-1].minor.yy322,yymsp[0].minor.yy4);}
105108 break;
105109 case 68: /* ccons ::= defer_subclause */
105110 {sqlite3DeferForeignKey(pParse,yymsp[0].minor.yy4);}
105111 break;
105112 case 69: /* ccons ::= COLLATE ids */
105113 {sqlite3AddCollateType(pParse, &yymsp[0].minor.yy0);}
105114 break;
105115 case 72: /* refargs ::= */
105116 { yygotominor.yy4 = OE_None*0x0101; /* EV: R-19803-45884 */}
105117 break;
105118 case 73: /* refargs ::= refargs refarg */
105119 { yygotominor.yy4 = (yymsp[-1].minor.yy4 & ~yymsp[0].minor.yy215.mask) | yymsp[0].minor.yy215.value; }
105120 break;
105121 case 74: /* refarg ::= MATCH nm */
105122 case 75: /* refarg ::= ON INSERT refact */ yytestcase(yyruleno==75);
105123 { yygotominor.yy215.value = 0; yygotominor.yy215.mask = 0x000000; }
105124 break;
105125 case 76: /* refarg ::= ON DELETE refact */
105126 { yygotominor.yy215.value = yymsp[0].minor.yy4; yygotominor.yy215.mask = 0x0000ff; }
105127 break;
105128 case 77: /* refarg ::= ON UPDATE refact */
105129 { yygotominor.yy215.value = yymsp[0].minor.yy4<<8; yygotominor.yy215.mask = 0x00ff00; }
105130 break;
105131 case 78: /* refact ::= SET NULL */
105132 { yygotominor.yy4 = OE_SetNull; /* EV: R-33326-45252 */}
105133 break;
105134 case 79: /* refact ::= SET DEFAULT */
105135 { yygotominor.yy4 = OE_SetDflt; /* EV: R-33326-45252 */}
105136 break;
105137 case 80: /* refact ::= CASCADE */
105138 { yygotominor.yy4 = OE_Cascade; /* EV: R-33326-45252 */}
105139 break;
105140 case 81: /* refact ::= RESTRICT */
105141 { yygotominor.yy4 = OE_Restrict; /* EV: R-33326-45252 */}
105142 break;
105143 case 82: /* refact ::= NO ACTION */
105144 { yygotominor.yy4 = OE_None; /* EV: R-33326-45252 */}
105145 break;
105146 case 84: /* defer_subclause ::= DEFERRABLE init_deferred_pred_opt */
105147 case 99: /* defer_subclause_opt ::= defer_subclause */ yytestcase(yyruleno==99);
105148 case 101: /* onconf ::= ON CONFLICT resolvetype */ yytestcase(yyruleno==101);
105149 case 104: /* resolvetype ::= raisetype */ yytestcase(yyruleno==104);
105150 {yygotominor.yy4 = yymsp[0].minor.yy4;}
105151 break;
105152 case 88: /* conslist_opt ::= */
105153 {yygotominor.yy0.n = 0; yygotominor.yy0.z = 0;}
105154 break;
105155 case 89: /* conslist_opt ::= COMMA conslist */
105156 {yygotominor.yy0 = yymsp[-1].minor.yy0;}
105157 break;
105158 case 94: /* tcons ::= PRIMARY KEY LP idxlist autoinc RP onconf */
105159 {sqlite3AddPrimaryKey(pParse,yymsp[-3].minor.yy322,yymsp[0].minor.yy4,yymsp[-2].minor.yy4,0);}
105160 break;
105161 case 95: /* tcons ::= UNIQUE LP idxlist RP onconf */
105162 {sqlite3CreateIndex(pParse,0,0,0,yymsp[-2].minor.yy322,yymsp[0].minor.yy4,0,0,0,0);}
105163 break;
105164 case 96: /* tcons ::= CHECK LP expr RP onconf */
105165 {sqlite3AddCheckConstraint(pParse,yymsp[-2].minor.yy118.pExpr);}
105166 break;
105167 case 97: /* tcons ::= FOREIGN KEY LP idxlist RP REFERENCES nm idxlist_opt refargs defer_subclause_opt */
105169 sqlite3CreateForeignKey(pParse, yymsp[-6].minor.yy322, &yymsp[-3].minor.yy0, yymsp[-2].minor.yy322, yymsp[-1].minor.yy4);
105170 sqlite3DeferForeignKey(pParse, yymsp[0].minor.yy4);
105172 break;
105173 case 100: /* onconf ::= */
105174 {yygotominor.yy4 = OE_Default;}
105175 break;
105176 case 102: /* orconf ::= */
105177 {yygotominor.yy210 = OE_Default;}
105178 break;
105179 case 103: /* orconf ::= OR resolvetype */
105180 {yygotominor.yy210 = (u8)yymsp[0].minor.yy4;}
105181 break;
105182 case 105: /* resolvetype ::= IGNORE */
105183 {yygotominor.yy4 = OE_Ignore;}
105184 break;
105185 case 106: /* resolvetype ::= REPLACE */
105186 {yygotominor.yy4 = OE_Replace;}
105187 break;
105188 case 107: /* cmd ::= DROP TABLE ifexists fullname */
105190 sqlite3DropTable(pParse, yymsp[0].minor.yy259, 0, yymsp[-1].minor.yy4);
105192 break;
105193 case 110: /* cmd ::= createkw temp VIEW ifnotexists nm dbnm AS select */
105195 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);
105197 break;
105198 case 111: /* cmd ::= DROP VIEW ifexists fullname */
105200 sqlite3DropTable(pParse, yymsp[0].minor.yy259, 1, yymsp[-1].minor.yy4);
105202 break;
105203 case 112: /* cmd ::= select */
105205 SelectDest dest = {SRT_Output, 0, 0, 0, 0};
105206 sqlite3Select(pParse, yymsp[0].minor.yy387, &dest);
105207 sqlite3SelectDelete(pParse->db, yymsp[0].minor.yy387);
105209 break;
105210 case 113: /* select ::= oneselect */
105211 {yygotominor.yy387 = yymsp[0].minor.yy387;}
105212 break;
105213 case 114: /* select ::= select multiselect_op oneselect */
105215 if( yymsp[0].minor.yy387 ){
105216 yymsp[0].minor.yy387->op = (u8)yymsp[-1].minor.yy4;
105217 yymsp[0].minor.yy387->pPrior = yymsp[-2].minor.yy387;
105218 }else{
105219 sqlite3SelectDelete(pParse->db, yymsp[-2].minor.yy387);
105221 yygotominor.yy387 = yymsp[0].minor.yy387;
105223 break;
105224 case 116: /* multiselect_op ::= UNION ALL */
105225 {yygotominor.yy4 = TK_ALL;}
105226 break;
105227 case 118: /* oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt orderby_opt limit_opt */
105229 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);
105231 break;
105232 case 122: /* sclp ::= selcollist COMMA */
105233 case 247: /* idxlist_opt ::= LP idxlist RP */ yytestcase(yyruleno==247);
105234 {yygotominor.yy322 = yymsp[-1].minor.yy322;}
105235 break;
105236 case 123: /* sclp ::= */
105237 case 151: /* orderby_opt ::= */ yytestcase(yyruleno==151);
105238 case 159: /* groupby_opt ::= */ yytestcase(yyruleno==159);
105239 case 240: /* exprlist ::= */ yytestcase(yyruleno==240);
105240 case 246: /* idxlist_opt ::= */ yytestcase(yyruleno==246);
105241 {yygotominor.yy322 = 0;}
105242 break;
105243 case 124: /* selcollist ::= sclp expr as */
105245 yygotominor.yy322 = sqlite3ExprListAppend(pParse, yymsp[-2].minor.yy322, yymsp[-1].minor.yy118.pExpr);
105246 if( yymsp[0].minor.yy0.n>0 ) sqlite3ExprListSetName(pParse, yygotominor.yy322, &yymsp[0].minor.yy0, 1);
105247 sqlite3ExprListSetSpan(pParse,yygotominor.yy322,&yymsp[-1].minor.yy118);
105249 break;
105250 case 125: /* selcollist ::= sclp STAR */
105252 Expr *p = sqlite3Expr(pParse->db, TK_ALL, 0);
105253 yygotominor.yy322 = sqlite3ExprListAppend(pParse, yymsp[-1].minor.yy322, p);
105255 break;
105256 case 126: /* selcollist ::= sclp nm DOT STAR */
105258 Expr *pRight = sqlite3PExpr(pParse, TK_ALL, 0, 0, &yymsp[0].minor.yy0);
105259 Expr *pLeft = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-2].minor.yy0);
105260 Expr *pDot = sqlite3PExpr(pParse, TK_DOT, pLeft, pRight, 0);
105261 yygotominor.yy322 = sqlite3ExprListAppend(pParse,yymsp[-3].minor.yy322, pDot);
105263 break;
105264 case 129: /* as ::= */
105265 {yygotominor.yy0.n = 0;}
105266 break;
105267 case 130: /* from ::= */
105268 {yygotominor.yy259 = sqlite3DbMallocZero(pParse->db, sizeof(*yygotominor.yy259));}
105269 break;
105270 case 131: /* from ::= FROM seltablist */
105272 yygotominor.yy259 = yymsp[0].minor.yy259;
105273 sqlite3SrcListShiftJoinType(yygotominor.yy259);
105275 break;
105276 case 132: /* stl_prefix ::= seltablist joinop */
105278 yygotominor.yy259 = yymsp[-1].minor.yy259;
105279 if( ALWAYS(yygotominor.yy259 && yygotominor.yy259->nSrc>0) ) yygotominor.yy259->a[yygotominor.yy259->nSrc-1].jointype = (u8)yymsp[0].minor.yy4;
105281 break;
105282 case 133: /* stl_prefix ::= */
105283 {yygotominor.yy259 = 0;}
105284 break;
105285 case 134: /* seltablist ::= stl_prefix nm dbnm as indexed_opt on_opt using_opt */
105287 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);
105288 sqlite3SrcListIndexedBy(pParse, yygotominor.yy259, &yymsp[-2].minor.yy0);
105290 break;
105291 case 135: /* seltablist ::= stl_prefix LP select RP as on_opt using_opt */
105293 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);
105295 break;
105296 case 136: /* seltablist ::= stl_prefix LP seltablist RP as on_opt using_opt */
105298 if( yymsp[-6].minor.yy259==0 && yymsp[-2].minor.yy0.n==0 && yymsp[-1].minor.yy314==0 && yymsp[0].minor.yy384==0 ){
105299 yygotominor.yy259 = yymsp[-4].minor.yy259;
105300 }else{
105301 Select *pSubquery;
105302 sqlite3SrcListShiftJoinType(yymsp[-4].minor.yy259);
105303 pSubquery = sqlite3SelectNew(pParse,0,yymsp[-4].minor.yy259,0,0,0,0,0,0,0);
105304 yygotominor.yy259 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-6].minor.yy259,0,0,&yymsp[-2].minor.yy0,pSubquery,yymsp[-1].minor.yy314,yymsp[0].minor.yy384);
105307 break;
105308 case 137: /* dbnm ::= */
105309 case 146: /* indexed_opt ::= */ yytestcase(yyruleno==146);
105310 {yygotominor.yy0.z=0; yygotominor.yy0.n=0;}
105311 break;
105312 case 139: /* fullname ::= nm dbnm */
105313 {yygotominor.yy259 = sqlite3SrcListAppend(pParse->db,0,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0);}
105314 break;
105315 case 140: /* joinop ::= COMMA|JOIN */
105316 { yygotominor.yy4 = JT_INNER; }
105317 break;
105318 case 141: /* joinop ::= JOIN_KW JOIN */
105319 { yygotominor.yy4 = sqlite3JoinType(pParse,&yymsp[-1].minor.yy0,0,0); }
105320 break;
105321 case 142: /* joinop ::= JOIN_KW nm JOIN */
105322 { yygotominor.yy4 = sqlite3JoinType(pParse,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0,0); }
105323 break;
105324 case 143: /* joinop ::= JOIN_KW nm nm JOIN */
105325 { yygotominor.yy4 = sqlite3JoinType(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0); }
105326 break;
105327 case 144: /* on_opt ::= ON expr */
105328 case 155: /* sortitem ::= expr */ yytestcase(yyruleno==155);
105329 case 162: /* having_opt ::= HAVING expr */ yytestcase(yyruleno==162);
105330 case 169: /* where_opt ::= WHERE expr */ yytestcase(yyruleno==169);
105331 case 235: /* case_else ::= ELSE expr */ yytestcase(yyruleno==235);
105332 case 237: /* case_operand ::= expr */ yytestcase(yyruleno==237);
105333 {yygotominor.yy314 = yymsp[0].minor.yy118.pExpr;}
105334 break;
105335 case 145: /* on_opt ::= */
105336 case 161: /* having_opt ::= */ yytestcase(yyruleno==161);
105337 case 168: /* where_opt ::= */ yytestcase(yyruleno==168);
105338 case 236: /* case_else ::= */ yytestcase(yyruleno==236);
105339 case 238: /* case_operand ::= */ yytestcase(yyruleno==238);
105340 {yygotominor.yy314 = 0;}
105341 break;
105342 case 148: /* indexed_opt ::= NOT INDEXED */
105343 {yygotominor.yy0.z=0; yygotominor.yy0.n=1;}
105344 break;
105345 case 149: /* using_opt ::= USING LP inscollist RP */
105346 case 181: /* inscollist_opt ::= LP inscollist RP */ yytestcase(yyruleno==181);
105347 {yygotominor.yy384 = yymsp[-1].minor.yy384;}
105348 break;
105349 case 150: /* using_opt ::= */
105350 case 180: /* inscollist_opt ::= */ yytestcase(yyruleno==180);
105351 {yygotominor.yy384 = 0;}
105352 break;
105353 case 152: /* orderby_opt ::= ORDER BY sortlist */
105354 case 160: /* groupby_opt ::= GROUP BY nexprlist */ yytestcase(yyruleno==160);
105355 case 239: /* exprlist ::= nexprlist */ yytestcase(yyruleno==239);
105356 {yygotominor.yy322 = yymsp[0].minor.yy322;}
105357 break;
105358 case 153: /* sortlist ::= sortlist COMMA sortitem sortorder */
105360 yygotominor.yy322 = sqlite3ExprListAppend(pParse,yymsp[-3].minor.yy322,yymsp[-1].minor.yy314);
105361 if( yygotominor.yy322 ) yygotominor.yy322->a[yygotominor.yy322->nExpr-1].sortOrder = (u8)yymsp[0].minor.yy4;
105363 break;
105364 case 154: /* sortlist ::= sortitem sortorder */
105366 yygotominor.yy322 = sqlite3ExprListAppend(pParse,0,yymsp[-1].minor.yy314);
105367 if( yygotominor.yy322 && ALWAYS(yygotominor.yy322->a) ) yygotominor.yy322->a[0].sortOrder = (u8)yymsp[0].minor.yy4;
105369 break;
105370 case 156: /* sortorder ::= ASC */
105371 case 158: /* sortorder ::= */ yytestcase(yyruleno==158);
105372 {yygotominor.yy4 = SQLITE_SO_ASC;}
105373 break;
105374 case 157: /* sortorder ::= DESC */
105375 {yygotominor.yy4 = SQLITE_SO_DESC;}
105376 break;
105377 case 163: /* limit_opt ::= */
105378 {yygotominor.yy292.pLimit = 0; yygotominor.yy292.pOffset = 0;}
105379 break;
105380 case 164: /* limit_opt ::= LIMIT expr */
105381 {yygotominor.yy292.pLimit = yymsp[0].minor.yy118.pExpr; yygotominor.yy292.pOffset = 0;}
105382 break;
105383 case 165: /* limit_opt ::= LIMIT expr OFFSET expr */
105384 {yygotominor.yy292.pLimit = yymsp[-2].minor.yy118.pExpr; yygotominor.yy292.pOffset = yymsp[0].minor.yy118.pExpr;}
105385 break;
105386 case 166: /* limit_opt ::= LIMIT expr COMMA expr */
105387 {yygotominor.yy292.pOffset = yymsp[-2].minor.yy118.pExpr; yygotominor.yy292.pLimit = yymsp[0].minor.yy118.pExpr;}
105388 break;
105389 case 167: /* cmd ::= DELETE FROM fullname indexed_opt where_opt */
105391 sqlite3SrcListIndexedBy(pParse, yymsp[-2].minor.yy259, &yymsp[-1].minor.yy0);
105392 sqlite3DeleteFrom(pParse,yymsp[-2].minor.yy259,yymsp[0].minor.yy314);
105394 break;
105395 case 170: /* cmd ::= UPDATE orconf fullname indexed_opt SET setlist where_opt */
105397 sqlite3SrcListIndexedBy(pParse, yymsp[-4].minor.yy259, &yymsp[-3].minor.yy0);
105398 sqlite3ExprListCheckLength(pParse,yymsp[-1].minor.yy322,"set list");
105399 sqlite3Update(pParse,yymsp[-4].minor.yy259,yymsp[-1].minor.yy322,yymsp[0].minor.yy314,yymsp[-5].minor.yy210);
105401 break;
105402 case 171: /* setlist ::= setlist COMMA nm EQ expr */
105404 yygotominor.yy322 = sqlite3ExprListAppend(pParse, yymsp[-4].minor.yy322, yymsp[0].minor.yy118.pExpr);
105405 sqlite3ExprListSetName(pParse, yygotominor.yy322, &yymsp[-2].minor.yy0, 1);
105407 break;
105408 case 172: /* setlist ::= nm EQ expr */
105410 yygotominor.yy322 = sqlite3ExprListAppend(pParse, 0, yymsp[0].minor.yy118.pExpr);
105411 sqlite3ExprListSetName(pParse, yygotominor.yy322, &yymsp[-2].minor.yy0, 1);
105413 break;
105414 case 173: /* cmd ::= insert_cmd INTO fullname inscollist_opt VALUES LP itemlist RP */
105415 {sqlite3Insert(pParse, yymsp[-5].minor.yy259, yymsp[-1].minor.yy322, 0, yymsp[-4].minor.yy384, yymsp[-7].minor.yy210);}
105416 break;
105417 case 174: /* cmd ::= insert_cmd INTO fullname inscollist_opt select */
105418 {sqlite3Insert(pParse, yymsp[-2].minor.yy259, 0, yymsp[0].minor.yy387, yymsp[-1].minor.yy384, yymsp[-4].minor.yy210);}
105419 break;
105420 case 175: /* cmd ::= insert_cmd INTO fullname inscollist_opt DEFAULT VALUES */
105421 {sqlite3Insert(pParse, yymsp[-3].minor.yy259, 0, 0, yymsp[-2].minor.yy384, yymsp[-5].minor.yy210);}
105422 break;
105423 case 176: /* insert_cmd ::= INSERT orconf */
105424 {yygotominor.yy210 = yymsp[0].minor.yy210;}
105425 break;
105426 case 177: /* insert_cmd ::= REPLACE */
105427 {yygotominor.yy210 = OE_Replace;}
105428 break;
105429 case 178: /* itemlist ::= itemlist COMMA expr */
105430 case 241: /* nexprlist ::= nexprlist COMMA expr */ yytestcase(yyruleno==241);
105431 {yygotominor.yy322 = sqlite3ExprListAppend(pParse,yymsp[-2].minor.yy322,yymsp[0].minor.yy118.pExpr);}
105432 break;
105433 case 179: /* itemlist ::= expr */
105434 case 242: /* nexprlist ::= expr */ yytestcase(yyruleno==242);
105435 {yygotominor.yy322 = sqlite3ExprListAppend(pParse,0,yymsp[0].minor.yy118.pExpr);}
105436 break;
105437 case 182: /* inscollist ::= inscollist COMMA nm */
105438 {yygotominor.yy384 = sqlite3IdListAppend(pParse->db,yymsp[-2].minor.yy384,&yymsp[0].minor.yy0);}
105439 break;
105440 case 183: /* inscollist ::= nm */
105441 {yygotominor.yy384 = sqlite3IdListAppend(pParse->db,0,&yymsp[0].minor.yy0);}
105442 break;
105443 case 184: /* expr ::= term */
105444 {yygotominor.yy118 = yymsp[0].minor.yy118;}
105445 break;
105446 case 185: /* expr ::= LP expr RP */
105447 {yygotominor.yy118.pExpr = yymsp[-1].minor.yy118.pExpr; spanSet(&yygotominor.yy118,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0);}
105448 break;
105449 case 186: /* term ::= NULL */
105450 case 191: /* term ::= INTEGER|FLOAT|BLOB */ yytestcase(yyruleno==191);
105451 case 192: /* term ::= STRING */ yytestcase(yyruleno==192);
105452 {spanExpr(&yygotominor.yy118, pParse, yymsp[0].major, &yymsp[0].minor.yy0);}
105453 break;
105454 case 187: /* expr ::= id */
105455 case 188: /* expr ::= JOIN_KW */ yytestcase(yyruleno==188);
105456 {spanExpr(&yygotominor.yy118, pParse, TK_ID, &yymsp[0].minor.yy0);}
105457 break;
105458 case 189: /* expr ::= nm DOT nm */
105460 Expr *temp1 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-2].minor.yy0);
105461 Expr *temp2 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[0].minor.yy0);
105462 yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_DOT, temp1, temp2, 0);
105463 spanSet(&yygotominor.yy118,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0);
105465 break;
105466 case 190: /* expr ::= nm DOT nm DOT nm */
105468 Expr *temp1 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-4].minor.yy0);
105469 Expr *temp2 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-2].minor.yy0);
105470 Expr *temp3 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[0].minor.yy0);
105471 Expr *temp4 = sqlite3PExpr(pParse, TK_DOT, temp2, temp3, 0);
105472 yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_DOT, temp1, temp4, 0);
105473 spanSet(&yygotominor.yy118,&yymsp[-4].minor.yy0,&yymsp[0].minor.yy0);
105475 break;
105476 case 193: /* expr ::= REGISTER */
105478 /* When doing a nested parse, one can include terms in an expression
105479 ** that look like this: #1 #2 ... These terms refer to registers
105480 ** in the virtual machine. #N is the N-th register. */
105481 if( pParse->nested==0 ){
105482 sqlite3ErrorMsg(pParse, "near \"%T\": syntax error", &yymsp[0].minor.yy0);
105483 yygotominor.yy118.pExpr = 0;
105484 }else{
105485 yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_REGISTER, 0, 0, &yymsp[0].minor.yy0);
105486 if( yygotominor.yy118.pExpr ) sqlite3GetInt32(&yymsp[0].minor.yy0.z[1], &yygotominor.yy118.pExpr->iTable);
105488 spanSet(&yygotominor.yy118, &yymsp[0].minor.yy0, &yymsp[0].minor.yy0);
105490 break;
105491 case 194: /* expr ::= VARIABLE */
105493 spanExpr(&yygotominor.yy118, pParse, TK_VARIABLE, &yymsp[0].minor.yy0);
105494 sqlite3ExprAssignVarNumber(pParse, yygotominor.yy118.pExpr);
105495 spanSet(&yygotominor.yy118, &yymsp[0].minor.yy0, &yymsp[0].minor.yy0);
105497 break;
105498 case 195: /* expr ::= expr COLLATE ids */
105500 yygotominor.yy118.pExpr = sqlite3ExprSetCollByToken(pParse, yymsp[-2].minor.yy118.pExpr, &yymsp[0].minor.yy0);
105501 yygotominor.yy118.zStart = yymsp[-2].minor.yy118.zStart;
105502 yygotominor.yy118.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
105504 break;
105505 case 196: /* expr ::= CAST LP expr AS typetoken RP */
105507 yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_CAST, yymsp[-3].minor.yy118.pExpr, 0, &yymsp[-1].minor.yy0);
105508 spanSet(&yygotominor.yy118,&yymsp[-5].minor.yy0,&yymsp[0].minor.yy0);
105510 break;
105511 case 197: /* expr ::= ID LP distinct exprlist RP */
105513 if( yymsp[-1].minor.yy322 && yymsp[-1].minor.yy322->nExpr>pParse->db->aLimit[SQLITE_LIMIT_FUNCTION_ARG] ){
105514 sqlite3ErrorMsg(pParse, "too many arguments on function %T", &yymsp[-4].minor.yy0);
105516 yygotominor.yy118.pExpr = sqlite3ExprFunction(pParse, yymsp[-1].minor.yy322, &yymsp[-4].minor.yy0);
105517 spanSet(&yygotominor.yy118,&yymsp[-4].minor.yy0,&yymsp[0].minor.yy0);
105518 if( yymsp[-2].minor.yy4 && yygotominor.yy118.pExpr ){
105519 yygotominor.yy118.pExpr->flags |= EP_Distinct;
105522 break;
105523 case 198: /* expr ::= ID LP STAR RP */
105525 yygotominor.yy118.pExpr = sqlite3ExprFunction(pParse, 0, &yymsp[-3].minor.yy0);
105526 spanSet(&yygotominor.yy118,&yymsp[-3].minor.yy0,&yymsp[0].minor.yy0);
105528 break;
105529 case 199: /* term ::= CTIME_KW */
105531 /* The CURRENT_TIME, CURRENT_DATE, and CURRENT_TIMESTAMP values are
105532 ** treated as functions that return constants */
105533 yygotominor.yy118.pExpr = sqlite3ExprFunction(pParse, 0,&yymsp[0].minor.yy0);
105534 if( yygotominor.yy118.pExpr ){
105535 yygotominor.yy118.pExpr->op = TK_CONST_FUNC;
105537 spanSet(&yygotominor.yy118, &yymsp[0].minor.yy0, &yymsp[0].minor.yy0);
105539 break;
105540 case 200: /* expr ::= expr AND expr */
105541 case 201: /* expr ::= expr OR expr */ yytestcase(yyruleno==201);
105542 case 202: /* expr ::= expr LT|GT|GE|LE expr */ yytestcase(yyruleno==202);
105543 case 203: /* expr ::= expr EQ|NE expr */ yytestcase(yyruleno==203);
105544 case 204: /* expr ::= expr BITAND|BITOR|LSHIFT|RSHIFT expr */ yytestcase(yyruleno==204);
105545 case 205: /* expr ::= expr PLUS|MINUS expr */ yytestcase(yyruleno==205);
105546 case 206: /* expr ::= expr STAR|SLASH|REM expr */ yytestcase(yyruleno==206);
105547 case 207: /* expr ::= expr CONCAT expr */ yytestcase(yyruleno==207);
105548 {spanBinaryExpr(&yygotominor.yy118,pParse,yymsp[-1].major,&yymsp[-2].minor.yy118,&yymsp[0].minor.yy118);}
105549 break;
105550 case 208: /* likeop ::= LIKE_KW */
105551 case 210: /* likeop ::= MATCH */ yytestcase(yyruleno==210);
105552 {yygotominor.yy342.eOperator = yymsp[0].minor.yy0; yygotominor.yy342.not = 0;}
105553 break;
105554 case 209: /* likeop ::= NOT LIKE_KW */
105555 case 211: /* likeop ::= NOT MATCH */ yytestcase(yyruleno==211);
105556 {yygotominor.yy342.eOperator = yymsp[0].minor.yy0; yygotominor.yy342.not = 1;}
105557 break;
105558 case 212: /* expr ::= expr likeop expr */
105560 ExprList *pList;
105561 pList = sqlite3ExprListAppend(pParse,0, yymsp[0].minor.yy118.pExpr);
105562 pList = sqlite3ExprListAppend(pParse,pList, yymsp[-2].minor.yy118.pExpr);
105563 yygotominor.yy118.pExpr = sqlite3ExprFunction(pParse, pList, &yymsp[-1].minor.yy342.eOperator);
105564 if( yymsp[-1].minor.yy342.not ) yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy118.pExpr, 0, 0);
105565 yygotominor.yy118.zStart = yymsp[-2].minor.yy118.zStart;
105566 yygotominor.yy118.zEnd = yymsp[0].minor.yy118.zEnd;
105567 if( yygotominor.yy118.pExpr ) yygotominor.yy118.pExpr->flags |= EP_InfixFunc;
105569 break;
105570 case 213: /* expr ::= expr likeop expr ESCAPE expr */
105572 ExprList *pList;
105573 pList = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy118.pExpr);
105574 pList = sqlite3ExprListAppend(pParse,pList, yymsp[-4].minor.yy118.pExpr);
105575 pList = sqlite3ExprListAppend(pParse,pList, yymsp[0].minor.yy118.pExpr);
105576 yygotominor.yy118.pExpr = sqlite3ExprFunction(pParse, pList, &yymsp[-3].minor.yy342.eOperator);
105577 if( yymsp[-3].minor.yy342.not ) yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy118.pExpr, 0, 0);
105578 yygotominor.yy118.zStart = yymsp[-4].minor.yy118.zStart;
105579 yygotominor.yy118.zEnd = yymsp[0].minor.yy118.zEnd;
105580 if( yygotominor.yy118.pExpr ) yygotominor.yy118.pExpr->flags |= EP_InfixFunc;
105582 break;
105583 case 214: /* expr ::= expr ISNULL|NOTNULL */
105584 {spanUnaryPostfix(&yygotominor.yy118,pParse,yymsp[0].major,&yymsp[-1].minor.yy118,&yymsp[0].minor.yy0);}
105585 break;
105586 case 215: /* expr ::= expr NOT NULL */
105587 {spanUnaryPostfix(&yygotominor.yy118,pParse,TK_NOTNULL,&yymsp[-2].minor.yy118,&yymsp[0].minor.yy0);}
105588 break;
105589 case 216: /* expr ::= expr IS expr */
105591 spanBinaryExpr(&yygotominor.yy118,pParse,TK_IS,&yymsp[-2].minor.yy118,&yymsp[0].minor.yy118);
105592 binaryToUnaryIfNull(pParse, yymsp[0].minor.yy118.pExpr, yygotominor.yy118.pExpr, TK_ISNULL);
105594 break;
105595 case 217: /* expr ::= expr IS NOT expr */
105597 spanBinaryExpr(&yygotominor.yy118,pParse,TK_ISNOT,&yymsp[-3].minor.yy118,&yymsp[0].minor.yy118);
105598 binaryToUnaryIfNull(pParse, yymsp[0].minor.yy118.pExpr, yygotominor.yy118.pExpr, TK_NOTNULL);
105600 break;
105601 case 218: /* expr ::= NOT expr */
105602 case 219: /* expr ::= BITNOT expr */ yytestcase(yyruleno==219);
105603 {spanUnaryPrefix(&yygotominor.yy118,pParse,yymsp[-1].major,&yymsp[0].minor.yy118,&yymsp[-1].minor.yy0);}
105604 break;
105605 case 220: /* expr ::= MINUS expr */
105606 {spanUnaryPrefix(&yygotominor.yy118,pParse,TK_UMINUS,&yymsp[0].minor.yy118,&yymsp[-1].minor.yy0);}
105607 break;
105608 case 221: /* expr ::= PLUS expr */
105609 {spanUnaryPrefix(&yygotominor.yy118,pParse,TK_UPLUS,&yymsp[0].minor.yy118,&yymsp[-1].minor.yy0);}
105610 break;
105611 case 224: /* expr ::= expr between_op expr AND expr */
105613 ExprList *pList = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy118.pExpr);
105614 pList = sqlite3ExprListAppend(pParse,pList, yymsp[0].minor.yy118.pExpr);
105615 yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_BETWEEN, yymsp[-4].minor.yy118.pExpr, 0, 0);
105616 if( yygotominor.yy118.pExpr ){
105617 yygotominor.yy118.pExpr->x.pList = pList;
105618 }else{
105619 sqlite3ExprListDelete(pParse->db, pList);
105621 if( yymsp[-3].minor.yy4 ) yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy118.pExpr, 0, 0);
105622 yygotominor.yy118.zStart = yymsp[-4].minor.yy118.zStart;
105623 yygotominor.yy118.zEnd = yymsp[0].minor.yy118.zEnd;
105625 break;
105626 case 227: /* expr ::= expr in_op LP exprlist RP */
105628 if( yymsp[-1].minor.yy322==0 ){
105629 /* Expressions of the form
105631 ** expr1 IN ()
105632 ** expr1 NOT IN ()
105634 ** simplify to constants 0 (false) and 1 (true), respectively,
105635 ** regardless of the value of expr1.
105637 yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_INTEGER, 0, 0, &sqlite3IntTokens[yymsp[-3].minor.yy4]);
105638 sqlite3ExprDelete(pParse->db, yymsp[-4].minor.yy118.pExpr);
105639 }else{
105640 yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_IN, yymsp[-4].minor.yy118.pExpr, 0, 0);
105641 if( yygotominor.yy118.pExpr ){
105642 yygotominor.yy118.pExpr->x.pList = yymsp[-1].minor.yy322;
105643 sqlite3ExprSetHeight(pParse, yygotominor.yy118.pExpr);
105644 }else{
105645 sqlite3ExprListDelete(pParse->db, yymsp[-1].minor.yy322);
105647 if( yymsp[-3].minor.yy4 ) yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy118.pExpr, 0, 0);
105649 yygotominor.yy118.zStart = yymsp[-4].minor.yy118.zStart;
105650 yygotominor.yy118.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
105652 break;
105653 case 228: /* expr ::= LP select RP */
105655 yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_SELECT, 0, 0, 0);
105656 if( yygotominor.yy118.pExpr ){
105657 yygotominor.yy118.pExpr->x.pSelect = yymsp[-1].minor.yy387;
105658 ExprSetProperty(yygotominor.yy118.pExpr, EP_xIsSelect);
105659 sqlite3ExprSetHeight(pParse, yygotominor.yy118.pExpr);
105660 }else{
105661 sqlite3SelectDelete(pParse->db, yymsp[-1].minor.yy387);
105663 yygotominor.yy118.zStart = yymsp[-2].minor.yy0.z;
105664 yygotominor.yy118.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
105666 break;
105667 case 229: /* expr ::= expr in_op LP select RP */
105669 yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_IN, yymsp[-4].minor.yy118.pExpr, 0, 0);
105670 if( yygotominor.yy118.pExpr ){
105671 yygotominor.yy118.pExpr->x.pSelect = yymsp[-1].minor.yy387;
105672 ExprSetProperty(yygotominor.yy118.pExpr, EP_xIsSelect);
105673 sqlite3ExprSetHeight(pParse, yygotominor.yy118.pExpr);
105674 }else{
105675 sqlite3SelectDelete(pParse->db, yymsp[-1].minor.yy387);
105677 if( yymsp[-3].minor.yy4 ) yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy118.pExpr, 0, 0);
105678 yygotominor.yy118.zStart = yymsp[-4].minor.yy118.zStart;
105679 yygotominor.yy118.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
105681 break;
105682 case 230: /* expr ::= expr in_op nm dbnm */
105684 SrcList *pSrc = sqlite3SrcListAppend(pParse->db, 0,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0);
105685 yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_IN, yymsp[-3].minor.yy118.pExpr, 0, 0);
105686 if( yygotominor.yy118.pExpr ){
105687 yygotominor.yy118.pExpr->x.pSelect = sqlite3SelectNew(pParse, 0,pSrc,0,0,0,0,0,0,0);
105688 ExprSetProperty(yygotominor.yy118.pExpr, EP_xIsSelect);
105689 sqlite3ExprSetHeight(pParse, yygotominor.yy118.pExpr);
105690 }else{
105691 sqlite3SrcListDelete(pParse->db, pSrc);
105693 if( yymsp[-2].minor.yy4 ) yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy118.pExpr, 0, 0);
105694 yygotominor.yy118.zStart = yymsp[-3].minor.yy118.zStart;
105695 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];
105697 break;
105698 case 231: /* expr ::= EXISTS LP select RP */
105700 Expr *p = yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_EXISTS, 0, 0, 0);
105701 if( p ){
105702 p->x.pSelect = yymsp[-1].minor.yy387;
105703 ExprSetProperty(p, EP_xIsSelect);
105704 sqlite3ExprSetHeight(pParse, p);
105705 }else{
105706 sqlite3SelectDelete(pParse->db, yymsp[-1].minor.yy387);
105708 yygotominor.yy118.zStart = yymsp[-3].minor.yy0.z;
105709 yygotominor.yy118.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
105711 break;
105712 case 232: /* expr ::= CASE case_operand case_exprlist case_else END */
105714 yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_CASE, yymsp[-3].minor.yy314, yymsp[-1].minor.yy314, 0);
105715 if( yygotominor.yy118.pExpr ){
105716 yygotominor.yy118.pExpr->x.pList = yymsp[-2].minor.yy322;
105717 sqlite3ExprSetHeight(pParse, yygotominor.yy118.pExpr);
105718 }else{
105719 sqlite3ExprListDelete(pParse->db, yymsp[-2].minor.yy322);
105721 yygotominor.yy118.zStart = yymsp[-4].minor.yy0.z;
105722 yygotominor.yy118.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
105724 break;
105725 case 233: /* case_exprlist ::= case_exprlist WHEN expr THEN expr */
105727 yygotominor.yy322 = sqlite3ExprListAppend(pParse,yymsp[-4].minor.yy322, yymsp[-2].minor.yy118.pExpr);
105728 yygotominor.yy322 = sqlite3ExprListAppend(pParse,yygotominor.yy322, yymsp[0].minor.yy118.pExpr);
105730 break;
105731 case 234: /* case_exprlist ::= WHEN expr THEN expr */
105733 yygotominor.yy322 = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy118.pExpr);
105734 yygotominor.yy322 = sqlite3ExprListAppend(pParse,yygotominor.yy322, yymsp[0].minor.yy118.pExpr);
105736 break;
105737 case 243: /* cmd ::= createkw uniqueflag INDEX ifnotexists nm dbnm ON nm LP idxlist RP */
105739 sqlite3CreateIndex(pParse, &yymsp[-6].minor.yy0, &yymsp[-5].minor.yy0,
105740 sqlite3SrcListAppend(pParse->db,0,&yymsp[-3].minor.yy0,0), yymsp[-1].minor.yy322, yymsp[-9].minor.yy4,
105741 &yymsp[-10].minor.yy0, &yymsp[0].minor.yy0, SQLITE_SO_ASC, yymsp[-7].minor.yy4);
105743 break;
105744 case 244: /* uniqueflag ::= UNIQUE */
105745 case 298: /* raisetype ::= ABORT */ yytestcase(yyruleno==298);
105746 {yygotominor.yy4 = OE_Abort;}
105747 break;
105748 case 245: /* uniqueflag ::= */
105749 {yygotominor.yy4 = OE_None;}
105750 break;
105751 case 248: /* idxlist ::= idxlist COMMA nm collate sortorder */
105753 Expr *p = 0;
105754 if( yymsp[-1].minor.yy0.n>0 ){
105755 p = sqlite3Expr(pParse->db, TK_COLUMN, 0);
105756 sqlite3ExprSetCollByToken(pParse, p, &yymsp[-1].minor.yy0);
105758 yygotominor.yy322 = sqlite3ExprListAppend(pParse,yymsp[-4].minor.yy322, p);
105759 sqlite3ExprListSetName(pParse,yygotominor.yy322,&yymsp[-2].minor.yy0,1);
105760 sqlite3ExprListCheckLength(pParse, yygotominor.yy322, "index");
105761 if( yygotominor.yy322 ) yygotominor.yy322->a[yygotominor.yy322->nExpr-1].sortOrder = (u8)yymsp[0].minor.yy4;
105763 break;
105764 case 249: /* idxlist ::= nm collate sortorder */
105766 Expr *p = 0;
105767 if( yymsp[-1].minor.yy0.n>0 ){
105768 p = sqlite3PExpr(pParse, TK_COLUMN, 0, 0, 0);
105769 sqlite3ExprSetCollByToken(pParse, p, &yymsp[-1].minor.yy0);
105771 yygotominor.yy322 = sqlite3ExprListAppend(pParse,0, p);
105772 sqlite3ExprListSetName(pParse, yygotominor.yy322, &yymsp[-2].minor.yy0, 1);
105773 sqlite3ExprListCheckLength(pParse, yygotominor.yy322, "index");
105774 if( yygotominor.yy322 ) yygotominor.yy322->a[yygotominor.yy322->nExpr-1].sortOrder = (u8)yymsp[0].minor.yy4;
105776 break;
105777 case 250: /* collate ::= */
105778 {yygotominor.yy0.z = 0; yygotominor.yy0.n = 0;}
105779 break;
105780 case 252: /* cmd ::= DROP INDEX ifexists fullname */
105781 {sqlite3DropIndex(pParse, yymsp[0].minor.yy259, yymsp[-1].minor.yy4);}
105782 break;
105783 case 253: /* cmd ::= VACUUM */
105784 case 254: /* cmd ::= VACUUM nm */ yytestcase(yyruleno==254);
105785 {sqlite3Vacuum(pParse);}
105786 break;
105787 case 255: /* cmd ::= PRAGMA nm dbnm */
105788 {sqlite3Pragma(pParse,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0,0,0);}
105789 break;
105790 case 256: /* cmd ::= PRAGMA nm dbnm EQ nmnum */
105791 {sqlite3Pragma(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0,0);}
105792 break;
105793 case 257: /* cmd ::= PRAGMA nm dbnm LP nmnum RP */
105794 {sqlite3Pragma(pParse,&yymsp[-4].minor.yy0,&yymsp[-3].minor.yy0,&yymsp[-1].minor.yy0,0);}
105795 break;
105796 case 258: /* cmd ::= PRAGMA nm dbnm EQ minus_num */
105797 {sqlite3Pragma(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0,1);}
105798 break;
105799 case 259: /* cmd ::= PRAGMA nm dbnm LP minus_num RP */
105800 {sqlite3Pragma(pParse,&yymsp[-4].minor.yy0,&yymsp[-3].minor.yy0,&yymsp[-1].minor.yy0,1);}
105801 break;
105802 case 270: /* cmd ::= createkw trigger_decl BEGIN trigger_cmd_list END */
105804 Token all;
105805 all.z = yymsp[-3].minor.yy0.z;
105806 all.n = (int)(yymsp[0].minor.yy0.z - yymsp[-3].minor.yy0.z) + yymsp[0].minor.yy0.n;
105807 sqlite3FinishTrigger(pParse, yymsp[-1].minor.yy203, &all);
105809 break;
105810 case 271: /* trigger_decl ::= temp TRIGGER ifnotexists nm dbnm trigger_time trigger_event ON fullname foreach_clause when_clause */
105812 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);
105813 yygotominor.yy0 = (yymsp[-6].minor.yy0.n==0?yymsp[-7].minor.yy0:yymsp[-6].minor.yy0);
105815 break;
105816 case 272: /* trigger_time ::= BEFORE */
105817 case 275: /* trigger_time ::= */ yytestcase(yyruleno==275);
105818 { yygotominor.yy4 = TK_BEFORE; }
105819 break;
105820 case 273: /* trigger_time ::= AFTER */
105821 { yygotominor.yy4 = TK_AFTER; }
105822 break;
105823 case 274: /* trigger_time ::= INSTEAD OF */
105824 { yygotominor.yy4 = TK_INSTEAD;}
105825 break;
105826 case 276: /* trigger_event ::= DELETE|INSERT */
105827 case 277: /* trigger_event ::= UPDATE */ yytestcase(yyruleno==277);
105828 {yygotominor.yy90.a = yymsp[0].major; yygotominor.yy90.b = 0;}
105829 break;
105830 case 278: /* trigger_event ::= UPDATE OF inscollist */
105831 {yygotominor.yy90.a = TK_UPDATE; yygotominor.yy90.b = yymsp[0].minor.yy384;}
105832 break;
105833 case 281: /* when_clause ::= */
105834 case 303: /* key_opt ::= */ yytestcase(yyruleno==303);
105835 { yygotominor.yy314 = 0; }
105836 break;
105837 case 282: /* when_clause ::= WHEN expr */
105838 case 304: /* key_opt ::= KEY expr */ yytestcase(yyruleno==304);
105839 { yygotominor.yy314 = yymsp[0].minor.yy118.pExpr; }
105840 break;
105841 case 283: /* trigger_cmd_list ::= trigger_cmd_list trigger_cmd SEMI */
105843 assert( yymsp[-2].minor.yy203!=0 );
105844 yymsp[-2].minor.yy203->pLast->pNext = yymsp[-1].minor.yy203;
105845 yymsp[-2].minor.yy203->pLast = yymsp[-1].minor.yy203;
105846 yygotominor.yy203 = yymsp[-2].minor.yy203;
105848 break;
105849 case 284: /* trigger_cmd_list ::= trigger_cmd SEMI */
105851 assert( yymsp[-1].minor.yy203!=0 );
105852 yymsp[-1].minor.yy203->pLast = yymsp[-1].minor.yy203;
105853 yygotominor.yy203 = yymsp[-1].minor.yy203;
105855 break;
105856 case 286: /* trnm ::= nm DOT nm */
105858 yygotominor.yy0 = yymsp[0].minor.yy0;
105859 sqlite3ErrorMsg(pParse,
105860 "qualified table names are not allowed on INSERT, UPDATE, and DELETE "
105861 "statements within triggers");
105863 break;
105864 case 288: /* tridxby ::= INDEXED BY nm */
105866 sqlite3ErrorMsg(pParse,
105867 "the INDEXED BY clause is not allowed on UPDATE or DELETE statements "
105868 "within triggers");
105870 break;
105871 case 289: /* tridxby ::= NOT INDEXED */
105873 sqlite3ErrorMsg(pParse,
105874 "the NOT INDEXED clause is not allowed on UPDATE or DELETE statements "
105875 "within triggers");
105877 break;
105878 case 290: /* trigger_cmd ::= UPDATE orconf trnm tridxby SET setlist where_opt */
105879 { yygotominor.yy203 = sqlite3TriggerUpdateStep(pParse->db, &yymsp[-4].minor.yy0, yymsp[-1].minor.yy322, yymsp[0].minor.yy314, yymsp[-5].minor.yy210); }
105880 break;
105881 case 291: /* trigger_cmd ::= insert_cmd INTO trnm inscollist_opt VALUES LP itemlist RP */
105882 {yygotominor.yy203 = sqlite3TriggerInsertStep(pParse->db, &yymsp[-5].minor.yy0, yymsp[-4].minor.yy384, yymsp[-1].minor.yy322, 0, yymsp[-7].minor.yy210);}
105883 break;
105884 case 292: /* trigger_cmd ::= insert_cmd INTO trnm inscollist_opt select */
105885 {yygotominor.yy203 = sqlite3TriggerInsertStep(pParse->db, &yymsp[-2].minor.yy0, yymsp[-1].minor.yy384, 0, yymsp[0].minor.yy387, yymsp[-4].minor.yy210);}
105886 break;
105887 case 293: /* trigger_cmd ::= DELETE FROM trnm tridxby where_opt */
105888 {yygotominor.yy203 = sqlite3TriggerDeleteStep(pParse->db, &yymsp[-2].minor.yy0, yymsp[0].minor.yy314);}
105889 break;
105890 case 294: /* trigger_cmd ::= select */
105891 {yygotominor.yy203 = sqlite3TriggerSelectStep(pParse->db, yymsp[0].minor.yy387); }
105892 break;
105893 case 295: /* expr ::= RAISE LP IGNORE RP */
105895 yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_RAISE, 0, 0, 0);
105896 if( yygotominor.yy118.pExpr ){
105897 yygotominor.yy118.pExpr->affinity = OE_Ignore;
105899 yygotominor.yy118.zStart = yymsp[-3].minor.yy0.z;
105900 yygotominor.yy118.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
105902 break;
105903 case 296: /* expr ::= RAISE LP raisetype COMMA nm RP */
105905 yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_RAISE, 0, 0, &yymsp[-1].minor.yy0);
105906 if( yygotominor.yy118.pExpr ) {
105907 yygotominor.yy118.pExpr->affinity = (char)yymsp[-3].minor.yy4;
105909 yygotominor.yy118.zStart = yymsp[-5].minor.yy0.z;
105910 yygotominor.yy118.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
105912 break;
105913 case 297: /* raisetype ::= ROLLBACK */
105914 {yygotominor.yy4 = OE_Rollback;}
105915 break;
105916 case 299: /* raisetype ::= FAIL */
105917 {yygotominor.yy4 = OE_Fail;}
105918 break;
105919 case 300: /* cmd ::= DROP TRIGGER ifexists fullname */
105921 sqlite3DropTrigger(pParse,yymsp[0].minor.yy259,yymsp[-1].minor.yy4);
105923 break;
105924 case 301: /* cmd ::= ATTACH database_kw_opt expr AS expr key_opt */
105926 sqlite3Attach(pParse, yymsp[-3].minor.yy118.pExpr, yymsp[-1].minor.yy118.pExpr, yymsp[0].minor.yy314);
105928 break;
105929 case 302: /* cmd ::= DETACH database_kw_opt expr */
105931 sqlite3Detach(pParse, yymsp[0].minor.yy118.pExpr);
105933 break;
105934 case 307: /* cmd ::= REINDEX */
105935 {sqlite3Reindex(pParse, 0, 0);}
105936 break;
105937 case 308: /* cmd ::= REINDEX nm dbnm */
105938 {sqlite3Reindex(pParse, &yymsp[-1].minor.yy0, &yymsp[0].minor.yy0);}
105939 break;
105940 case 309: /* cmd ::= ANALYZE */
105941 {sqlite3Analyze(pParse, 0, 0);}
105942 break;
105943 case 310: /* cmd ::= ANALYZE nm dbnm */
105944 {sqlite3Analyze(pParse, &yymsp[-1].minor.yy0, &yymsp[0].minor.yy0);}
105945 break;
105946 case 311: /* cmd ::= ALTER TABLE fullname RENAME TO nm */
105948 sqlite3AlterRenameTable(pParse,yymsp[-3].minor.yy259,&yymsp[0].minor.yy0);
105950 break;
105951 case 312: /* cmd ::= ALTER TABLE add_column_fullname ADD kwcolumn_opt column */
105953 sqlite3AlterFinishAddColumn(pParse, &yymsp[0].minor.yy0);
105955 break;
105956 case 313: /* add_column_fullname ::= fullname */
105958 pParse->db->lookaside.bEnabled = 0;
105959 sqlite3AlterBeginAddColumn(pParse, yymsp[0].minor.yy259);
105961 break;
105962 case 316: /* cmd ::= create_vtab */
105963 {sqlite3VtabFinishParse(pParse,0);}
105964 break;
105965 case 317: /* cmd ::= create_vtab LP vtabarglist RP */
105966 {sqlite3VtabFinishParse(pParse,&yymsp[0].minor.yy0);}
105967 break;
105968 case 318: /* create_vtab ::= createkw VIRTUAL TABLE nm dbnm USING nm */
105970 sqlite3VtabBeginParse(pParse, &yymsp[-3].minor.yy0, &yymsp[-2].minor.yy0, &yymsp[0].minor.yy0);
105972 break;
105973 case 321: /* vtabarg ::= */
105974 {sqlite3VtabArgInit(pParse);}
105975 break;
105976 case 323: /* vtabargtoken ::= ANY */
105977 case 324: /* vtabargtoken ::= lp anylist RP */ yytestcase(yyruleno==324);
105978 case 325: /* lp ::= LP */ yytestcase(yyruleno==325);
105979 {sqlite3VtabArgExtend(pParse,&yymsp[0].minor.yy0);}
105980 break;
105981 default:
105982 /* (0) input ::= cmdlist */ yytestcase(yyruleno==0);
105983 /* (1) cmdlist ::= cmdlist ecmd */ yytestcase(yyruleno==1);
105984 /* (2) cmdlist ::= ecmd */ yytestcase(yyruleno==2);
105985 /* (3) ecmd ::= SEMI */ yytestcase(yyruleno==3);
105986 /* (4) ecmd ::= explain cmdx SEMI */ yytestcase(yyruleno==4);
105987 /* (10) trans_opt ::= */ yytestcase(yyruleno==10);
105988 /* (11) trans_opt ::= TRANSACTION */ yytestcase(yyruleno==11);
105989 /* (12) trans_opt ::= TRANSACTION nm */ yytestcase(yyruleno==12);
105990 /* (20) savepoint_opt ::= SAVEPOINT */ yytestcase(yyruleno==20);
105991 /* (21) savepoint_opt ::= */ yytestcase(yyruleno==21);
105992 /* (25) cmd ::= create_table create_table_args */ yytestcase(yyruleno==25);
105993 /* (34) columnlist ::= columnlist COMMA column */ yytestcase(yyruleno==34);
105994 /* (35) columnlist ::= column */ yytestcase(yyruleno==35);
105995 /* (44) type ::= */ yytestcase(yyruleno==44);
105996 /* (51) signed ::= plus_num */ yytestcase(yyruleno==51);
105997 /* (52) signed ::= minus_num */ yytestcase(yyruleno==52);
105998 /* (53) carglist ::= carglist carg */ yytestcase(yyruleno==53);
105999 /* (54) carglist ::= */ yytestcase(yyruleno==54);
106000 /* (55) carg ::= CONSTRAINT nm ccons */ yytestcase(yyruleno==55);
106001 /* (56) carg ::= ccons */ yytestcase(yyruleno==56);
106002 /* (62) ccons ::= NULL onconf */ yytestcase(yyruleno==62);
106003 /* (90) conslist ::= conslist COMMA tcons */ yytestcase(yyruleno==90);
106004 /* (91) conslist ::= conslist tcons */ yytestcase(yyruleno==91);
106005 /* (92) conslist ::= tcons */ yytestcase(yyruleno==92);
106006 /* (93) tcons ::= CONSTRAINT nm */ yytestcase(yyruleno==93);
106007 /* (268) plus_opt ::= PLUS */ yytestcase(yyruleno==268);
106008 /* (269) plus_opt ::= */ yytestcase(yyruleno==269);
106009 /* (279) foreach_clause ::= */ yytestcase(yyruleno==279);
106010 /* (280) foreach_clause ::= FOR EACH ROW */ yytestcase(yyruleno==280);
106011 /* (287) tridxby ::= */ yytestcase(yyruleno==287);
106012 /* (305) database_kw_opt ::= DATABASE */ yytestcase(yyruleno==305);
106013 /* (306) database_kw_opt ::= */ yytestcase(yyruleno==306);
106014 /* (314) kwcolumn_opt ::= */ yytestcase(yyruleno==314);
106015 /* (315) kwcolumn_opt ::= COLUMNKW */ yytestcase(yyruleno==315);
106016 /* (319) vtabarglist ::= vtabarg */ yytestcase(yyruleno==319);
106017 /* (320) vtabarglist ::= vtabarglist COMMA vtabarg */ yytestcase(yyruleno==320);
106018 /* (322) vtabarg ::= vtabarg vtabargtoken */ yytestcase(yyruleno==322);
106019 /* (326) anylist ::= */ yytestcase(yyruleno==326);
106020 /* (327) anylist ::= anylist LP anylist RP */ yytestcase(yyruleno==327);
106021 /* (328) anylist ::= anylist ANY */ yytestcase(yyruleno==328);
106022 break;
106024 yygoto = yyRuleInfo[yyruleno].lhs;
106025 yysize = yyRuleInfo[yyruleno].nrhs;
106026 yypParser->yyidx -= yysize;
106027 yyact = yy_find_reduce_action(yymsp[-yysize].stateno,(YYCODETYPE)yygoto);
106028 if( yyact < YYNSTATE ){
106029 #ifdef NDEBUG
106030 /* If we are not debugging and the reduce action popped at least
106031 ** one element off the stack, then we can push the new element back
106032 ** onto the stack here, and skip the stack overflow test in yy_shift().
106033 ** That gives a significant speed improvement. */
106034 if( yysize ){
106035 yypParser->yyidx++;
106036 yymsp -= yysize-1;
106037 yymsp->stateno = (YYACTIONTYPE)yyact;
106038 yymsp->major = (YYCODETYPE)yygoto;
106039 yymsp->minor = yygotominor;
106040 }else
106041 #endif
106043 yy_shift(yypParser,yyact,yygoto,&yygotominor);
106045 }else{
106046 assert( yyact == YYNSTATE + YYNRULE + 1 );
106047 yy_accept(yypParser);
106052 ** The following code executes when the parse fails
106054 #ifndef YYNOERRORRECOVERY
106055 static void yy_parse_failed(
106056 yyParser *yypParser /* The parser */
106058 sqlite3ParserARG_FETCH;
106059 #ifndef NDEBUG
106060 if( yyTraceFILE ){
106061 fprintf(yyTraceFILE,"%sFail!\n",yyTracePrompt);
106063 #endif
106064 while( yypParser->yyidx>=0 ) yy_pop_parser_stack(yypParser);
106065 /* Here code is inserted which will be executed whenever the
106066 ** parser fails */
106067 sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
106069 #endif /* YYNOERRORRECOVERY */
106072 ** The following code executes when a syntax error first occurs.
106074 static void yy_syntax_error(
106075 yyParser *yypParser, /* The parser */
106076 int yymajor, /* The major type of the error token */
106077 YYMINORTYPE yyminor /* The minor type of the error token */
106079 sqlite3ParserARG_FETCH;
106080 #define TOKEN (yyminor.yy0)
106082 UNUSED_PARAMETER(yymajor); /* Silence some compiler warnings */
106083 assert( TOKEN.z[0] ); /* The tokenizer always gives us a token */
106084 sqlite3ErrorMsg(pParse, "near \"%T\": syntax error", &TOKEN);
106085 pParse->parseError = 1;
106086 sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
106090 ** The following is executed when the parser accepts
106092 static void yy_accept(
106093 yyParser *yypParser /* The parser */
106095 sqlite3ParserARG_FETCH;
106096 #ifndef NDEBUG
106097 if( yyTraceFILE ){
106098 fprintf(yyTraceFILE,"%sAccept!\n",yyTracePrompt);
106100 #endif
106101 while( yypParser->yyidx>=0 ) yy_pop_parser_stack(yypParser);
106102 /* Here code is inserted which will be executed whenever the
106103 ** parser accepts */
106104 sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
106107 /* The main parser program.
106108 ** The first argument is a pointer to a structure obtained from
106109 ** "sqlite3ParserAlloc" which describes the current state of the parser.
106110 ** The second argument is the major token number. The third is
106111 ** the minor token. The fourth optional argument is whatever the
106112 ** user wants (and specified in the grammar) and is available for
106113 ** use by the action routines.
106115 ** Inputs:
106116 ** <ul>
106117 ** <li> A pointer to the parser (an opaque structure.)
106118 ** <li> The major token number.
106119 ** <li> The minor token number.
106120 ** <li> An option argument of a grammar-specified type.
106121 ** </ul>
106123 ** Outputs:
106124 ** None.
106126 SQLITE_PRIVATE void sqlite3Parser(
106127 void *yyp, /* The parser */
106128 int yymajor, /* The major token code number */
106129 sqlite3ParserTOKENTYPE yyminor /* The value for the token */
106130 sqlite3ParserARG_PDECL /* Optional %extra_argument parameter */
106132 YYMINORTYPE yyminorunion;
106133 int yyact; /* The parser action. */
106134 int yyendofinput; /* True if we are at the end of input */
106135 #ifdef YYERRORSYMBOL
106136 int yyerrorhit = 0; /* True if yymajor has invoked an error */
106137 #endif
106138 yyParser *yypParser; /* The parser */
106140 /* (re)initialize the parser, if necessary */
106141 yypParser = (yyParser*)yyp;
106142 if( yypParser->yyidx<0 ){
106143 #if YYSTACKDEPTH<=0
106144 if( yypParser->yystksz <=0 ){
106145 /*memset(&yyminorunion, 0, sizeof(yyminorunion));*/
106146 yyminorunion = yyzerominor;
106147 yyStackOverflow(yypParser, &yyminorunion);
106148 return;
106150 #endif
106151 yypParser->yyidx = 0;
106152 yypParser->yyerrcnt = -1;
106153 yypParser->yystack[0].stateno = 0;
106154 yypParser->yystack[0].major = 0;
106156 yyminorunion.yy0 = yyminor;
106157 yyendofinput = (yymajor==0);
106158 sqlite3ParserARG_STORE;
106160 #ifndef NDEBUG
106161 if( yyTraceFILE ){
106162 fprintf(yyTraceFILE,"%sInput %s\n",yyTracePrompt,yyTokenName[yymajor]);
106164 #endif
106167 yyact = yy_find_shift_action(yypParser,(YYCODETYPE)yymajor);
106168 if( yyact<YYNSTATE ){
106169 assert( !yyendofinput ); /* Impossible to shift the $ token */
106170 yy_shift(yypParser,yyact,yymajor,&yyminorunion);
106171 yypParser->yyerrcnt--;
106172 yymajor = YYNOCODE;
106173 }else if( yyact < YYNSTATE + YYNRULE ){
106174 yy_reduce(yypParser,yyact-YYNSTATE);
106175 }else{
106176 assert( yyact == YY_ERROR_ACTION );
106177 #ifdef YYERRORSYMBOL
106178 int yymx;
106179 #endif
106180 #ifndef NDEBUG
106181 if( yyTraceFILE ){
106182 fprintf(yyTraceFILE,"%sSyntax Error!\n",yyTracePrompt);
106184 #endif
106185 #ifdef YYERRORSYMBOL
106186 /* A syntax error has occurred.
106187 ** The response to an error depends upon whether or not the
106188 ** grammar defines an error token "ERROR".
106190 ** This is what we do if the grammar does define ERROR:
106192 ** * Call the %syntax_error function.
106194 ** * Begin popping the stack until we enter a state where
106195 ** it is legal to shift the error symbol, then shift
106196 ** the error symbol.
106198 ** * Set the error count to three.
106200 ** * Begin accepting and shifting new tokens. No new error
106201 ** processing will occur until three tokens have been
106202 ** shifted successfully.
106205 if( yypParser->yyerrcnt<0 ){
106206 yy_syntax_error(yypParser,yymajor,yyminorunion);
106208 yymx = yypParser->yystack[yypParser->yyidx].major;
106209 if( yymx==YYERRORSYMBOL || yyerrorhit ){
106210 #ifndef NDEBUG
106211 if( yyTraceFILE ){
106212 fprintf(yyTraceFILE,"%sDiscard input token %s\n",
106213 yyTracePrompt,yyTokenName[yymajor]);
106215 #endif
106216 yy_destructor(yypParser, (YYCODETYPE)yymajor,&yyminorunion);
106217 yymajor = YYNOCODE;
106218 }else{
106219 while(
106220 yypParser->yyidx >= 0 &&
106221 yymx != YYERRORSYMBOL &&
106222 (yyact = yy_find_reduce_action(
106223 yypParser->yystack[yypParser->yyidx].stateno,
106224 YYERRORSYMBOL)) >= YYNSTATE
106226 yy_pop_parser_stack(yypParser);
106228 if( yypParser->yyidx < 0 || yymajor==0 ){
106229 yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion);
106230 yy_parse_failed(yypParser);
106231 yymajor = YYNOCODE;
106232 }else if( yymx!=YYERRORSYMBOL ){
106233 YYMINORTYPE u2;
106234 u2.YYERRSYMDT = 0;
106235 yy_shift(yypParser,yyact,YYERRORSYMBOL,&u2);
106238 yypParser->yyerrcnt = 3;
106239 yyerrorhit = 1;
106240 #elif defined(YYNOERRORRECOVERY)
106241 /* If the YYNOERRORRECOVERY macro is defined, then do not attempt to
106242 ** do any kind of error recovery. Instead, simply invoke the syntax
106243 ** error routine and continue going as if nothing had happened.
106245 ** Applications can set this macro (for example inside %include) if
106246 ** they intend to abandon the parse upon the first syntax error seen.
106248 yy_syntax_error(yypParser,yymajor,yyminorunion);
106249 yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion);
106250 yymajor = YYNOCODE;
106252 #else /* YYERRORSYMBOL is not defined */
106253 /* This is what we do if the grammar does not define ERROR:
106255 ** * Report an error message, and throw away the input token.
106257 ** * If the input token is $, then fail the parse.
106259 ** As before, subsequent error messages are suppressed until
106260 ** three input tokens have been successfully shifted.
106262 if( yypParser->yyerrcnt<=0 ){
106263 yy_syntax_error(yypParser,yymajor,yyminorunion);
106265 yypParser->yyerrcnt = 3;
106266 yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion);
106267 if( yyendofinput ){
106268 yy_parse_failed(yypParser);
106270 yymajor = YYNOCODE;
106271 #endif
106273 }while( yymajor!=YYNOCODE && yypParser->yyidx>=0 );
106274 return;
106277 /************** End of parse.c ***********************************************/
106278 /************** Begin file tokenize.c ****************************************/
106280 ** 2001 September 15
106282 ** The author disclaims copyright to this source code. In place of
106283 ** a legal notice, here is a blessing:
106285 ** May you do good and not evil.
106286 ** May you find forgiveness for yourself and forgive others.
106287 ** May you share freely, never taking more than you give.
106289 *************************************************************************
106290 ** An tokenizer for SQL
106292 ** This file contains C code that splits an SQL input string up into
106293 ** individual tokens and sends those tokens one-by-one over to the
106294 ** parser for analysis.
106298 ** The charMap() macro maps alphabetic characters into their
106299 ** lower-case ASCII equivalent. On ASCII machines, this is just
106300 ** an upper-to-lower case map. On EBCDIC machines we also need
106301 ** to adjust the encoding. Only alphabetic characters and underscores
106302 ** need to be translated.
106304 #ifdef SQLITE_ASCII
106305 # define charMap(X) sqlite3UpperToLower[(unsigned char)X]
106306 #endif
106307 #ifdef SQLITE_EBCDIC
106308 # define charMap(X) ebcdicToAscii[(unsigned char)X]
106309 const unsigned char ebcdicToAscii[] = {
106310 /* 0 1 2 3 4 5 6 7 8 9 A B C D E F */
106311 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0x */
106312 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 1x */
106313 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 2x */
106314 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 3x */
106315 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 4x */
106316 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 5x */
106317 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 95, 0, 0, /* 6x */
106318 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 7x */
106319 0, 97, 98, 99,100,101,102,103,104,105, 0, 0, 0, 0, 0, 0, /* 8x */
106320 0,106,107,108,109,110,111,112,113,114, 0, 0, 0, 0, 0, 0, /* 9x */
106321 0, 0,115,116,117,118,119,120,121,122, 0, 0, 0, 0, 0, 0, /* Ax */
106322 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Bx */
106323 0, 97, 98, 99,100,101,102,103,104,105, 0, 0, 0, 0, 0, 0, /* Cx */
106324 0,106,107,108,109,110,111,112,113,114, 0, 0, 0, 0, 0, 0, /* Dx */
106325 0, 0,115,116,117,118,119,120,121,122, 0, 0, 0, 0, 0, 0, /* Ex */
106326 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Fx */
106328 #endif
106331 ** The sqlite3KeywordCode function looks up an identifier to determine if
106332 ** it is a keyword. If it is a keyword, the token code of that keyword is
106333 ** returned. If the input is not a keyword, TK_ID is returned.
106335 ** The implementation of this routine was generated by a program,
106336 ** mkkeywordhash.h, located in the tool subdirectory of the distribution.
106337 ** The output of the mkkeywordhash.c program is written into a file
106338 ** named keywordhash.h and then included into this source file by
106339 ** the #include below.
106341 /************** Include keywordhash.h in the middle of tokenize.c ************/
106342 /************** Begin file keywordhash.h *************************************/
106343 /***** This file contains automatically generated code ******
106345 ** The code in this file has been automatically generated by
106347 ** sqlite/tool/mkkeywordhash.c
106349 ** The code in this file implements a function that determines whether
106350 ** or not a given identifier is really an SQL keyword. The same thing
106351 ** might be implemented more directly using a hand-written hash table.
106352 ** But by using this automatically generated code, the size of the code
106353 ** is substantially reduced. This is important for embedded applications
106354 ** on platforms with limited memory.
106356 /* Hash score: 175 */
106357 static int keywordCode(const char *z, int n){
106358 /* zText[] encodes 811 bytes of keywords in 541 bytes */
106359 /* REINDEXEDESCAPEACHECKEYBEFOREIGNOREGEXPLAINSTEADDATABASELECT */
106360 /* ABLEFTHENDEFERRABLELSEXCEPTRANSACTIONATURALTERAISEXCLUSIVE */
106361 /* XISTSAVEPOINTERSECTRIGGEREFERENCESCONSTRAINTOFFSETEMPORARY */
106362 /* UNIQUERYATTACHAVINGROUPDATEBEGINNERELEASEBETWEENOTNULLIKE */
106363 /* CASCADELETECASECOLLATECREATECURRENT_DATEDETACHIMMEDIATEJOIN */
106364 /* SERTMATCHPLANALYZEPRAGMABORTVALUESVIRTUALIMITWHENWHERENAME */
106365 /* AFTEREPLACEANDEFAULTAUTOINCREMENTCASTCOLUMNCOMMITCONFLICTCROSS */
106366 /* CURRENT_TIMESTAMPRIMARYDEFERREDISTINCTDROPFAILFROMFULLGLOBYIF */
106367 /* ISNULLORDERESTRICTOUTERIGHTROLLBACKROWUNIONUSINGVACUUMVIEW */
106368 /* INITIALLY */
106369 static const char zText[540] = {
106370 'R','E','I','N','D','E','X','E','D','E','S','C','A','P','E','A','C','H',
106371 'E','C','K','E','Y','B','E','F','O','R','E','I','G','N','O','R','E','G',
106372 'E','X','P','L','A','I','N','S','T','E','A','D','D','A','T','A','B','A',
106373 'S','E','L','E','C','T','A','B','L','E','F','T','H','E','N','D','E','F',
106374 'E','R','R','A','B','L','E','L','S','E','X','C','E','P','T','R','A','N',
106375 'S','A','C','T','I','O','N','A','T','U','R','A','L','T','E','R','A','I',
106376 'S','E','X','C','L','U','S','I','V','E','X','I','S','T','S','A','V','E',
106377 'P','O','I','N','T','E','R','S','E','C','T','R','I','G','G','E','R','E',
106378 'F','E','R','E','N','C','E','S','C','O','N','S','T','R','A','I','N','T',
106379 'O','F','F','S','E','T','E','M','P','O','R','A','R','Y','U','N','I','Q',
106380 'U','E','R','Y','A','T','T','A','C','H','A','V','I','N','G','R','O','U',
106381 'P','D','A','T','E','B','E','G','I','N','N','E','R','E','L','E','A','S',
106382 'E','B','E','T','W','E','E','N','O','T','N','U','L','L','I','K','E','C',
106383 'A','S','C','A','D','E','L','E','T','E','C','A','S','E','C','O','L','L',
106384 'A','T','E','C','R','E','A','T','E','C','U','R','R','E','N','T','_','D',
106385 'A','T','E','D','E','T','A','C','H','I','M','M','E','D','I','A','T','E',
106386 'J','O','I','N','S','E','R','T','M','A','T','C','H','P','L','A','N','A',
106387 'L','Y','Z','E','P','R','A','G','M','A','B','O','R','T','V','A','L','U',
106388 'E','S','V','I','R','T','U','A','L','I','M','I','T','W','H','E','N','W',
106389 'H','E','R','E','N','A','M','E','A','F','T','E','R','E','P','L','A','C',
106390 'E','A','N','D','E','F','A','U','L','T','A','U','T','O','I','N','C','R',
106391 'E','M','E','N','T','C','A','S','T','C','O','L','U','M','N','C','O','M',
106392 'M','I','T','C','O','N','F','L','I','C','T','C','R','O','S','S','C','U',
106393 'R','R','E','N','T','_','T','I','M','E','S','T','A','M','P','R','I','M',
106394 'A','R','Y','D','E','F','E','R','R','E','D','I','S','T','I','N','C','T',
106395 'D','R','O','P','F','A','I','L','F','R','O','M','F','U','L','L','G','L',
106396 'O','B','Y','I','F','I','S','N','U','L','L','O','R','D','E','R','E','S',
106397 'T','R','I','C','T','O','U','T','E','R','I','G','H','T','R','O','L','L',
106398 'B','A','C','K','R','O','W','U','N','I','O','N','U','S','I','N','G','V',
106399 'A','C','U','U','M','V','I','E','W','I','N','I','T','I','A','L','L','Y',
106401 static const unsigned char aHash[127] = {
106402 72, 101, 114, 70, 0, 45, 0, 0, 78, 0, 73, 0, 0,
106403 42, 12, 74, 15, 0, 113, 81, 50, 108, 0, 19, 0, 0,
106404 118, 0, 116, 111, 0, 22, 89, 0, 9, 0, 0, 66, 67,
106405 0, 65, 6, 0, 48, 86, 98, 0, 115, 97, 0, 0, 44,
106406 0, 99, 24, 0, 17, 0, 119, 49, 23, 0, 5, 106, 25,
106407 92, 0, 0, 121, 102, 56, 120, 53, 28, 51, 0, 87, 0,
106408 96, 26, 0, 95, 0, 0, 0, 91, 88, 93, 84, 105, 14,
106409 39, 104, 0, 77, 0, 18, 85, 107, 32, 0, 117, 76, 109,
106410 58, 46, 80, 0, 0, 90, 40, 0, 112, 0, 36, 0, 0,
106411 29, 0, 82, 59, 60, 0, 20, 57, 0, 52,
106413 static const unsigned char aNext[121] = {
106414 0, 0, 0, 0, 4, 0, 0, 0, 0, 0, 0, 0, 0,
106415 0, 2, 0, 0, 0, 0, 0, 0, 13, 0, 0, 0, 0,
106416 0, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
106417 0, 0, 0, 0, 33, 0, 21, 0, 0, 0, 43, 3, 47,
106418 0, 0, 0, 0, 30, 0, 54, 0, 38, 0, 0, 0, 1,
106419 62, 0, 0, 63, 0, 41, 0, 0, 0, 0, 0, 0, 0,
106420 61, 0, 0, 0, 0, 31, 55, 16, 34, 10, 0, 0, 0,
106421 0, 0, 0, 0, 11, 68, 75, 0, 8, 0, 100, 94, 0,
106422 103, 0, 83, 0, 71, 0, 0, 110, 27, 37, 69, 79, 0,
106423 35, 64, 0, 0,
106425 static const unsigned char aLen[121] = {
106426 7, 7, 5, 4, 6, 4, 5, 3, 6, 7, 3, 6, 6,
106427 7, 7, 3, 8, 2, 6, 5, 4, 4, 3, 10, 4, 6,
106428 11, 6, 2, 7, 5, 5, 9, 6, 9, 9, 7, 10, 10,
106429 4, 6, 2, 3, 9, 4, 2, 6, 5, 6, 6, 5, 6,
106430 5, 5, 7, 7, 7, 3, 2, 4, 4, 7, 3, 6, 4,
106431 7, 6, 12, 6, 9, 4, 6, 5, 4, 7, 6, 5, 6,
106432 7, 5, 4, 5, 6, 5, 7, 3, 7, 13, 2, 2, 4,
106433 6, 6, 8, 5, 17, 12, 7, 8, 8, 2, 4, 4, 4,
106434 4, 4, 2, 2, 6, 5, 8, 5, 5, 8, 3, 5, 5,
106435 6, 4, 9, 3,
106437 static const unsigned short int aOffset[121] = {
106438 0, 2, 2, 8, 9, 14, 16, 20, 23, 25, 25, 29, 33,
106439 36, 41, 46, 48, 53, 54, 59, 62, 65, 67, 69, 78, 81,
106440 86, 91, 95, 96, 101, 105, 109, 117, 122, 128, 136, 142, 152,
106441 159, 162, 162, 165, 167, 167, 171, 176, 179, 184, 189, 194, 197,
106442 203, 206, 210, 217, 223, 223, 223, 226, 229, 233, 234, 238, 244,
106443 248, 255, 261, 273, 279, 288, 290, 296, 301, 303, 310, 315, 320,
106444 326, 332, 337, 341, 344, 350, 354, 361, 363, 370, 372, 374, 383,
106445 387, 393, 399, 407, 412, 412, 428, 435, 442, 443, 450, 454, 458,
106446 462, 466, 469, 471, 473, 479, 483, 491, 495, 500, 508, 511, 516,
106447 521, 527, 531, 536,
106449 static const unsigned char aCode[121] = {
106450 TK_REINDEX, TK_INDEXED, TK_INDEX, TK_DESC, TK_ESCAPE,
106451 TK_EACH, TK_CHECK, TK_KEY, TK_BEFORE, TK_FOREIGN,
106452 TK_FOR, TK_IGNORE, TK_LIKE_KW, TK_EXPLAIN, TK_INSTEAD,
106453 TK_ADD, TK_DATABASE, TK_AS, TK_SELECT, TK_TABLE,
106454 TK_JOIN_KW, TK_THEN, TK_END, TK_DEFERRABLE, TK_ELSE,
106455 TK_EXCEPT, TK_TRANSACTION,TK_ACTION, TK_ON, TK_JOIN_KW,
106456 TK_ALTER, TK_RAISE, TK_EXCLUSIVE, TK_EXISTS, TK_SAVEPOINT,
106457 TK_INTERSECT, TK_TRIGGER, TK_REFERENCES, TK_CONSTRAINT, TK_INTO,
106458 TK_OFFSET, TK_OF, TK_SET, TK_TEMP, TK_TEMP,
106459 TK_OR, TK_UNIQUE, TK_QUERY, TK_ATTACH, TK_HAVING,
106460 TK_GROUP, TK_UPDATE, TK_BEGIN, TK_JOIN_KW, TK_RELEASE,
106461 TK_BETWEEN, TK_NOTNULL, TK_NOT, TK_NO, TK_NULL,
106462 TK_LIKE_KW, TK_CASCADE, TK_ASC, TK_DELETE, TK_CASE,
106463 TK_COLLATE, TK_CREATE, TK_CTIME_KW, TK_DETACH, TK_IMMEDIATE,
106464 TK_JOIN, TK_INSERT, TK_MATCH, TK_PLAN, TK_ANALYZE,
106465 TK_PRAGMA, TK_ABORT, TK_VALUES, TK_VIRTUAL, TK_LIMIT,
106466 TK_WHEN, TK_WHERE, TK_RENAME, TK_AFTER, TK_REPLACE,
106467 TK_AND, TK_DEFAULT, TK_AUTOINCR, TK_TO, TK_IN,
106468 TK_CAST, TK_COLUMNKW, TK_COMMIT, TK_CONFLICT, TK_JOIN_KW,
106469 TK_CTIME_KW, TK_CTIME_KW, TK_PRIMARY, TK_DEFERRED, TK_DISTINCT,
106470 TK_IS, TK_DROP, TK_FAIL, TK_FROM, TK_JOIN_KW,
106471 TK_LIKE_KW, TK_BY, TK_IF, TK_ISNULL, TK_ORDER,
106472 TK_RESTRICT, TK_JOIN_KW, TK_JOIN_KW, TK_ROLLBACK, TK_ROW,
106473 TK_UNION, TK_USING, TK_VACUUM, TK_VIEW, TK_INITIALLY,
106474 TK_ALL,
106476 int h, i;
106477 if( n<2 ) return TK_ID;
106478 h = ((charMap(z[0])*4) ^
106479 (charMap(z[n-1])*3) ^
106480 n) % 127;
106481 for(i=((int)aHash[h])-1; i>=0; i=((int)aNext[i])-1){
106482 if( aLen[i]==n && sqlite3StrNICmp(&zText[aOffset[i]],z,n)==0 ){
106483 testcase( i==0 ); /* REINDEX */
106484 testcase( i==1 ); /* INDEXED */
106485 testcase( i==2 ); /* INDEX */
106486 testcase( i==3 ); /* DESC */
106487 testcase( i==4 ); /* ESCAPE */
106488 testcase( i==5 ); /* EACH */
106489 testcase( i==6 ); /* CHECK */
106490 testcase( i==7 ); /* KEY */
106491 testcase( i==8 ); /* BEFORE */
106492 testcase( i==9 ); /* FOREIGN */
106493 testcase( i==10 ); /* FOR */
106494 testcase( i==11 ); /* IGNORE */
106495 testcase( i==12 ); /* REGEXP */
106496 testcase( i==13 ); /* EXPLAIN */
106497 testcase( i==14 ); /* INSTEAD */
106498 testcase( i==15 ); /* ADD */
106499 testcase( i==16 ); /* DATABASE */
106500 testcase( i==17 ); /* AS */
106501 testcase( i==18 ); /* SELECT */
106502 testcase( i==19 ); /* TABLE */
106503 testcase( i==20 ); /* LEFT */
106504 testcase( i==21 ); /* THEN */
106505 testcase( i==22 ); /* END */
106506 testcase( i==23 ); /* DEFERRABLE */
106507 testcase( i==24 ); /* ELSE */
106508 testcase( i==25 ); /* EXCEPT */
106509 testcase( i==26 ); /* TRANSACTION */
106510 testcase( i==27 ); /* ACTION */
106511 testcase( i==28 ); /* ON */
106512 testcase( i==29 ); /* NATURAL */
106513 testcase( i==30 ); /* ALTER */
106514 testcase( i==31 ); /* RAISE */
106515 testcase( i==32 ); /* EXCLUSIVE */
106516 testcase( i==33 ); /* EXISTS */
106517 testcase( i==34 ); /* SAVEPOINT */
106518 testcase( i==35 ); /* INTERSECT */
106519 testcase( i==36 ); /* TRIGGER */
106520 testcase( i==37 ); /* REFERENCES */
106521 testcase( i==38 ); /* CONSTRAINT */
106522 testcase( i==39 ); /* INTO */
106523 testcase( i==40 ); /* OFFSET */
106524 testcase( i==41 ); /* OF */
106525 testcase( i==42 ); /* SET */
106526 testcase( i==43 ); /* TEMPORARY */
106527 testcase( i==44 ); /* TEMP */
106528 testcase( i==45 ); /* OR */
106529 testcase( i==46 ); /* UNIQUE */
106530 testcase( i==47 ); /* QUERY */
106531 testcase( i==48 ); /* ATTACH */
106532 testcase( i==49 ); /* HAVING */
106533 testcase( i==50 ); /* GROUP */
106534 testcase( i==51 ); /* UPDATE */
106535 testcase( i==52 ); /* BEGIN */
106536 testcase( i==53 ); /* INNER */
106537 testcase( i==54 ); /* RELEASE */
106538 testcase( i==55 ); /* BETWEEN */
106539 testcase( i==56 ); /* NOTNULL */
106540 testcase( i==57 ); /* NOT */
106541 testcase( i==58 ); /* NO */
106542 testcase( i==59 ); /* NULL */
106543 testcase( i==60 ); /* LIKE */
106544 testcase( i==61 ); /* CASCADE */
106545 testcase( i==62 ); /* ASC */
106546 testcase( i==63 ); /* DELETE */
106547 testcase( i==64 ); /* CASE */
106548 testcase( i==65 ); /* COLLATE */
106549 testcase( i==66 ); /* CREATE */
106550 testcase( i==67 ); /* CURRENT_DATE */
106551 testcase( i==68 ); /* DETACH */
106552 testcase( i==69 ); /* IMMEDIATE */
106553 testcase( i==70 ); /* JOIN */
106554 testcase( i==71 ); /* INSERT */
106555 testcase( i==72 ); /* MATCH */
106556 testcase( i==73 ); /* PLAN */
106557 testcase( i==74 ); /* ANALYZE */
106558 testcase( i==75 ); /* PRAGMA */
106559 testcase( i==76 ); /* ABORT */
106560 testcase( i==77 ); /* VALUES */
106561 testcase( i==78 ); /* VIRTUAL */
106562 testcase( i==79 ); /* LIMIT */
106563 testcase( i==80 ); /* WHEN */
106564 testcase( i==81 ); /* WHERE */
106565 testcase( i==82 ); /* RENAME */
106566 testcase( i==83 ); /* AFTER */
106567 testcase( i==84 ); /* REPLACE */
106568 testcase( i==85 ); /* AND */
106569 testcase( i==86 ); /* DEFAULT */
106570 testcase( i==87 ); /* AUTOINCREMENT */
106571 testcase( i==88 ); /* TO */
106572 testcase( i==89 ); /* IN */
106573 testcase( i==90 ); /* CAST */
106574 testcase( i==91 ); /* COLUMN */
106575 testcase( i==92 ); /* COMMIT */
106576 testcase( i==93 ); /* CONFLICT */
106577 testcase( i==94 ); /* CROSS */
106578 testcase( i==95 ); /* CURRENT_TIMESTAMP */
106579 testcase( i==96 ); /* CURRENT_TIME */
106580 testcase( i==97 ); /* PRIMARY */
106581 testcase( i==98 ); /* DEFERRED */
106582 testcase( i==99 ); /* DISTINCT */
106583 testcase( i==100 ); /* IS */
106584 testcase( i==101 ); /* DROP */
106585 testcase( i==102 ); /* FAIL */
106586 testcase( i==103 ); /* FROM */
106587 testcase( i==104 ); /* FULL */
106588 testcase( i==105 ); /* GLOB */
106589 testcase( i==106 ); /* BY */
106590 testcase( i==107 ); /* IF */
106591 testcase( i==108 ); /* ISNULL */
106592 testcase( i==109 ); /* ORDER */
106593 testcase( i==110 ); /* RESTRICT */
106594 testcase( i==111 ); /* OUTER */
106595 testcase( i==112 ); /* RIGHT */
106596 testcase( i==113 ); /* ROLLBACK */
106597 testcase( i==114 ); /* ROW */
106598 testcase( i==115 ); /* UNION */
106599 testcase( i==116 ); /* USING */
106600 testcase( i==117 ); /* VACUUM */
106601 testcase( i==118 ); /* VIEW */
106602 testcase( i==119 ); /* INITIALLY */
106603 testcase( i==120 ); /* ALL */
106604 return aCode[i];
106607 return TK_ID;
106609 SQLITE_PRIVATE int sqlite3KeywordCode(const unsigned char *z, int n){
106610 return keywordCode((char*)z, n);
106612 #define SQLITE_N_KEYWORD 121
106614 /************** End of keywordhash.h *****************************************/
106615 /************** Continuing where we left off in tokenize.c *******************/
106619 ** If X is a character that can be used in an identifier then
106620 ** IdChar(X) will be true. Otherwise it is false.
106622 ** For ASCII, any character with the high-order bit set is
106623 ** allowed in an identifier. For 7-bit characters,
106624 ** sqlite3IsIdChar[X] must be 1.
106626 ** For EBCDIC, the rules are more complex but have the same
106627 ** end result.
106629 ** Ticket #1066. the SQL standard does not allow '$' in the
106630 ** middle of identfiers. But many SQL implementations do.
106631 ** SQLite will allow '$' in identifiers for compatibility.
106632 ** But the feature is undocumented.
106634 #ifdef SQLITE_ASCII
106635 #define IdChar(C) ((sqlite3CtypeMap[(unsigned char)C]&0x46)!=0)
106636 #endif
106637 #ifdef SQLITE_EBCDIC
106638 SQLITE_PRIVATE const char sqlite3IsEbcdicIdChar[] = {
106639 /* x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 xA xB xC xD xE xF */
106640 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, /* 4x */
106641 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 0, 0, 0, /* 5x */
106642 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0, /* 6x */
106643 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, /* 7x */
106644 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 0, /* 8x */
106645 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 0, 1, 0, /* 9x */
106646 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 0, /* Ax */
106647 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Bx */
106648 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, /* Cx */
106649 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, /* Dx */
106650 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, /* Ex */
106651 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 0, /* Fx */
106653 #define IdChar(C) (((c=C)>=0x42 && sqlite3IsEbcdicIdChar[c-0x40]))
106654 #endif
106658 ** Return the length of the token that begins at z[0].
106659 ** Store the token type in *tokenType before returning.
106661 SQLITE_PRIVATE int sqlite3GetToken(const unsigned char *z, int *tokenType){
106662 int i, c;
106663 switch( *z ){
106664 case ' ': case '\t': case '\n': case '\f': case '\r': {
106665 testcase( z[0]==' ' );
106666 testcase( z[0]=='\t' );
106667 testcase( z[0]=='\n' );
106668 testcase( z[0]=='\f' );
106669 testcase( z[0]=='\r' );
106670 for(i=1; sqlite3Isspace(z[i]); i++){}
106671 *tokenType = TK_SPACE;
106672 return i;
106674 case '-': {
106675 if( z[1]=='-' ){
106676 /* IMP: R-15891-05542 -- syntax diagram for comments */
106677 for(i=2; (c=z[i])!=0 && c!='\n'; i++){}
106678 *tokenType = TK_SPACE; /* IMP: R-22934-25134 */
106679 return i;
106681 *tokenType = TK_MINUS;
106682 return 1;
106684 case '(': {
106685 *tokenType = TK_LP;
106686 return 1;
106688 case ')': {
106689 *tokenType = TK_RP;
106690 return 1;
106692 case ';': {
106693 *tokenType = TK_SEMI;
106694 return 1;
106696 case '+': {
106697 *tokenType = TK_PLUS;
106698 return 1;
106700 case '*': {
106701 *tokenType = TK_STAR;
106702 return 1;
106704 case '/': {
106705 if( z[1]!='*' || z[2]==0 ){
106706 *tokenType = TK_SLASH;
106707 return 1;
106709 /* IMP: R-15891-05542 -- syntax diagram for comments */
106710 for(i=3, c=z[2]; (c!='*' || z[i]!='/') && (c=z[i])!=0; i++){}
106711 if( c ) i++;
106712 *tokenType = TK_SPACE; /* IMP: R-22934-25134 */
106713 return i;
106715 case '%': {
106716 *tokenType = TK_REM;
106717 return 1;
106719 case '=': {
106720 *tokenType = TK_EQ;
106721 return 1 + (z[1]=='=');
106723 case '<': {
106724 if( (c=z[1])=='=' ){
106725 *tokenType = TK_LE;
106726 return 2;
106727 }else if( c=='>' ){
106728 *tokenType = TK_NE;
106729 return 2;
106730 }else if( c=='<' ){
106731 *tokenType = TK_LSHIFT;
106732 return 2;
106733 }else{
106734 *tokenType = TK_LT;
106735 return 1;
106738 case '>': {
106739 if( (c=z[1])=='=' ){
106740 *tokenType = TK_GE;
106741 return 2;
106742 }else if( c=='>' ){
106743 *tokenType = TK_RSHIFT;
106744 return 2;
106745 }else{
106746 *tokenType = TK_GT;
106747 return 1;
106750 case '!': {
106751 if( z[1]!='=' ){
106752 *tokenType = TK_ILLEGAL;
106753 return 2;
106754 }else{
106755 *tokenType = TK_NE;
106756 return 2;
106759 case '|': {
106760 if( z[1]!='|' ){
106761 *tokenType = TK_BITOR;
106762 return 1;
106763 }else{
106764 *tokenType = TK_CONCAT;
106765 return 2;
106768 case ',': {
106769 *tokenType = TK_COMMA;
106770 return 1;
106772 case '&': {
106773 *tokenType = TK_BITAND;
106774 return 1;
106776 case '~': {
106777 *tokenType = TK_BITNOT;
106778 return 1;
106780 case '`':
106781 case '\'':
106782 case '"': {
106783 int delim = z[0];
106784 testcase( delim=='`' );
106785 testcase( delim=='\'' );
106786 testcase( delim=='"' );
106787 for(i=1; (c=z[i])!=0; i++){
106788 if( c==delim ){
106789 if( z[i+1]==delim ){
106791 }else{
106792 break;
106796 if( c=='\'' ){
106797 *tokenType = TK_STRING;
106798 return i+1;
106799 }else if( c!=0 ){
106800 *tokenType = TK_ID;
106801 return i+1;
106802 }else{
106803 *tokenType = TK_ILLEGAL;
106804 return i;
106807 case '.': {
106808 #ifndef SQLITE_OMIT_FLOATING_POINT
106809 if( !sqlite3Isdigit(z[1]) )
106810 #endif
106812 *tokenType = TK_DOT;
106813 return 1;
106815 /* If the next character is a digit, this is a floating point
106816 ** number that begins with ".". Fall thru into the next case */
106818 case '0': case '1': case '2': case '3': case '4':
106819 case '5': case '6': case '7': case '8': case '9': {
106820 testcase( z[0]=='0' ); testcase( z[0]=='1' ); testcase( z[0]=='2' );
106821 testcase( z[0]=='3' ); testcase( z[0]=='4' ); testcase( z[0]=='5' );
106822 testcase( z[0]=='6' ); testcase( z[0]=='7' ); testcase( z[0]=='8' );
106823 testcase( z[0]=='9' );
106824 *tokenType = TK_INTEGER;
106825 for(i=0; sqlite3Isdigit(z[i]); i++){}
106826 #ifndef SQLITE_OMIT_FLOATING_POINT
106827 if( z[i]=='.' ){
106829 while( sqlite3Isdigit(z[i]) ){ i++; }
106830 *tokenType = TK_FLOAT;
106832 if( (z[i]=='e' || z[i]=='E') &&
106833 ( sqlite3Isdigit(z[i+1])
106834 || ((z[i+1]=='+' || z[i+1]=='-') && sqlite3Isdigit(z[i+2]))
106837 i += 2;
106838 while( sqlite3Isdigit(z[i]) ){ i++; }
106839 *tokenType = TK_FLOAT;
106841 #endif
106842 while( IdChar(z[i]) ){
106843 *tokenType = TK_ILLEGAL;
106846 return i;
106848 case '[': {
106849 for(i=1, c=z[0]; c!=']' && (c=z[i])!=0; i++){}
106850 *tokenType = c==']' ? TK_ID : TK_ILLEGAL;
106851 return i;
106853 case '?': {
106854 *tokenType = TK_VARIABLE;
106855 for(i=1; sqlite3Isdigit(z[i]); i++){}
106856 return i;
106858 case '#': {
106859 for(i=1; sqlite3Isdigit(z[i]); i++){}
106860 if( i>1 ){
106861 /* Parameters of the form #NNN (where NNN is a number) are used
106862 ** internally by sqlite3NestedParse. */
106863 *tokenType = TK_REGISTER;
106864 return i;
106866 /* Fall through into the next case if the '#' is not followed by
106867 ** a digit. Try to match #AAAA where AAAA is a parameter name. */
106869 #ifndef SQLITE_OMIT_TCL_VARIABLE
106870 case '$':
106871 #endif
106872 case '@': /* For compatibility with MS SQL Server */
106873 case ':': {
106874 int n = 0;
106875 testcase( z[0]=='$' ); testcase( z[0]=='@' ); testcase( z[0]==':' );
106876 *tokenType = TK_VARIABLE;
106877 for(i=1; (c=z[i])!=0; i++){
106878 if( IdChar(c) ){
106880 #ifndef SQLITE_OMIT_TCL_VARIABLE
106881 }else if( c=='(' && n>0 ){
106884 }while( (c=z[i])!=0 && !sqlite3Isspace(c) && c!=')' );
106885 if( c==')' ){
106887 }else{
106888 *tokenType = TK_ILLEGAL;
106890 break;
106891 }else if( c==':' && z[i+1]==':' ){
106893 #endif
106894 }else{
106895 break;
106898 if( n==0 ) *tokenType = TK_ILLEGAL;
106899 return i;
106901 #ifndef SQLITE_OMIT_BLOB_LITERAL
106902 case 'x': case 'X': {
106903 testcase( z[0]=='x' ); testcase( z[0]=='X' );
106904 if( z[1]=='\'' ){
106905 *tokenType = TK_BLOB;
106906 for(i=2; (c=z[i])!=0 && c!='\''; i++){
106907 if( !sqlite3Isxdigit(c) ){
106908 *tokenType = TK_ILLEGAL;
106911 if( i%2 || !c ) *tokenType = TK_ILLEGAL;
106912 if( c ) i++;
106913 return i;
106915 /* Otherwise fall through to the next case */
106917 #endif
106918 default: {
106919 if( !IdChar(*z) ){
106920 break;
106922 for(i=1; IdChar(z[i]); i++){}
106923 *tokenType = keywordCode((char*)z, i);
106924 return i;
106927 *tokenType = TK_ILLEGAL;
106928 return 1;
106932 ** Run the parser on the given SQL string. The parser structure is
106933 ** passed in. An SQLITE_ status code is returned. If an error occurs
106934 ** then an and attempt is made to write an error message into
106935 ** memory obtained from sqlite3_malloc() and to make *pzErrMsg point to that
106936 ** error message.
106938 SQLITE_PRIVATE int sqlite3RunParser(Parse *pParse, const char *zSql, char **pzErrMsg){
106939 int nErr = 0; /* Number of errors encountered */
106940 int i; /* Loop counter */
106941 void *pEngine; /* The LEMON-generated LALR(1) parser */
106942 int tokenType; /* type of the next token */
106943 int lastTokenParsed = -1; /* type of the previous token */
106944 u8 enableLookaside; /* Saved value of db->lookaside.bEnabled */
106945 sqlite3 *db = pParse->db; /* The database connection */
106946 int mxSqlLen; /* Max length of an SQL string */
106949 mxSqlLen = db->aLimit[SQLITE_LIMIT_SQL_LENGTH];
106950 if( db->activeVdbeCnt==0 ){
106951 db->u1.isInterrupted = 0;
106953 pParse->rc = SQLITE_OK;
106954 pParse->zTail = zSql;
106955 i = 0;
106956 assert( pzErrMsg!=0 );
106957 pEngine = sqlite3ParserAlloc((void*(*)(size_t))sqlite3Malloc);
106958 if( pEngine==0 ){
106959 db->mallocFailed = 1;
106960 return SQLITE_NOMEM;
106962 assert( pParse->pNewTable==0 );
106963 assert( pParse->pNewTrigger==0 );
106964 assert( pParse->nVar==0 );
106965 assert( pParse->nVarExpr==0 );
106966 assert( pParse->nVarExprAlloc==0 );
106967 assert( pParse->apVarExpr==0 );
106968 enableLookaside = db->lookaside.bEnabled;
106969 if( db->lookaside.pStart ) db->lookaside.bEnabled = 1;
106970 while( !db->mallocFailed && zSql[i]!=0 ){
106971 assert( i>=0 );
106972 pParse->sLastToken.z = &zSql[i];
106973 pParse->sLastToken.n = sqlite3GetToken((unsigned char*)&zSql[i],&tokenType);
106974 i += pParse->sLastToken.n;
106975 if( i>mxSqlLen ){
106976 pParse->rc = SQLITE_TOOBIG;
106977 break;
106979 switch( tokenType ){
106980 case TK_SPACE: {
106981 if( db->u1.isInterrupted ){
106982 sqlite3ErrorMsg(pParse, "interrupt");
106983 pParse->rc = SQLITE_INTERRUPT;
106984 goto abort_parse;
106986 break;
106988 case TK_ILLEGAL: {
106989 sqlite3DbFree(db, *pzErrMsg);
106990 *pzErrMsg = sqlite3MPrintf(db, "unrecognized token: \"%T\"",
106991 &pParse->sLastToken);
106992 nErr++;
106993 goto abort_parse;
106995 case TK_SEMI: {
106996 pParse->zTail = &zSql[i];
106997 /* Fall thru into the default case */
106999 default: {
107000 sqlite3Parser(pEngine, tokenType, pParse->sLastToken, pParse);
107001 lastTokenParsed = tokenType;
107002 if( pParse->rc!=SQLITE_OK ){
107003 goto abort_parse;
107005 break;
107009 abort_parse:
107010 if( zSql[i]==0 && nErr==0 && pParse->rc==SQLITE_OK ){
107011 if( lastTokenParsed!=TK_SEMI ){
107012 sqlite3Parser(pEngine, TK_SEMI, pParse->sLastToken, pParse);
107013 pParse->zTail = &zSql[i];
107015 sqlite3Parser(pEngine, 0, pParse->sLastToken, pParse);
107017 #ifdef YYTRACKMAXSTACKDEPTH
107018 sqlite3StatusSet(SQLITE_STATUS_PARSER_STACK,
107019 sqlite3ParserStackPeak(pEngine)
107021 #endif /* YYDEBUG */
107022 sqlite3ParserFree(pEngine, sqlite3_free);
107023 db->lookaside.bEnabled = enableLookaside;
107024 if( db->mallocFailed ){
107025 pParse->rc = SQLITE_NOMEM;
107027 if( pParse->rc!=SQLITE_OK && pParse->rc!=SQLITE_DONE && pParse->zErrMsg==0 ){
107028 sqlite3SetString(&pParse->zErrMsg, db, "%s", sqlite3ErrStr(pParse->rc));
107030 assert( pzErrMsg!=0 );
107031 if( pParse->zErrMsg ){
107032 *pzErrMsg = pParse->zErrMsg;
107033 sqlite3_log(pParse->rc, "%s", *pzErrMsg);
107034 pParse->zErrMsg = 0;
107035 nErr++;
107037 if( pParse->pVdbe && pParse->nErr>0 && pParse->nested==0 ){
107038 sqlite3VdbeDelete(pParse->pVdbe);
107039 pParse->pVdbe = 0;
107041 #ifndef SQLITE_OMIT_SHARED_CACHE
107042 if( pParse->nested==0 ){
107043 sqlite3DbFree(db, pParse->aTableLock);
107044 pParse->aTableLock = 0;
107045 pParse->nTableLock = 0;
107047 #endif
107048 #ifndef SQLITE_OMIT_VIRTUALTABLE
107049 sqlite3_free(pParse->apVtabLock);
107050 #endif
107052 if( !IN_DECLARE_VTAB ){
107053 /* If the pParse->declareVtab flag is set, do not delete any table
107054 ** structure built up in pParse->pNewTable. The calling code (see vtab.c)
107055 ** will take responsibility for freeing the Table structure.
107057 sqlite3DeleteTable(db, pParse->pNewTable);
107060 sqlite3DeleteTrigger(db, pParse->pNewTrigger);
107061 sqlite3DbFree(db, pParse->apVarExpr);
107062 sqlite3DbFree(db, pParse->aAlias);
107063 while( pParse->pAinc ){
107064 AutoincInfo *p = pParse->pAinc;
107065 pParse->pAinc = p->pNext;
107066 sqlite3DbFree(db, p);
107068 while( pParse->pZombieTab ){
107069 Table *p = pParse->pZombieTab;
107070 pParse->pZombieTab = p->pNextZombie;
107071 sqlite3DeleteTable(db, p);
107073 if( nErr>0 && pParse->rc==SQLITE_OK ){
107074 pParse->rc = SQLITE_ERROR;
107076 return nErr;
107079 /************** End of tokenize.c ********************************************/
107080 /************** Begin file complete.c ****************************************/
107082 ** 2001 September 15
107084 ** The author disclaims copyright to this source code. In place of
107085 ** a legal notice, here is a blessing:
107087 ** May you do good and not evil.
107088 ** May you find forgiveness for yourself and forgive others.
107089 ** May you share freely, never taking more than you give.
107091 *************************************************************************
107092 ** An tokenizer for SQL
107094 ** This file contains C code that implements the sqlite3_complete() API.
107095 ** This code used to be part of the tokenizer.c source file. But by
107096 ** separating it out, the code will be automatically omitted from
107097 ** static links that do not use it.
107099 #ifndef SQLITE_OMIT_COMPLETE
107102 ** This is defined in tokenize.c. We just have to import the definition.
107104 #ifndef SQLITE_AMALGAMATION
107105 #ifdef SQLITE_ASCII
107106 #define IdChar(C) ((sqlite3CtypeMap[(unsigned char)C]&0x46)!=0)
107107 #endif
107108 #ifdef SQLITE_EBCDIC
107109 SQLITE_PRIVATE const char sqlite3IsEbcdicIdChar[];
107110 #define IdChar(C) (((c=C)>=0x42 && sqlite3IsEbcdicIdChar[c-0x40]))
107111 #endif
107112 #endif /* SQLITE_AMALGAMATION */
107116 ** Token types used by the sqlite3_complete() routine. See the header
107117 ** comments on that procedure for additional information.
107119 #define tkSEMI 0
107120 #define tkWS 1
107121 #define tkOTHER 2
107122 #ifndef SQLITE_OMIT_TRIGGER
107123 #define tkEXPLAIN 3
107124 #define tkCREATE 4
107125 #define tkTEMP 5
107126 #define tkTRIGGER 6
107127 #define tkEND 7
107128 #endif
107131 ** Return TRUE if the given SQL string ends in a semicolon.
107133 ** Special handling is require for CREATE TRIGGER statements.
107134 ** Whenever the CREATE TRIGGER keywords are seen, the statement
107135 ** must end with ";END;".
107137 ** This implementation uses a state machine with 8 states:
107139 ** (0) INVALID We have not yet seen a non-whitespace character.
107141 ** (1) START At the beginning or end of an SQL statement. This routine
107142 ** returns 1 if it ends in the START state and 0 if it ends
107143 ** in any other state.
107145 ** (2) NORMAL We are in the middle of statement which ends with a single
107146 ** semicolon.
107148 ** (3) EXPLAIN The keyword EXPLAIN has been seen at the beginning of
107149 ** a statement.
107151 ** (4) CREATE The keyword CREATE has been seen at the beginning of a
107152 ** statement, possibly preceeded by EXPLAIN and/or followed by
107153 ** TEMP or TEMPORARY
107155 ** (5) TRIGGER We are in the middle of a trigger definition that must be
107156 ** ended by a semicolon, the keyword END, and another semicolon.
107158 ** (6) SEMI We've seen the first semicolon in the ";END;" that occurs at
107159 ** the end of a trigger definition.
107161 ** (7) END We've seen the ";END" of the ";END;" that occurs at the end
107162 ** of a trigger difinition.
107164 ** Transitions between states above are determined by tokens extracted
107165 ** from the input. The following tokens are significant:
107167 ** (0) tkSEMI A semicolon.
107168 ** (1) tkWS Whitespace.
107169 ** (2) tkOTHER Any other SQL token.
107170 ** (3) tkEXPLAIN The "explain" keyword.
107171 ** (4) tkCREATE The "create" keyword.
107172 ** (5) tkTEMP The "temp" or "temporary" keyword.
107173 ** (6) tkTRIGGER The "trigger" keyword.
107174 ** (7) tkEND The "end" keyword.
107176 ** Whitespace never causes a state transition and is always ignored.
107177 ** This means that a SQL string of all whitespace is invalid.
107179 ** If we compile with SQLITE_OMIT_TRIGGER, all of the computation needed
107180 ** to recognize the end of a trigger can be omitted. All we have to do
107181 ** is look for a semicolon that is not part of an string or comment.
107183 SQLITE_API int sqlite3_complete(const char *zSql){
107184 u8 state = 0; /* Current state, using numbers defined in header comment */
107185 u8 token; /* Value of the next token */
107187 #ifndef SQLITE_OMIT_TRIGGER
107188 /* A complex statement machine used to detect the end of a CREATE TRIGGER
107189 ** statement. This is the normal case.
107191 static const u8 trans[8][8] = {
107192 /* Token: */
107193 /* State: ** SEMI WS OTHER EXPLAIN CREATE TEMP TRIGGER END */
107194 /* 0 INVALID: */ { 1, 0, 2, 3, 4, 2, 2, 2, },
107195 /* 1 START: */ { 1, 1, 2, 3, 4, 2, 2, 2, },
107196 /* 2 NORMAL: */ { 1, 2, 2, 2, 2, 2, 2, 2, },
107197 /* 3 EXPLAIN: */ { 1, 3, 3, 2, 4, 2, 2, 2, },
107198 /* 4 CREATE: */ { 1, 4, 2, 2, 2, 4, 5, 2, },
107199 /* 5 TRIGGER: */ { 6, 5, 5, 5, 5, 5, 5, 5, },
107200 /* 6 SEMI: */ { 6, 6, 5, 5, 5, 5, 5, 7, },
107201 /* 7 END: */ { 1, 7, 5, 5, 5, 5, 5, 5, },
107203 #else
107204 /* If triggers are not supported by this compile then the statement machine
107205 ** used to detect the end of a statement is much simplier
107207 static const u8 trans[3][3] = {
107208 /* Token: */
107209 /* State: ** SEMI WS OTHER */
107210 /* 0 INVALID: */ { 1, 0, 2, },
107211 /* 1 START: */ { 1, 1, 2, },
107212 /* 2 NORMAL: */ { 1, 2, 2, },
107214 #endif /* SQLITE_OMIT_TRIGGER */
107216 while( *zSql ){
107217 switch( *zSql ){
107218 case ';': { /* A semicolon */
107219 token = tkSEMI;
107220 break;
107222 case ' ':
107223 case '\r':
107224 case '\t':
107225 case '\n':
107226 case '\f': { /* White space is ignored */
107227 token = tkWS;
107228 break;
107230 case '/': { /* C-style comments */
107231 if( zSql[1]!='*' ){
107232 token = tkOTHER;
107233 break;
107235 zSql += 2;
107236 while( zSql[0] && (zSql[0]!='*' || zSql[1]!='/') ){ zSql++; }
107237 if( zSql[0]==0 ) return 0;
107238 zSql++;
107239 token = tkWS;
107240 break;
107242 case '-': { /* SQL-style comments from "--" to end of line */
107243 if( zSql[1]!='-' ){
107244 token = tkOTHER;
107245 break;
107247 while( *zSql && *zSql!='\n' ){ zSql++; }
107248 if( *zSql==0 ) return state==1;
107249 token = tkWS;
107250 break;
107252 case '[': { /* Microsoft-style identifiers in [...] */
107253 zSql++;
107254 while( *zSql && *zSql!=']' ){ zSql++; }
107255 if( *zSql==0 ) return 0;
107256 token = tkOTHER;
107257 break;
107259 case '`': /* Grave-accent quoted symbols used by MySQL */
107260 case '"': /* single- and double-quoted strings */
107261 case '\'': {
107262 int c = *zSql;
107263 zSql++;
107264 while( *zSql && *zSql!=c ){ zSql++; }
107265 if( *zSql==0 ) return 0;
107266 token = tkOTHER;
107267 break;
107269 default: {
107270 #ifdef SQLITE_EBCDIC
107271 unsigned char c;
107272 #endif
107273 if( IdChar((u8)*zSql) ){
107274 /* Keywords and unquoted identifiers */
107275 int nId;
107276 for(nId=1; IdChar(zSql[nId]); nId++){}
107277 #ifdef SQLITE_OMIT_TRIGGER
107278 token = tkOTHER;
107279 #else
107280 switch( *zSql ){
107281 case 'c': case 'C': {
107282 if( nId==6 && sqlite3StrNICmp(zSql, "create", 6)==0 ){
107283 token = tkCREATE;
107284 }else{
107285 token = tkOTHER;
107287 break;
107289 case 't': case 'T': {
107290 if( nId==7 && sqlite3StrNICmp(zSql, "trigger", 7)==0 ){
107291 token = tkTRIGGER;
107292 }else if( nId==4 && sqlite3StrNICmp(zSql, "temp", 4)==0 ){
107293 token = tkTEMP;
107294 }else if( nId==9 && sqlite3StrNICmp(zSql, "temporary", 9)==0 ){
107295 token = tkTEMP;
107296 }else{
107297 token = tkOTHER;
107299 break;
107301 case 'e': case 'E': {
107302 if( nId==3 && sqlite3StrNICmp(zSql, "end", 3)==0 ){
107303 token = tkEND;
107304 }else
107305 #ifndef SQLITE_OMIT_EXPLAIN
107306 if( nId==7 && sqlite3StrNICmp(zSql, "explain", 7)==0 ){
107307 token = tkEXPLAIN;
107308 }else
107309 #endif
107311 token = tkOTHER;
107313 break;
107315 default: {
107316 token = tkOTHER;
107317 break;
107320 #endif /* SQLITE_OMIT_TRIGGER */
107321 zSql += nId-1;
107322 }else{
107323 /* Operators and special symbols */
107324 token = tkOTHER;
107326 break;
107329 state = trans[state][token];
107330 zSql++;
107332 return state==1;
107335 #ifndef SQLITE_OMIT_UTF16
107337 ** This routine is the same as the sqlite3_complete() routine described
107338 ** above, except that the parameter is required to be UTF-16 encoded, not
107339 ** UTF-8.
107341 SQLITE_API int sqlite3_complete16(const void *zSql){
107342 sqlite3_value *pVal;
107343 char const *zSql8;
107344 int rc = SQLITE_NOMEM;
107346 #ifndef SQLITE_OMIT_AUTOINIT
107347 rc = sqlite3_initialize();
107348 if( rc ) return rc;
107349 #endif
107350 pVal = sqlite3ValueNew(0);
107351 sqlite3ValueSetStr(pVal, -1, zSql, SQLITE_UTF16NATIVE, SQLITE_STATIC);
107352 zSql8 = sqlite3ValueText(pVal, SQLITE_UTF8);
107353 if( zSql8 ){
107354 rc = sqlite3_complete(zSql8);
107355 }else{
107356 rc = SQLITE_NOMEM;
107358 sqlite3ValueFree(pVal);
107359 return sqlite3ApiExit(0, rc);
107361 #endif /* SQLITE_OMIT_UTF16 */
107362 #endif /* SQLITE_OMIT_COMPLETE */
107364 /************** End of complete.c ********************************************/
107365 /************** Begin file main.c ********************************************/
107367 ** 2001 September 15
107369 ** The author disclaims copyright to this source code. In place of
107370 ** a legal notice, here is a blessing:
107372 ** May you do good and not evil.
107373 ** May you find forgiveness for yourself and forgive others.
107374 ** May you share freely, never taking more than you give.
107376 *************************************************************************
107377 ** Main file for the SQLite library. The routines in this file
107378 ** implement the programmer interface to the library. Routines in
107379 ** other files are for internal use by SQLite and should not be
107380 ** accessed by users of the library.
107383 #ifdef SQLITE_ENABLE_FTS3
107384 /************** Include fts3.h in the middle of main.c ***********************/
107385 /************** Begin file fts3.h ********************************************/
107387 ** 2006 Oct 10
107389 ** The author disclaims copyright to this source code. In place of
107390 ** a legal notice, here is a blessing:
107392 ** May you do good and not evil.
107393 ** May you find forgiveness for yourself and forgive others.
107394 ** May you share freely, never taking more than you give.
107396 ******************************************************************************
107398 ** This header file is used by programs that want to link against the
107399 ** FTS3 library. All it does is declare the sqlite3Fts3Init() interface.
107402 #if 0
107403 extern "C" {
107404 #endif /* __cplusplus */
107406 SQLITE_PRIVATE int sqlite3Fts3Init(sqlite3 *db);
107408 #if 0
107409 } /* extern "C" */
107410 #endif /* __cplusplus */
107412 /************** End of fts3.h ************************************************/
107413 /************** Continuing where we left off in main.c ***********************/
107414 #endif
107415 #ifdef SQLITE_ENABLE_RTREE
107416 /************** Include rtree.h in the middle of main.c **********************/
107417 /************** Begin file rtree.h *******************************************/
107419 ** 2008 May 26
107421 ** The author disclaims copyright to this source code. In place of
107422 ** a legal notice, here is a blessing:
107424 ** May you do good and not evil.
107425 ** May you find forgiveness for yourself and forgive others.
107426 ** May you share freely, never taking more than you give.
107428 ******************************************************************************
107430 ** This header file is used by programs that want to link against the
107431 ** RTREE library. All it does is declare the sqlite3RtreeInit() interface.
107434 #if 0
107435 extern "C" {
107436 #endif /* __cplusplus */
107438 SQLITE_PRIVATE int sqlite3RtreeInit(sqlite3 *db);
107440 #if 0
107441 } /* extern "C" */
107442 #endif /* __cplusplus */
107444 /************** End of rtree.h ***********************************************/
107445 /************** Continuing where we left off in main.c ***********************/
107446 #endif
107447 #ifdef SQLITE_ENABLE_ICU
107448 /************** Include sqliteicu.h in the middle of main.c ******************/
107449 /************** Begin file sqliteicu.h ***************************************/
107451 ** 2008 May 26
107453 ** The author disclaims copyright to this source code. In place of
107454 ** a legal notice, here is a blessing:
107456 ** May you do good and not evil.
107457 ** May you find forgiveness for yourself and forgive others.
107458 ** May you share freely, never taking more than you give.
107460 ******************************************************************************
107462 ** This header file is used by programs that want to link against the
107463 ** ICU extension. All it does is declare the sqlite3IcuInit() interface.
107466 #if 0
107467 extern "C" {
107468 #endif /* __cplusplus */
107470 SQLITE_PRIVATE int sqlite3IcuInit(sqlite3 *db);
107472 #if 0
107473 } /* extern "C" */
107474 #endif /* __cplusplus */
107477 /************** End of sqliteicu.h *******************************************/
107478 /************** Continuing where we left off in main.c ***********************/
107479 #endif
107481 #ifndef SQLITE_AMALGAMATION
107482 /* IMPLEMENTATION-OF: R-46656-45156 The sqlite3_version[] string constant
107483 ** contains the text of SQLITE_VERSION macro.
107485 SQLITE_API const char sqlite3_version[] = SQLITE_VERSION;
107486 #endif
107488 /* IMPLEMENTATION-OF: R-53536-42575 The sqlite3_libversion() function returns
107489 ** a pointer to the to the sqlite3_version[] string constant.
107491 SQLITE_API const char *sqlite3_libversion(void){ return sqlite3_version; }
107493 /* IMPLEMENTATION-OF: R-63124-39300 The sqlite3_sourceid() function returns a
107494 ** pointer to a string constant whose value is the same as the
107495 ** SQLITE_SOURCE_ID C preprocessor macro.
107497 SQLITE_API const char *sqlite3_sourceid(void){ return SQLITE_SOURCE_ID; }
107499 /* IMPLEMENTATION-OF: R-35210-63508 The sqlite3_libversion_number() function
107500 ** returns an integer equal to SQLITE_VERSION_NUMBER.
107502 SQLITE_API int sqlite3_libversion_number(void){ return SQLITE_VERSION_NUMBER; }
107504 /* IMPLEMENTATION-OF: R-54823-41343 The sqlite3_threadsafe() function returns
107505 ** zero if and only if SQLite was compiled mutexing code omitted due to
107506 ** the SQLITE_THREADSAFE compile-time option being set to 0.
107508 SQLITE_API int sqlite3_threadsafe(void){ return SQLITE_THREADSAFE; }
107510 #if !defined(SQLITE_OMIT_TRACE) && defined(SQLITE_ENABLE_IOTRACE)
107512 ** If the following function pointer is not NULL and if
107513 ** SQLITE_ENABLE_IOTRACE is enabled, then messages describing
107514 ** I/O active are written using this function. These messages
107515 ** are intended for debugging activity only.
107517 SQLITE_PRIVATE void (*sqlite3IoTrace)(const char*, ...) = 0;
107518 #endif
107521 ** If the following global variable points to a string which is the
107522 ** name of a directory, then that directory will be used to store
107523 ** temporary files.
107525 ** See also the "PRAGMA temp_store_directory" SQL command.
107527 SQLITE_API char *sqlite3_temp_directory = 0;
107530 ** Initialize SQLite.
107532 ** This routine must be called to initialize the memory allocation,
107533 ** VFS, and mutex subsystems prior to doing any serious work with
107534 ** SQLite. But as long as you do not compile with SQLITE_OMIT_AUTOINIT
107535 ** this routine will be called automatically by key routines such as
107536 ** sqlite3_open().
107538 ** This routine is a no-op except on its very first call for the process,
107539 ** or for the first call after a call to sqlite3_shutdown.
107541 ** The first thread to call this routine runs the initialization to
107542 ** completion. If subsequent threads call this routine before the first
107543 ** thread has finished the initialization process, then the subsequent
107544 ** threads must block until the first thread finishes with the initialization.
107546 ** The first thread might call this routine recursively. Recursive
107547 ** calls to this routine should not block, of course. Otherwise the
107548 ** initialization process would never complete.
107550 ** Let X be the first thread to enter this routine. Let Y be some other
107551 ** thread. Then while the initial invocation of this routine by X is
107552 ** incomplete, it is required that:
107554 ** * Calls to this routine from Y must block until the outer-most
107555 ** call by X completes.
107557 ** * Recursive calls to this routine from thread X return immediately
107558 ** without blocking.
107560 SQLITE_API int sqlite3_initialize(void){
107561 sqlite3_mutex *pMaster; /* The main static mutex */
107562 int rc; /* Result code */
107564 #ifdef SQLITE_OMIT_WSD
107565 rc = sqlite3_wsd_init(4096, 24);
107566 if( rc!=SQLITE_OK ){
107567 return rc;
107569 #endif
107571 /* If SQLite is already completely initialized, then this call
107572 ** to sqlite3_initialize() should be a no-op. But the initialization
107573 ** must be complete. So isInit must not be set until the very end
107574 ** of this routine.
107576 if( sqlite3GlobalConfig.isInit ) return SQLITE_OK;
107578 /* Make sure the mutex subsystem is initialized. If unable to
107579 ** initialize the mutex subsystem, return early with the error.
107580 ** If the system is so sick that we are unable to allocate a mutex,
107581 ** there is not much SQLite is going to be able to do.
107583 ** The mutex subsystem must take care of serializing its own
107584 ** initialization.
107586 rc = sqlite3MutexInit();
107587 if( rc ) return rc;
107589 /* Initialize the malloc() system and the recursive pInitMutex mutex.
107590 ** This operation is protected by the STATIC_MASTER mutex. Note that
107591 ** MutexAlloc() is called for a static mutex prior to initializing the
107592 ** malloc subsystem - this implies that the allocation of a static
107593 ** mutex must not require support from the malloc subsystem.
107595 pMaster = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
107596 sqlite3_mutex_enter(pMaster);
107597 sqlite3GlobalConfig.isMutexInit = 1;
107598 if( !sqlite3GlobalConfig.isMallocInit ){
107599 rc = sqlite3MallocInit();
107601 if( rc==SQLITE_OK ){
107602 sqlite3GlobalConfig.isMallocInit = 1;
107603 if( !sqlite3GlobalConfig.pInitMutex ){
107604 sqlite3GlobalConfig.pInitMutex =
107605 sqlite3MutexAlloc(SQLITE_MUTEX_RECURSIVE);
107606 if( sqlite3GlobalConfig.bCoreMutex && !sqlite3GlobalConfig.pInitMutex ){
107607 rc = SQLITE_NOMEM;
107611 if( rc==SQLITE_OK ){
107612 sqlite3GlobalConfig.nRefInitMutex++;
107614 sqlite3_mutex_leave(pMaster);
107616 /* If rc is not SQLITE_OK at this point, then either the malloc
107617 ** subsystem could not be initialized or the system failed to allocate
107618 ** the pInitMutex mutex. Return an error in either case. */
107619 if( rc!=SQLITE_OK ){
107620 return rc;
107623 /* Do the rest of the initialization under the recursive mutex so
107624 ** that we will be able to handle recursive calls into
107625 ** sqlite3_initialize(). The recursive calls normally come through
107626 ** sqlite3_os_init() when it invokes sqlite3_vfs_register(), but other
107627 ** recursive calls might also be possible.
107629 ** IMPLEMENTATION-OF: R-00140-37445 SQLite automatically serializes calls
107630 ** to the xInit method, so the xInit method need not be threadsafe.
107632 ** The following mutex is what serializes access to the appdef pcache xInit
107633 ** methods. The sqlite3_pcache_methods.xInit() all is embedded in the
107634 ** call to sqlite3PcacheInitialize().
107636 sqlite3_mutex_enter(sqlite3GlobalConfig.pInitMutex);
107637 if( sqlite3GlobalConfig.isInit==0 && sqlite3GlobalConfig.inProgress==0 ){
107638 FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
107639 sqlite3GlobalConfig.inProgress = 1;
107640 memset(pHash, 0, sizeof(sqlite3GlobalFunctions));
107641 sqlite3RegisterGlobalFunctions();
107642 if( sqlite3GlobalConfig.isPCacheInit==0 ){
107643 rc = sqlite3PcacheInitialize();
107645 if( rc==SQLITE_OK ){
107646 sqlite3GlobalConfig.isPCacheInit = 1;
107647 rc = sqlite3OsInit();
107649 if( rc==SQLITE_OK ){
107650 sqlite3PCacheBufferSetup( sqlite3GlobalConfig.pPage,
107651 sqlite3GlobalConfig.szPage, sqlite3GlobalConfig.nPage);
107652 sqlite3GlobalConfig.isInit = 1;
107654 sqlite3GlobalConfig.inProgress = 0;
107656 sqlite3_mutex_leave(sqlite3GlobalConfig.pInitMutex);
107658 /* Go back under the static mutex and clean up the recursive
107659 ** mutex to prevent a resource leak.
107661 sqlite3_mutex_enter(pMaster);
107662 sqlite3GlobalConfig.nRefInitMutex--;
107663 if( sqlite3GlobalConfig.nRefInitMutex<=0 ){
107664 assert( sqlite3GlobalConfig.nRefInitMutex==0 );
107665 sqlite3_mutex_free(sqlite3GlobalConfig.pInitMutex);
107666 sqlite3GlobalConfig.pInitMutex = 0;
107668 sqlite3_mutex_leave(pMaster);
107670 /* The following is just a sanity check to make sure SQLite has
107671 ** been compiled correctly. It is important to run this code, but
107672 ** we don't want to run it too often and soak up CPU cycles for no
107673 ** reason. So we run it once during initialization.
107675 #ifndef NDEBUG
107676 #ifndef SQLITE_OMIT_FLOATING_POINT
107677 /* This section of code's only "output" is via assert() statements. */
107678 if ( rc==SQLITE_OK ){
107679 u64 x = (((u64)1)<<63)-1;
107680 double y;
107681 assert(sizeof(x)==8);
107682 assert(sizeof(x)==sizeof(y));
107683 memcpy(&y, &x, 8);
107684 assert( sqlite3IsNaN(y) );
107686 #endif
107687 #endif
107689 return rc;
107693 ** Undo the effects of sqlite3_initialize(). Must not be called while
107694 ** there are outstanding database connections or memory allocations or
107695 ** while any part of SQLite is otherwise in use in any thread. This
107696 ** routine is not threadsafe. But it is safe to invoke this routine
107697 ** on when SQLite is already shut down. If SQLite is already shut down
107698 ** when this routine is invoked, then this routine is a harmless no-op.
107700 SQLITE_API int sqlite3_shutdown(void){
107701 if( sqlite3GlobalConfig.isInit ){
107702 sqlite3_os_end();
107703 sqlite3_reset_auto_extension();
107704 sqlite3GlobalConfig.isInit = 0;
107706 if( sqlite3GlobalConfig.isPCacheInit ){
107707 sqlite3PcacheShutdown();
107708 sqlite3GlobalConfig.isPCacheInit = 0;
107710 if( sqlite3GlobalConfig.isMallocInit ){
107711 sqlite3MallocEnd();
107712 sqlite3GlobalConfig.isMallocInit = 0;
107714 if( sqlite3GlobalConfig.isMutexInit ){
107715 sqlite3MutexEnd();
107716 sqlite3GlobalConfig.isMutexInit = 0;
107719 return SQLITE_OK;
107723 ** This API allows applications to modify the global configuration of
107724 ** the SQLite library at run-time.
107726 ** This routine should only be called when there are no outstanding
107727 ** database connections or memory allocations. This routine is not
107728 ** threadsafe. Failure to heed these warnings can lead to unpredictable
107729 ** behavior.
107731 SQLITE_API int sqlite3_config(int op, ...){
107732 va_list ap;
107733 int rc = SQLITE_OK;
107735 /* sqlite3_config() shall return SQLITE_MISUSE if it is invoked while
107736 ** the SQLite library is in use. */
107737 if( sqlite3GlobalConfig.isInit ) return SQLITE_MISUSE_BKPT;
107739 va_start(ap, op);
107740 switch( op ){
107742 /* Mutex configuration options are only available in a threadsafe
107743 ** compile.
107745 #if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0
107746 case SQLITE_CONFIG_SINGLETHREAD: {
107747 /* Disable all mutexing */
107748 sqlite3GlobalConfig.bCoreMutex = 0;
107749 sqlite3GlobalConfig.bFullMutex = 0;
107750 break;
107752 case SQLITE_CONFIG_MULTITHREAD: {
107753 /* Disable mutexing of database connections */
107754 /* Enable mutexing of core data structures */
107755 sqlite3GlobalConfig.bCoreMutex = 1;
107756 sqlite3GlobalConfig.bFullMutex = 0;
107757 break;
107759 case SQLITE_CONFIG_SERIALIZED: {
107760 /* Enable all mutexing */
107761 sqlite3GlobalConfig.bCoreMutex = 1;
107762 sqlite3GlobalConfig.bFullMutex = 1;
107763 break;
107765 case SQLITE_CONFIG_MUTEX: {
107766 /* Specify an alternative mutex implementation */
107767 sqlite3GlobalConfig.mutex = *va_arg(ap, sqlite3_mutex_methods*);
107768 break;
107770 case SQLITE_CONFIG_GETMUTEX: {
107771 /* Retrieve the current mutex implementation */
107772 *va_arg(ap, sqlite3_mutex_methods*) = sqlite3GlobalConfig.mutex;
107773 break;
107775 #endif
107778 case SQLITE_CONFIG_MALLOC: {
107779 /* Specify an alternative malloc implementation */
107780 sqlite3GlobalConfig.m = *va_arg(ap, sqlite3_mem_methods*);
107781 break;
107783 case SQLITE_CONFIG_GETMALLOC: {
107784 /* Retrieve the current malloc() implementation */
107785 if( sqlite3GlobalConfig.m.xMalloc==0 ) sqlite3MemSetDefault();
107786 *va_arg(ap, sqlite3_mem_methods*) = sqlite3GlobalConfig.m;
107787 break;
107789 case SQLITE_CONFIG_MEMSTATUS: {
107790 /* Enable or disable the malloc status collection */
107791 sqlite3GlobalConfig.bMemstat = va_arg(ap, int);
107792 break;
107794 case SQLITE_CONFIG_SCRATCH: {
107795 /* Designate a buffer for scratch memory space */
107796 sqlite3GlobalConfig.pScratch = va_arg(ap, void*);
107797 sqlite3GlobalConfig.szScratch = va_arg(ap, int);
107798 sqlite3GlobalConfig.nScratch = va_arg(ap, int);
107799 break;
107801 case SQLITE_CONFIG_PAGECACHE: {
107802 /* Designate a buffer for page cache memory space */
107803 sqlite3GlobalConfig.pPage = va_arg(ap, void*);
107804 sqlite3GlobalConfig.szPage = va_arg(ap, int);
107805 sqlite3GlobalConfig.nPage = va_arg(ap, int);
107806 break;
107809 case SQLITE_CONFIG_PCACHE: {
107810 /* Specify an alternative page cache implementation */
107811 sqlite3GlobalConfig.pcache = *va_arg(ap, sqlite3_pcache_methods*);
107812 break;
107815 case SQLITE_CONFIG_GETPCACHE: {
107816 if( sqlite3GlobalConfig.pcache.xInit==0 ){
107817 sqlite3PCacheSetDefault();
107819 *va_arg(ap, sqlite3_pcache_methods*) = sqlite3GlobalConfig.pcache;
107820 break;
107823 #if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
107824 case SQLITE_CONFIG_HEAP: {
107825 /* Designate a buffer for heap memory space */
107826 sqlite3GlobalConfig.pHeap = va_arg(ap, void*);
107827 sqlite3GlobalConfig.nHeap = va_arg(ap, int);
107828 sqlite3GlobalConfig.mnReq = va_arg(ap, int);
107830 if( sqlite3GlobalConfig.mnReq<1 ){
107831 sqlite3GlobalConfig.mnReq = 1;
107832 }else if( sqlite3GlobalConfig.mnReq>(1<<12) ){
107833 /* cap min request size at 2^12 */
107834 sqlite3GlobalConfig.mnReq = (1<<12);
107837 if( sqlite3GlobalConfig.pHeap==0 ){
107838 /* If the heap pointer is NULL, then restore the malloc implementation
107839 ** back to NULL pointers too. This will cause the malloc to go
107840 ** back to its default implementation when sqlite3_initialize() is
107841 ** run.
107843 memset(&sqlite3GlobalConfig.m, 0, sizeof(sqlite3GlobalConfig.m));
107844 }else{
107845 /* The heap pointer is not NULL, then install one of the
107846 ** mem5.c/mem3.c methods. If neither ENABLE_MEMSYS3 nor
107847 ** ENABLE_MEMSYS5 is defined, return an error.
107849 #ifdef SQLITE_ENABLE_MEMSYS3
107850 sqlite3GlobalConfig.m = *sqlite3MemGetMemsys3();
107851 #endif
107852 #ifdef SQLITE_ENABLE_MEMSYS5
107853 sqlite3GlobalConfig.m = *sqlite3MemGetMemsys5();
107854 #endif
107856 break;
107858 #endif
107860 case SQLITE_CONFIG_LOOKASIDE: {
107861 sqlite3GlobalConfig.szLookaside = va_arg(ap, int);
107862 sqlite3GlobalConfig.nLookaside = va_arg(ap, int);
107863 break;
107866 /* Record a pointer to the logger funcction and its first argument.
107867 ** The default is NULL. Logging is disabled if the function pointer is
107868 ** NULL.
107870 case SQLITE_CONFIG_LOG: {
107871 /* MSVC is picky about pulling func ptrs from va lists.
107872 ** http://support.microsoft.com/kb/47961
107873 ** sqlite3GlobalConfig.xLog = va_arg(ap, void(*)(void*,int,const char*));
107875 typedef void(*LOGFUNC_t)(void*,int,const char*);
107876 sqlite3GlobalConfig.xLog = va_arg(ap, LOGFUNC_t);
107877 sqlite3GlobalConfig.pLogArg = va_arg(ap, void*);
107878 break;
107881 default: {
107882 rc = SQLITE_ERROR;
107883 break;
107886 va_end(ap);
107887 return rc;
107891 ** Set up the lookaside buffers for a database connection.
107892 ** Return SQLITE_OK on success.
107893 ** If lookaside is already active, return SQLITE_BUSY.
107895 ** The sz parameter is the number of bytes in each lookaside slot.
107896 ** The cnt parameter is the number of slots. If pStart is NULL the
107897 ** space for the lookaside memory is obtained from sqlite3_malloc().
107898 ** If pStart is not NULL then it is sz*cnt bytes of memory to use for
107899 ** the lookaside memory.
107901 static int setupLookaside(sqlite3 *db, void *pBuf, int sz, int cnt){
107902 void *pStart;
107903 if( db->lookaside.nOut ){
107904 return SQLITE_BUSY;
107906 /* Free any existing lookaside buffer for this handle before
107907 ** allocating a new one so we don't have to have space for
107908 ** both at the same time.
107910 if( db->lookaside.bMalloced ){
107911 sqlite3_free(db->lookaside.pStart);
107913 /* The size of a lookaside slot needs to be larger than a pointer
107914 ** to be useful.
107916 if( sz<=(int)sizeof(LookasideSlot*) ) sz = 0;
107917 if( cnt<0 ) cnt = 0;
107918 if( sz==0 || cnt==0 ){
107919 sz = 0;
107920 pStart = 0;
107921 }else if( pBuf==0 ){
107922 sz = ROUNDDOWN8(sz); /* IMP: R-33038-09382 */
107923 sqlite3BeginBenignMalloc();
107924 pStart = sqlite3Malloc( sz*cnt ); /* IMP: R-61949-35727 */
107925 sqlite3EndBenignMalloc();
107926 }else{
107927 sz = ROUNDDOWN8(sz); /* IMP: R-33038-09382 */
107928 pStart = pBuf;
107930 db->lookaside.pStart = pStart;
107931 db->lookaside.pFree = 0;
107932 db->lookaside.sz = (u16)sz;
107933 if( pStart ){
107934 int i;
107935 LookasideSlot *p;
107936 assert( sz > (int)sizeof(LookasideSlot*) );
107937 p = (LookasideSlot*)pStart;
107938 for(i=cnt-1; i>=0; i--){
107939 p->pNext = db->lookaside.pFree;
107940 db->lookaside.pFree = p;
107941 p = (LookasideSlot*)&((u8*)p)[sz];
107943 db->lookaside.pEnd = p;
107944 db->lookaside.bEnabled = 1;
107945 db->lookaside.bMalloced = pBuf==0 ?1:0;
107946 }else{
107947 db->lookaside.pEnd = 0;
107948 db->lookaside.bEnabled = 0;
107949 db->lookaside.bMalloced = 0;
107951 return SQLITE_OK;
107955 ** Return the mutex associated with a database connection.
107957 SQLITE_API sqlite3_mutex *sqlite3_db_mutex(sqlite3 *db){
107958 return db->mutex;
107962 ** Configuration settings for an individual database connection
107964 SQLITE_API int sqlite3_db_config(sqlite3 *db, int op, ...){
107965 va_list ap;
107966 int rc;
107967 va_start(ap, op);
107968 switch( op ){
107969 case SQLITE_DBCONFIG_LOOKASIDE: {
107970 void *pBuf = va_arg(ap, void*); /* IMP: R-26835-10964 */
107971 int sz = va_arg(ap, int); /* IMP: R-47871-25994 */
107972 int cnt = va_arg(ap, int); /* IMP: R-04460-53386 */
107973 rc = setupLookaside(db, pBuf, sz, cnt);
107974 break;
107976 default: {
107977 static const struct {
107978 int op; /* The opcode */
107979 u32 mask; /* Mask of the bit in sqlite3.flags to set/clear */
107980 } aFlagOp[] = {
107981 { SQLITE_DBCONFIG_ENABLE_FKEY, SQLITE_ForeignKeys },
107982 { SQLITE_DBCONFIG_ENABLE_TRIGGER, SQLITE_EnableTrigger },
107984 unsigned int i;
107985 rc = SQLITE_ERROR; /* IMP: R-42790-23372 */
107986 for(i=0; i<ArraySize(aFlagOp); i++){
107987 if( aFlagOp[i].op==op ){
107988 int onoff = va_arg(ap, int);
107989 int *pRes = va_arg(ap, int*);
107990 int oldFlags = db->flags;
107991 if( onoff>0 ){
107992 db->flags |= aFlagOp[i].mask;
107993 }else if( onoff==0 ){
107994 db->flags &= ~aFlagOp[i].mask;
107996 if( oldFlags!=db->flags ){
107997 sqlite3ExpirePreparedStatements(db);
107999 if( pRes ){
108000 *pRes = (db->flags & aFlagOp[i].mask)!=0;
108002 rc = SQLITE_OK;
108003 break;
108006 break;
108009 va_end(ap);
108010 return rc;
108015 ** Return true if the buffer z[0..n-1] contains all spaces.
108017 static int allSpaces(const char *z, int n){
108018 while( n>0 && z[n-1]==' ' ){ n--; }
108019 return n==0;
108023 ** This is the default collating function named "BINARY" which is always
108024 ** available.
108026 ** If the padFlag argument is not NULL then space padding at the end
108027 ** of strings is ignored. This implements the RTRIM collation.
108029 static int binCollFunc(
108030 void *padFlag,
108031 int nKey1, const void *pKey1,
108032 int nKey2, const void *pKey2
108034 int rc, n;
108035 n = nKey1<nKey2 ? nKey1 : nKey2;
108036 rc = memcmp(pKey1, pKey2, n);
108037 if( rc==0 ){
108038 if( padFlag
108039 && allSpaces(((char*)pKey1)+n, nKey1-n)
108040 && allSpaces(((char*)pKey2)+n, nKey2-n)
108042 /* Leave rc unchanged at 0 */
108043 }else{
108044 rc = nKey1 - nKey2;
108047 return rc;
108051 ** Another built-in collating sequence: NOCASE.
108053 ** This collating sequence is intended to be used for "case independant
108054 ** comparison". SQLite's knowledge of upper and lower case equivalents
108055 ** extends only to the 26 characters used in the English language.
108057 ** At the moment there is only a UTF-8 implementation.
108059 static int nocaseCollatingFunc(
108060 void *NotUsed,
108061 int nKey1, const void *pKey1,
108062 int nKey2, const void *pKey2
108064 int r = sqlite3StrNICmp(
108065 (const char *)pKey1, (const char *)pKey2, (nKey1<nKey2)?nKey1:nKey2);
108066 UNUSED_PARAMETER(NotUsed);
108067 if( 0==r ){
108068 r = nKey1-nKey2;
108070 return r;
108074 ** Return the ROWID of the most recent insert
108076 SQLITE_API sqlite_int64 sqlite3_last_insert_rowid(sqlite3 *db){
108077 return db->lastRowid;
108081 ** Return the number of changes in the most recent call to sqlite3_exec().
108083 SQLITE_API int sqlite3_changes(sqlite3 *db){
108084 return db->nChange;
108088 ** Return the number of changes since the database handle was opened.
108090 SQLITE_API int sqlite3_total_changes(sqlite3 *db){
108091 return db->nTotalChange;
108095 ** Close all open savepoints. This function only manipulates fields of the
108096 ** database handle object, it does not close any savepoints that may be open
108097 ** at the b-tree/pager level.
108099 SQLITE_PRIVATE void sqlite3CloseSavepoints(sqlite3 *db){
108100 while( db->pSavepoint ){
108101 Savepoint *pTmp = db->pSavepoint;
108102 db->pSavepoint = pTmp->pNext;
108103 sqlite3DbFree(db, pTmp);
108105 db->nSavepoint = 0;
108106 db->nStatement = 0;
108107 db->isTransactionSavepoint = 0;
108111 ** Invoke the destructor function associated with FuncDef p, if any. Except,
108112 ** if this is not the last copy of the function, do not invoke it. Multiple
108113 ** copies of a single function are created when create_function() is called
108114 ** with SQLITE_ANY as the encoding.
108116 static void functionDestroy(sqlite3 *db, FuncDef *p){
108117 FuncDestructor *pDestructor = p->pDestructor;
108118 if( pDestructor ){
108119 pDestructor->nRef--;
108120 if( pDestructor->nRef==0 ){
108121 pDestructor->xDestroy(pDestructor->pUserData);
108122 sqlite3DbFree(db, pDestructor);
108128 ** Close an existing SQLite database
108130 SQLITE_API int sqlite3_close(sqlite3 *db){
108131 HashElem *i; /* Hash table iterator */
108132 int j;
108134 if( !db ){
108135 return SQLITE_OK;
108137 if( !sqlite3SafetyCheckSickOrOk(db) ){
108138 return SQLITE_MISUSE_BKPT;
108140 sqlite3_mutex_enter(db->mutex);
108142 /* Force xDestroy calls on all virtual tables */
108143 sqlite3ResetInternalSchema(db, -1);
108145 /* If a transaction is open, the ResetInternalSchema() call above
108146 ** will not have called the xDisconnect() method on any virtual
108147 ** tables in the db->aVTrans[] array. The following sqlite3VtabRollback()
108148 ** call will do so. We need to do this before the check for active
108149 ** SQL statements below, as the v-table implementation may be storing
108150 ** some prepared statements internally.
108152 sqlite3VtabRollback(db);
108154 /* If there are any outstanding VMs, return SQLITE_BUSY. */
108155 if( db->pVdbe ){
108156 sqlite3Error(db, SQLITE_BUSY,
108157 "unable to close due to unfinalised statements");
108158 sqlite3_mutex_leave(db->mutex);
108159 return SQLITE_BUSY;
108161 assert( sqlite3SafetyCheckSickOrOk(db) );
108163 for(j=0; j<db->nDb; j++){
108164 Btree *pBt = db->aDb[j].pBt;
108165 if( pBt && sqlite3BtreeIsInBackup(pBt) ){
108166 sqlite3Error(db, SQLITE_BUSY,
108167 "unable to close due to unfinished backup operation");
108168 sqlite3_mutex_leave(db->mutex);
108169 return SQLITE_BUSY;
108173 /* Free any outstanding Savepoint structures. */
108174 sqlite3CloseSavepoints(db);
108176 for(j=0; j<db->nDb; j++){
108177 struct Db *pDb = &db->aDb[j];
108178 if( pDb->pBt ){
108179 sqlite3BtreeClose(pDb->pBt);
108180 pDb->pBt = 0;
108181 if( j!=1 ){
108182 pDb->pSchema = 0;
108186 sqlite3ResetInternalSchema(db, -1);
108188 /* Tell the code in notify.c that the connection no longer holds any
108189 ** locks and does not require any further unlock-notify callbacks.
108191 sqlite3ConnectionClosed(db);
108193 assert( db->nDb<=2 );
108194 assert( db->aDb==db->aDbStatic );
108195 for(j=0; j<ArraySize(db->aFunc.a); j++){
108196 FuncDef *pNext, *pHash, *p;
108197 for(p=db->aFunc.a[j]; p; p=pHash){
108198 pHash = p->pHash;
108199 while( p ){
108200 functionDestroy(db, p);
108201 pNext = p->pNext;
108202 sqlite3DbFree(db, p);
108203 p = pNext;
108207 for(i=sqliteHashFirst(&db->aCollSeq); i; i=sqliteHashNext(i)){
108208 CollSeq *pColl = (CollSeq *)sqliteHashData(i);
108209 /* Invoke any destructors registered for collation sequence user data. */
108210 for(j=0; j<3; j++){
108211 if( pColl[j].xDel ){
108212 pColl[j].xDel(pColl[j].pUser);
108215 sqlite3DbFree(db, pColl);
108217 sqlite3HashClear(&db->aCollSeq);
108218 #ifndef SQLITE_OMIT_VIRTUALTABLE
108219 for(i=sqliteHashFirst(&db->aModule); i; i=sqliteHashNext(i)){
108220 Module *pMod = (Module *)sqliteHashData(i);
108221 if( pMod->xDestroy ){
108222 pMod->xDestroy(pMod->pAux);
108224 sqlite3DbFree(db, pMod);
108226 sqlite3HashClear(&db->aModule);
108227 #endif
108229 sqlite3Error(db, SQLITE_OK, 0); /* Deallocates any cached error strings. */
108230 if( db->pErr ){
108231 sqlite3ValueFree(db->pErr);
108233 sqlite3CloseExtensions(db);
108235 db->magic = SQLITE_MAGIC_ERROR;
108237 /* The temp-database schema is allocated differently from the other schema
108238 ** objects (using sqliteMalloc() directly, instead of sqlite3BtreeSchema()).
108239 ** So it needs to be freed here. Todo: Why not roll the temp schema into
108240 ** the same sqliteMalloc() as the one that allocates the database
108241 ** structure?
108243 sqlite3DbFree(db, db->aDb[1].pSchema);
108244 sqlite3_mutex_leave(db->mutex);
108245 db->magic = SQLITE_MAGIC_CLOSED;
108246 sqlite3_mutex_free(db->mutex);
108247 assert( db->lookaside.nOut==0 ); /* Fails on a lookaside memory leak */
108248 if( db->lookaside.bMalloced ){
108249 sqlite3_free(db->lookaside.pStart);
108251 sqlite3_free(db);
108252 return SQLITE_OK;
108256 ** Rollback all database files.
108258 SQLITE_PRIVATE void sqlite3RollbackAll(sqlite3 *db){
108259 int i;
108260 int inTrans = 0;
108261 assert( sqlite3_mutex_held(db->mutex) );
108262 sqlite3BeginBenignMalloc();
108263 for(i=0; i<db->nDb; i++){
108264 if( db->aDb[i].pBt ){
108265 if( sqlite3BtreeIsInTrans(db->aDb[i].pBt) ){
108266 inTrans = 1;
108268 sqlite3BtreeRollback(db->aDb[i].pBt);
108269 db->aDb[i].inTrans = 0;
108272 sqlite3VtabRollback(db);
108273 sqlite3EndBenignMalloc();
108275 if( db->flags&SQLITE_InternChanges ){
108276 sqlite3ExpirePreparedStatements(db);
108277 sqlite3ResetInternalSchema(db, -1);
108280 /* Any deferred constraint violations have now been resolved. */
108281 db->nDeferredCons = 0;
108283 /* If one has been configured, invoke the rollback-hook callback */
108284 if( db->xRollbackCallback && (inTrans || !db->autoCommit) ){
108285 db->xRollbackCallback(db->pRollbackArg);
108290 ** Return a static string that describes the kind of error specified in the
108291 ** argument.
108293 SQLITE_PRIVATE const char *sqlite3ErrStr(int rc){
108294 static const char* const aMsg[] = {
108295 /* SQLITE_OK */ "not an error",
108296 /* SQLITE_ERROR */ "SQL logic error or missing database",
108297 /* SQLITE_INTERNAL */ 0,
108298 /* SQLITE_PERM */ "access permission denied",
108299 /* SQLITE_ABORT */ "callback requested query abort",
108300 /* SQLITE_BUSY */ "database is locked",
108301 /* SQLITE_LOCKED */ "database table is locked",
108302 /* SQLITE_NOMEM */ "out of memory",
108303 /* SQLITE_READONLY */ "attempt to write a readonly database",
108304 /* SQLITE_INTERRUPT */ "interrupted",
108305 /* SQLITE_IOERR */ "disk I/O error",
108306 /* SQLITE_CORRUPT */ "database disk image is malformed",
108307 /* SQLITE_NOTFOUND */ "unknown operation",
108308 /* SQLITE_FULL */ "database or disk is full",
108309 /* SQLITE_CANTOPEN */ "unable to open database file",
108310 /* SQLITE_PROTOCOL */ "locking protocol",
108311 /* SQLITE_EMPTY */ "table contains no data",
108312 /* SQLITE_SCHEMA */ "database schema has changed",
108313 /* SQLITE_TOOBIG */ "string or blob too big",
108314 /* SQLITE_CONSTRAINT */ "constraint failed",
108315 /* SQLITE_MISMATCH */ "datatype mismatch",
108316 /* SQLITE_MISUSE */ "library routine called out of sequence",
108317 /* SQLITE_NOLFS */ "large file support is disabled",
108318 /* SQLITE_AUTH */ "authorization denied",
108319 /* SQLITE_FORMAT */ "auxiliary database format error",
108320 /* SQLITE_RANGE */ "bind or column index out of range",
108321 /* SQLITE_NOTADB */ "file is encrypted or is not a database",
108323 rc &= 0xff;
108324 if( ALWAYS(rc>=0) && rc<(int)(sizeof(aMsg)/sizeof(aMsg[0])) && aMsg[rc]!=0 ){
108325 return aMsg[rc];
108326 }else{
108327 return "unknown error";
108332 ** This routine implements a busy callback that sleeps and tries
108333 ** again until a timeout value is reached. The timeout value is
108334 ** an integer number of milliseconds passed in as the first
108335 ** argument.
108337 static int sqliteDefaultBusyCallback(
108338 void *ptr, /* Database connection */
108339 int count /* Number of times table has been busy */
108341 #if SQLITE_OS_WIN || (defined(HAVE_USLEEP) && HAVE_USLEEP)
108342 static const u8 delays[] =
108343 { 1, 2, 5, 10, 15, 20, 25, 25, 25, 50, 50, 100 };
108344 static const u8 totals[] =
108345 { 0, 1, 3, 8, 18, 33, 53, 78, 103, 128, 178, 228 };
108346 # define NDELAY ArraySize(delays)
108347 sqlite3 *db = (sqlite3 *)ptr;
108348 int timeout = db->busyTimeout;
108349 int delay, prior;
108351 assert( count>=0 );
108352 if( count < NDELAY ){
108353 delay = delays[count];
108354 prior = totals[count];
108355 }else{
108356 delay = delays[NDELAY-1];
108357 prior = totals[NDELAY-1] + delay*(count-(NDELAY-1));
108359 if( prior + delay > timeout ){
108360 delay = timeout - prior;
108361 if( delay<=0 ) return 0;
108363 sqlite3OsSleep(db->pVfs, delay*1000);
108364 return 1;
108365 #else
108366 sqlite3 *db = (sqlite3 *)ptr;
108367 int timeout = ((sqlite3 *)ptr)->busyTimeout;
108368 if( (count+1)*1000 > timeout ){
108369 return 0;
108371 sqlite3OsSleep(db->pVfs, 1000000);
108372 return 1;
108373 #endif
108377 ** Invoke the given busy handler.
108379 ** This routine is called when an operation failed with a lock.
108380 ** If this routine returns non-zero, the lock is retried. If it
108381 ** returns 0, the operation aborts with an SQLITE_BUSY error.
108383 SQLITE_PRIVATE int sqlite3InvokeBusyHandler(BusyHandler *p){
108384 int rc;
108385 if( NEVER(p==0) || p->xFunc==0 || p->nBusy<0 ) return 0;
108386 rc = p->xFunc(p->pArg, p->nBusy);
108387 if( rc==0 ){
108388 p->nBusy = -1;
108389 }else{
108390 p->nBusy++;
108392 return rc;
108396 ** This routine sets the busy callback for an Sqlite database to the
108397 ** given callback function with the given argument.
108399 SQLITE_API int sqlite3_busy_handler(
108400 sqlite3 *db,
108401 int (*xBusy)(void*,int),
108402 void *pArg
108404 sqlite3_mutex_enter(db->mutex);
108405 db->busyHandler.xFunc = xBusy;
108406 db->busyHandler.pArg = pArg;
108407 db->busyHandler.nBusy = 0;
108408 sqlite3_mutex_leave(db->mutex);
108409 return SQLITE_OK;
108412 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
108414 ** This routine sets the progress callback for an Sqlite database to the
108415 ** given callback function with the given argument. The progress callback will
108416 ** be invoked every nOps opcodes.
108418 SQLITE_API void sqlite3_progress_handler(
108419 sqlite3 *db,
108420 int nOps,
108421 int (*xProgress)(void*),
108422 void *pArg
108424 sqlite3_mutex_enter(db->mutex);
108425 if( nOps>0 ){
108426 db->xProgress = xProgress;
108427 db->nProgressOps = nOps;
108428 db->pProgressArg = pArg;
108429 }else{
108430 db->xProgress = 0;
108431 db->nProgressOps = 0;
108432 db->pProgressArg = 0;
108434 sqlite3_mutex_leave(db->mutex);
108436 #endif
108440 ** This routine installs a default busy handler that waits for the
108441 ** specified number of milliseconds before returning 0.
108443 SQLITE_API int sqlite3_busy_timeout(sqlite3 *db, int ms){
108444 if( ms>0 ){
108445 db->busyTimeout = ms;
108446 sqlite3_busy_handler(db, sqliteDefaultBusyCallback, (void*)db);
108447 }else{
108448 sqlite3_busy_handler(db, 0, 0);
108450 return SQLITE_OK;
108454 ** Cause any pending operation to stop at its earliest opportunity.
108456 SQLITE_API void sqlite3_interrupt(sqlite3 *db){
108457 db->u1.isInterrupted = 1;
108462 ** This function is exactly the same as sqlite3_create_function(), except
108463 ** that it is designed to be called by internal code. The difference is
108464 ** that if a malloc() fails in sqlite3_create_function(), an error code
108465 ** is returned and the mallocFailed flag cleared.
108467 SQLITE_PRIVATE int sqlite3CreateFunc(
108468 sqlite3 *db,
108469 const char *zFunctionName,
108470 int nArg,
108471 int enc,
108472 void *pUserData,
108473 void (*xFunc)(sqlite3_context*,int,sqlite3_value **),
108474 void (*xStep)(sqlite3_context*,int,sqlite3_value **),
108475 void (*xFinal)(sqlite3_context*),
108476 FuncDestructor *pDestructor
108478 FuncDef *p;
108479 int nName;
108481 assert( sqlite3_mutex_held(db->mutex) );
108482 if( zFunctionName==0 ||
108483 (xFunc && (xFinal || xStep)) ||
108484 (!xFunc && (xFinal && !xStep)) ||
108485 (!xFunc && (!xFinal && xStep)) ||
108486 (nArg<-1 || nArg>SQLITE_MAX_FUNCTION_ARG) ||
108487 (255<(nName = sqlite3Strlen30( zFunctionName))) ){
108488 return SQLITE_MISUSE_BKPT;
108491 #ifndef SQLITE_OMIT_UTF16
108492 /* If SQLITE_UTF16 is specified as the encoding type, transform this
108493 ** to one of SQLITE_UTF16LE or SQLITE_UTF16BE using the
108494 ** SQLITE_UTF16NATIVE macro. SQLITE_UTF16 is not used internally.
108496 ** If SQLITE_ANY is specified, add three versions of the function
108497 ** to the hash table.
108499 if( enc==SQLITE_UTF16 ){
108500 enc = SQLITE_UTF16NATIVE;
108501 }else if( enc==SQLITE_ANY ){
108502 int rc;
108503 rc = sqlite3CreateFunc(db, zFunctionName, nArg, SQLITE_UTF8,
108504 pUserData, xFunc, xStep, xFinal, pDestructor);
108505 if( rc==SQLITE_OK ){
108506 rc = sqlite3CreateFunc(db, zFunctionName, nArg, SQLITE_UTF16LE,
108507 pUserData, xFunc, xStep, xFinal, pDestructor);
108509 if( rc!=SQLITE_OK ){
108510 return rc;
108512 enc = SQLITE_UTF16BE;
108514 #else
108515 enc = SQLITE_UTF8;
108516 #endif
108518 /* Check if an existing function is being overridden or deleted. If so,
108519 ** and there are active VMs, then return SQLITE_BUSY. If a function
108520 ** is being overridden/deleted but there are no active VMs, allow the
108521 ** operation to continue but invalidate all precompiled statements.
108523 p = sqlite3FindFunction(db, zFunctionName, nName, nArg, (u8)enc, 0);
108524 if( p && p->iPrefEnc==enc && p->nArg==nArg ){
108525 if( db->activeVdbeCnt ){
108526 sqlite3Error(db, SQLITE_BUSY,
108527 "unable to delete/modify user-function due to active statements");
108528 assert( !db->mallocFailed );
108529 return SQLITE_BUSY;
108530 }else{
108531 sqlite3ExpirePreparedStatements(db);
108535 p = sqlite3FindFunction(db, zFunctionName, nName, nArg, (u8)enc, 1);
108536 assert(p || db->mallocFailed);
108537 if( !p ){
108538 return SQLITE_NOMEM;
108541 /* If an older version of the function with a configured destructor is
108542 ** being replaced invoke the destructor function here. */
108543 functionDestroy(db, p);
108545 if( pDestructor ){
108546 pDestructor->nRef++;
108548 p->pDestructor = pDestructor;
108549 p->flags = 0;
108550 p->xFunc = xFunc;
108551 p->xStep = xStep;
108552 p->xFinalize = xFinal;
108553 p->pUserData = pUserData;
108554 p->nArg = (u16)nArg;
108555 return SQLITE_OK;
108559 ** Create new user functions.
108561 SQLITE_API int sqlite3_create_function(
108562 sqlite3 *db,
108563 const char *zFunc,
108564 int nArg,
108565 int enc,
108566 void *p,
108567 void (*xFunc)(sqlite3_context*,int,sqlite3_value **),
108568 void (*xStep)(sqlite3_context*,int,sqlite3_value **),
108569 void (*xFinal)(sqlite3_context*)
108571 return sqlite3_create_function_v2(db, zFunc, nArg, enc, p, xFunc, xStep,
108572 xFinal, 0);
108575 SQLITE_API int sqlite3_create_function_v2(
108576 sqlite3 *db,
108577 const char *zFunc,
108578 int nArg,
108579 int enc,
108580 void *p,
108581 void (*xFunc)(sqlite3_context*,int,sqlite3_value **),
108582 void (*xStep)(sqlite3_context*,int,sqlite3_value **),
108583 void (*xFinal)(sqlite3_context*),
108584 void (*xDestroy)(void *)
108586 int rc = SQLITE_ERROR;
108587 FuncDestructor *pArg = 0;
108588 sqlite3_mutex_enter(db->mutex);
108589 if( xDestroy ){
108590 pArg = (FuncDestructor *)sqlite3DbMallocZero(db, sizeof(FuncDestructor));
108591 if( !pArg ){
108592 xDestroy(p);
108593 goto out;
108595 pArg->xDestroy = xDestroy;
108596 pArg->pUserData = p;
108598 rc = sqlite3CreateFunc(db, zFunc, nArg, enc, p, xFunc, xStep, xFinal, pArg);
108599 if( pArg && pArg->nRef==0 ){
108600 assert( rc!=SQLITE_OK );
108601 xDestroy(p);
108602 sqlite3DbFree(db, pArg);
108606 rc = sqlite3ApiExit(db, rc);
108607 sqlite3_mutex_leave(db->mutex);
108608 return rc;
108611 #ifndef SQLITE_OMIT_UTF16
108612 SQLITE_API int sqlite3_create_function16(
108613 sqlite3 *db,
108614 const void *zFunctionName,
108615 int nArg,
108616 int eTextRep,
108617 void *p,
108618 void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
108619 void (*xStep)(sqlite3_context*,int,sqlite3_value**),
108620 void (*xFinal)(sqlite3_context*)
108622 int rc;
108623 char *zFunc8;
108624 sqlite3_mutex_enter(db->mutex);
108625 assert( !db->mallocFailed );
108626 zFunc8 = sqlite3Utf16to8(db, zFunctionName, -1, SQLITE_UTF16NATIVE);
108627 rc = sqlite3CreateFunc(db, zFunc8, nArg, eTextRep, p, xFunc, xStep, xFinal,0);
108628 sqlite3DbFree(db, zFunc8);
108629 rc = sqlite3ApiExit(db, rc);
108630 sqlite3_mutex_leave(db->mutex);
108631 return rc;
108633 #endif
108637 ** Declare that a function has been overloaded by a virtual table.
108639 ** If the function already exists as a regular global function, then
108640 ** this routine is a no-op. If the function does not exist, then create
108641 ** a new one that always throws a run-time error.
108643 ** When virtual tables intend to provide an overloaded function, they
108644 ** should call this routine to make sure the global function exists.
108645 ** A global function must exist in order for name resolution to work
108646 ** properly.
108648 SQLITE_API int sqlite3_overload_function(
108649 sqlite3 *db,
108650 const char *zName,
108651 int nArg
108653 int nName = sqlite3Strlen30(zName);
108654 int rc;
108655 sqlite3_mutex_enter(db->mutex);
108656 if( sqlite3FindFunction(db, zName, nName, nArg, SQLITE_UTF8, 0)==0 ){
108657 sqlite3CreateFunc(db, zName, nArg, SQLITE_UTF8,
108658 0, sqlite3InvalidFunction, 0, 0, 0);
108660 rc = sqlite3ApiExit(db, SQLITE_OK);
108661 sqlite3_mutex_leave(db->mutex);
108662 return rc;
108665 #ifndef SQLITE_OMIT_TRACE
108667 ** Register a trace function. The pArg from the previously registered trace
108668 ** is returned.
108670 ** A NULL trace function means that no tracing is executes. A non-NULL
108671 ** trace is a pointer to a function that is invoked at the start of each
108672 ** SQL statement.
108674 SQLITE_API void *sqlite3_trace(sqlite3 *db, void (*xTrace)(void*,const char*), void *pArg){
108675 void *pOld;
108676 sqlite3_mutex_enter(db->mutex);
108677 pOld = db->pTraceArg;
108678 db->xTrace = xTrace;
108679 db->pTraceArg = pArg;
108680 sqlite3_mutex_leave(db->mutex);
108681 return pOld;
108684 ** Register a profile function. The pArg from the previously registered
108685 ** profile function is returned.
108687 ** A NULL profile function means that no profiling is executes. A non-NULL
108688 ** profile is a pointer to a function that is invoked at the conclusion of
108689 ** each SQL statement that is run.
108691 SQLITE_API void *sqlite3_profile(
108692 sqlite3 *db,
108693 void (*xProfile)(void*,const char*,sqlite_uint64),
108694 void *pArg
108696 void *pOld;
108697 sqlite3_mutex_enter(db->mutex);
108698 pOld = db->pProfileArg;
108699 db->xProfile = xProfile;
108700 db->pProfileArg = pArg;
108701 sqlite3_mutex_leave(db->mutex);
108702 return pOld;
108704 #endif /* SQLITE_OMIT_TRACE */
108706 /*** EXPERIMENTAL ***
108708 ** Register a function to be invoked when a transaction comments.
108709 ** If the invoked function returns non-zero, then the commit becomes a
108710 ** rollback.
108712 SQLITE_API void *sqlite3_commit_hook(
108713 sqlite3 *db, /* Attach the hook to this database */
108714 int (*xCallback)(void*), /* Function to invoke on each commit */
108715 void *pArg /* Argument to the function */
108717 void *pOld;
108718 sqlite3_mutex_enter(db->mutex);
108719 pOld = db->pCommitArg;
108720 db->xCommitCallback = xCallback;
108721 db->pCommitArg = pArg;
108722 sqlite3_mutex_leave(db->mutex);
108723 return pOld;
108727 ** Register a callback to be invoked each time a row is updated,
108728 ** inserted or deleted using this database connection.
108730 SQLITE_API void *sqlite3_update_hook(
108731 sqlite3 *db, /* Attach the hook to this database */
108732 void (*xCallback)(void*,int,char const *,char const *,sqlite_int64),
108733 void *pArg /* Argument to the function */
108735 void *pRet;
108736 sqlite3_mutex_enter(db->mutex);
108737 pRet = db->pUpdateArg;
108738 db->xUpdateCallback = xCallback;
108739 db->pUpdateArg = pArg;
108740 sqlite3_mutex_leave(db->mutex);
108741 return pRet;
108745 ** Register a callback to be invoked each time a transaction is rolled
108746 ** back by this database connection.
108748 SQLITE_API void *sqlite3_rollback_hook(
108749 sqlite3 *db, /* Attach the hook to this database */
108750 void (*xCallback)(void*), /* Callback function */
108751 void *pArg /* Argument to the function */
108753 void *pRet;
108754 sqlite3_mutex_enter(db->mutex);
108755 pRet = db->pRollbackArg;
108756 db->xRollbackCallback = xCallback;
108757 db->pRollbackArg = pArg;
108758 sqlite3_mutex_leave(db->mutex);
108759 return pRet;
108762 #ifndef SQLITE_OMIT_WAL
108764 ** The sqlite3_wal_hook() callback registered by sqlite3_wal_autocheckpoint().
108765 ** Invoke sqlite3_wal_checkpoint if the number of frames in the log file
108766 ** is greater than sqlite3.pWalArg cast to an integer (the value configured by
108767 ** wal_autocheckpoint()).
108769 SQLITE_PRIVATE int sqlite3WalDefaultHook(
108770 void *pClientData, /* Argument */
108771 sqlite3 *db, /* Connection */
108772 const char *zDb, /* Database */
108773 int nFrame /* Size of WAL */
108775 if( nFrame>=SQLITE_PTR_TO_INT(pClientData) ){
108776 sqlite3BeginBenignMalloc();
108777 sqlite3_wal_checkpoint(db, zDb);
108778 sqlite3EndBenignMalloc();
108780 return SQLITE_OK;
108782 #endif /* SQLITE_OMIT_WAL */
108785 ** Configure an sqlite3_wal_hook() callback to automatically checkpoint
108786 ** a database after committing a transaction if there are nFrame or
108787 ** more frames in the log file. Passing zero or a negative value as the
108788 ** nFrame parameter disables automatic checkpoints entirely.
108790 ** The callback registered by this function replaces any existing callback
108791 ** registered using sqlite3_wal_hook(). Likewise, registering a callback
108792 ** using sqlite3_wal_hook() disables the automatic checkpoint mechanism
108793 ** configured by this function.
108795 SQLITE_API int sqlite3_wal_autocheckpoint(sqlite3 *db, int nFrame){
108796 #ifdef SQLITE_OMIT_WAL
108797 UNUSED_PARAMETER(db);
108798 UNUSED_PARAMETER(nFrame);
108799 #else
108800 if( nFrame>0 ){
108801 sqlite3_wal_hook(db, sqlite3WalDefaultHook, SQLITE_INT_TO_PTR(nFrame));
108802 }else{
108803 sqlite3_wal_hook(db, 0, 0);
108805 #endif
108806 return SQLITE_OK;
108810 ** Register a callback to be invoked each time a transaction is written
108811 ** into the write-ahead-log by this database connection.
108813 SQLITE_API void *sqlite3_wal_hook(
108814 sqlite3 *db, /* Attach the hook to this db handle */
108815 int(*xCallback)(void *, sqlite3*, const char*, int),
108816 void *pArg /* First argument passed to xCallback() */
108818 #ifndef SQLITE_OMIT_WAL
108819 void *pRet;
108820 sqlite3_mutex_enter(db->mutex);
108821 pRet = db->pWalArg;
108822 db->xWalCallback = xCallback;
108823 db->pWalArg = pArg;
108824 sqlite3_mutex_leave(db->mutex);
108825 return pRet;
108826 #else
108827 return 0;
108828 #endif
108832 ** Checkpoint database zDb.
108834 SQLITE_API int sqlite3_wal_checkpoint_v2(
108835 sqlite3 *db, /* Database handle */
108836 const char *zDb, /* Name of attached database (or NULL) */
108837 int eMode, /* SQLITE_CHECKPOINT_* value */
108838 int *pnLog, /* OUT: Size of WAL log in frames */
108839 int *pnCkpt /* OUT: Total number of frames checkpointed */
108841 #ifdef SQLITE_OMIT_WAL
108842 return SQLITE_OK;
108843 #else
108844 int rc; /* Return code */
108845 int iDb = SQLITE_MAX_ATTACHED; /* sqlite3.aDb[] index of db to checkpoint */
108847 /* Initialize the output variables to -1 in case an error occurs. */
108848 if( pnLog ) *pnLog = -1;
108849 if( pnCkpt ) *pnCkpt = -1;
108851 assert( SQLITE_CHECKPOINT_FULL>SQLITE_CHECKPOINT_PASSIVE );
108852 assert( SQLITE_CHECKPOINT_FULL<SQLITE_CHECKPOINT_RESTART );
108853 assert( SQLITE_CHECKPOINT_PASSIVE+2==SQLITE_CHECKPOINT_RESTART );
108854 if( eMode<SQLITE_CHECKPOINT_PASSIVE || eMode>SQLITE_CHECKPOINT_RESTART ){
108855 return SQLITE_MISUSE;
108858 sqlite3_mutex_enter(db->mutex);
108859 if( zDb && zDb[0] ){
108860 iDb = sqlite3FindDbName(db, zDb);
108862 if( iDb<0 ){
108863 rc = SQLITE_ERROR;
108864 sqlite3Error(db, SQLITE_ERROR, "unknown database: %s", zDb);
108865 }else{
108866 rc = sqlite3Checkpoint(db, iDb, eMode, pnLog, pnCkpt);
108867 sqlite3Error(db, rc, 0);
108869 rc = sqlite3ApiExit(db, rc);
108870 sqlite3_mutex_leave(db->mutex);
108871 return rc;
108872 #endif
108877 ** Checkpoint database zDb. If zDb is NULL, or if the buffer zDb points
108878 ** to contains a zero-length string, all attached databases are
108879 ** checkpointed.
108881 SQLITE_API int sqlite3_wal_checkpoint(sqlite3 *db, const char *zDb){
108882 return sqlite3_wal_checkpoint_v2(db, zDb, SQLITE_CHECKPOINT_PASSIVE, 0, 0);
108885 #ifndef SQLITE_OMIT_WAL
108887 ** Run a checkpoint on database iDb. This is a no-op if database iDb is
108888 ** not currently open in WAL mode.
108890 ** If a transaction is open on the database being checkpointed, this
108891 ** function returns SQLITE_LOCKED and a checkpoint is not attempted. If
108892 ** an error occurs while running the checkpoint, an SQLite error code is
108893 ** returned (i.e. SQLITE_IOERR). Otherwise, SQLITE_OK.
108895 ** The mutex on database handle db should be held by the caller. The mutex
108896 ** associated with the specific b-tree being checkpointed is taken by
108897 ** this function while the checkpoint is running.
108899 ** If iDb is passed SQLITE_MAX_ATTACHED, then all attached databases are
108900 ** checkpointed. If an error is encountered it is returned immediately -
108901 ** no attempt is made to checkpoint any remaining databases.
108903 ** Parameter eMode is one of SQLITE_CHECKPOINT_PASSIVE, FULL or RESTART.
108905 SQLITE_PRIVATE int sqlite3Checkpoint(sqlite3 *db, int iDb, int eMode, int *pnLog, int *pnCkpt){
108906 int rc = SQLITE_OK; /* Return code */
108907 int i; /* Used to iterate through attached dbs */
108908 int bBusy = 0; /* True if SQLITE_BUSY has been encountered */
108910 assert( sqlite3_mutex_held(db->mutex) );
108911 assert( !pnLog || *pnLog==-1 );
108912 assert( !pnCkpt || *pnCkpt==-1 );
108914 for(i=0; i<db->nDb && rc==SQLITE_OK; i++){
108915 if( i==iDb || iDb==SQLITE_MAX_ATTACHED ){
108916 rc = sqlite3BtreeCheckpoint(db->aDb[i].pBt, eMode, pnLog, pnCkpt);
108917 pnLog = 0;
108918 pnCkpt = 0;
108919 if( rc==SQLITE_BUSY ){
108920 bBusy = 1;
108921 rc = SQLITE_OK;
108926 return (rc==SQLITE_OK && bBusy) ? SQLITE_BUSY : rc;
108928 #endif /* SQLITE_OMIT_WAL */
108931 ** This function returns true if main-memory should be used instead of
108932 ** a temporary file for transient pager files and statement journals.
108933 ** The value returned depends on the value of db->temp_store (runtime
108934 ** parameter) and the compile time value of SQLITE_TEMP_STORE. The
108935 ** following table describes the relationship between these two values
108936 ** and this functions return value.
108938 ** SQLITE_TEMP_STORE db->temp_store Location of temporary database
108939 ** ----------------- -------------- ------------------------------
108940 ** 0 any file (return 0)
108941 ** 1 1 file (return 0)
108942 ** 1 2 memory (return 1)
108943 ** 1 0 file (return 0)
108944 ** 2 1 file (return 0)
108945 ** 2 2 memory (return 1)
108946 ** 2 0 memory (return 1)
108947 ** 3 any memory (return 1)
108949 SQLITE_PRIVATE int sqlite3TempInMemory(const sqlite3 *db){
108950 #if SQLITE_TEMP_STORE==1
108951 return ( db->temp_store==2 );
108952 #endif
108953 #if SQLITE_TEMP_STORE==2
108954 return ( db->temp_store!=1 );
108955 #endif
108956 #if SQLITE_TEMP_STORE==3
108957 return 1;
108958 #endif
108959 #if SQLITE_TEMP_STORE<1 || SQLITE_TEMP_STORE>3
108960 return 0;
108961 #endif
108965 ** Return UTF-8 encoded English language explanation of the most recent
108966 ** error.
108968 SQLITE_API const char *sqlite3_errmsg(sqlite3 *db){
108969 const char *z;
108970 if( !db ){
108971 return sqlite3ErrStr(SQLITE_NOMEM);
108973 if( !sqlite3SafetyCheckSickOrOk(db) ){
108974 return sqlite3ErrStr(SQLITE_MISUSE_BKPT);
108976 sqlite3_mutex_enter(db->mutex);
108977 if( db->mallocFailed ){
108978 z = sqlite3ErrStr(SQLITE_NOMEM);
108979 }else{
108980 z = (char*)sqlite3_value_text(db->pErr);
108981 assert( !db->mallocFailed );
108982 if( z==0 ){
108983 z = sqlite3ErrStr(db->errCode);
108986 sqlite3_mutex_leave(db->mutex);
108987 return z;
108990 #ifndef SQLITE_OMIT_UTF16
108992 ** Return UTF-16 encoded English language explanation of the most recent
108993 ** error.
108995 SQLITE_API const void *sqlite3_errmsg16(sqlite3 *db){
108996 static const u16 outOfMem[] = {
108997 'o', 'u', 't', ' ', 'o', 'f', ' ', 'm', 'e', 'm', 'o', 'r', 'y', 0
108999 static const u16 misuse[] = {
109000 'l', 'i', 'b', 'r', 'a', 'r', 'y', ' ',
109001 'r', 'o', 'u', 't', 'i', 'n', 'e', ' ',
109002 'c', 'a', 'l', 'l', 'e', 'd', ' ',
109003 'o', 'u', 't', ' ',
109004 'o', 'f', ' ',
109005 's', 'e', 'q', 'u', 'e', 'n', 'c', 'e', 0
109008 const void *z;
109009 if( !db ){
109010 return (void *)outOfMem;
109012 if( !sqlite3SafetyCheckSickOrOk(db) ){
109013 return (void *)misuse;
109015 sqlite3_mutex_enter(db->mutex);
109016 if( db->mallocFailed ){
109017 z = (void *)outOfMem;
109018 }else{
109019 z = sqlite3_value_text16(db->pErr);
109020 if( z==0 ){
109021 sqlite3ValueSetStr(db->pErr, -1, sqlite3ErrStr(db->errCode),
109022 SQLITE_UTF8, SQLITE_STATIC);
109023 z = sqlite3_value_text16(db->pErr);
109025 /* A malloc() may have failed within the call to sqlite3_value_text16()
109026 ** above. If this is the case, then the db->mallocFailed flag needs to
109027 ** be cleared before returning. Do this directly, instead of via
109028 ** sqlite3ApiExit(), to avoid setting the database handle error message.
109030 db->mallocFailed = 0;
109032 sqlite3_mutex_leave(db->mutex);
109033 return z;
109035 #endif /* SQLITE_OMIT_UTF16 */
109038 ** Return the most recent error code generated by an SQLite routine. If NULL is
109039 ** passed to this function, we assume a malloc() failed during sqlite3_open().
109041 SQLITE_API int sqlite3_errcode(sqlite3 *db){
109042 if( db && !sqlite3SafetyCheckSickOrOk(db) ){
109043 return SQLITE_MISUSE_BKPT;
109045 if( !db || db->mallocFailed ){
109046 return SQLITE_NOMEM;
109048 return db->errCode & db->errMask;
109050 SQLITE_API int sqlite3_extended_errcode(sqlite3 *db){
109051 if( db && !sqlite3SafetyCheckSickOrOk(db) ){
109052 return SQLITE_MISUSE_BKPT;
109054 if( !db || db->mallocFailed ){
109055 return SQLITE_NOMEM;
109057 return db->errCode;
109061 ** Create a new collating function for database "db". The name is zName
109062 ** and the encoding is enc.
109064 static int createCollation(
109065 sqlite3* db,
109066 const char *zName,
109067 u8 enc,
109068 u8 collType,
109069 void* pCtx,
109070 int(*xCompare)(void*,int,const void*,int,const void*),
109071 void(*xDel)(void*)
109073 CollSeq *pColl;
109074 int enc2;
109075 int nName = sqlite3Strlen30(zName);
109077 assert( sqlite3_mutex_held(db->mutex) );
109079 /* If SQLITE_UTF16 is specified as the encoding type, transform this
109080 ** to one of SQLITE_UTF16LE or SQLITE_UTF16BE using the
109081 ** SQLITE_UTF16NATIVE macro. SQLITE_UTF16 is not used internally.
109083 enc2 = enc;
109084 testcase( enc2==SQLITE_UTF16 );
109085 testcase( enc2==SQLITE_UTF16_ALIGNED );
109086 if( enc2==SQLITE_UTF16 || enc2==SQLITE_UTF16_ALIGNED ){
109087 enc2 = SQLITE_UTF16NATIVE;
109089 if( enc2<SQLITE_UTF8 || enc2>SQLITE_UTF16BE ){
109090 return SQLITE_MISUSE_BKPT;
109093 /* Check if this call is removing or replacing an existing collation
109094 ** sequence. If so, and there are active VMs, return busy. If there
109095 ** are no active VMs, invalidate any pre-compiled statements.
109097 pColl = sqlite3FindCollSeq(db, (u8)enc2, zName, 0);
109098 if( pColl && pColl->xCmp ){
109099 if( db->activeVdbeCnt ){
109100 sqlite3Error(db, SQLITE_BUSY,
109101 "unable to delete/modify collation sequence due to active statements");
109102 return SQLITE_BUSY;
109104 sqlite3ExpirePreparedStatements(db);
109106 /* If collation sequence pColl was created directly by a call to
109107 ** sqlite3_create_collation, and not generated by synthCollSeq(),
109108 ** then any copies made by synthCollSeq() need to be invalidated.
109109 ** Also, collation destructor - CollSeq.xDel() - function may need
109110 ** to be called.
109112 if( (pColl->enc & ~SQLITE_UTF16_ALIGNED)==enc2 ){
109113 CollSeq *aColl = sqlite3HashFind(&db->aCollSeq, zName, nName);
109114 int j;
109115 for(j=0; j<3; j++){
109116 CollSeq *p = &aColl[j];
109117 if( p->enc==pColl->enc ){
109118 if( p->xDel ){
109119 p->xDel(p->pUser);
109121 p->xCmp = 0;
109127 pColl = sqlite3FindCollSeq(db, (u8)enc2, zName, 1);
109128 if( pColl==0 ) return SQLITE_NOMEM;
109129 pColl->xCmp = xCompare;
109130 pColl->pUser = pCtx;
109131 pColl->xDel = xDel;
109132 pColl->enc = (u8)(enc2 | (enc & SQLITE_UTF16_ALIGNED));
109133 pColl->type = collType;
109134 sqlite3Error(db, SQLITE_OK, 0);
109135 return SQLITE_OK;
109140 ** This array defines hard upper bounds on limit values. The
109141 ** initializer must be kept in sync with the SQLITE_LIMIT_*
109142 ** #defines in sqlite3.h.
109144 static const int aHardLimit[] = {
109145 SQLITE_MAX_LENGTH,
109146 SQLITE_MAX_SQL_LENGTH,
109147 SQLITE_MAX_COLUMN,
109148 SQLITE_MAX_EXPR_DEPTH,
109149 SQLITE_MAX_COMPOUND_SELECT,
109150 SQLITE_MAX_VDBE_OP,
109151 SQLITE_MAX_FUNCTION_ARG,
109152 SQLITE_MAX_ATTACHED,
109153 SQLITE_MAX_LIKE_PATTERN_LENGTH,
109154 SQLITE_MAX_VARIABLE_NUMBER,
109155 SQLITE_MAX_TRIGGER_DEPTH,
109159 ** Make sure the hard limits are set to reasonable values
109161 #if SQLITE_MAX_LENGTH<100
109162 # error SQLITE_MAX_LENGTH must be at least 100
109163 #endif
109164 #if SQLITE_MAX_SQL_LENGTH<100
109165 # error SQLITE_MAX_SQL_LENGTH must be at least 100
109166 #endif
109167 #if SQLITE_MAX_SQL_LENGTH>SQLITE_MAX_LENGTH
109168 # error SQLITE_MAX_SQL_LENGTH must not be greater than SQLITE_MAX_LENGTH
109169 #endif
109170 #if SQLITE_MAX_COMPOUND_SELECT<2
109171 # error SQLITE_MAX_COMPOUND_SELECT must be at least 2
109172 #endif
109173 #if SQLITE_MAX_VDBE_OP<40
109174 # error SQLITE_MAX_VDBE_OP must be at least 40
109175 #endif
109176 #if SQLITE_MAX_FUNCTION_ARG<0 || SQLITE_MAX_FUNCTION_ARG>1000
109177 # error SQLITE_MAX_FUNCTION_ARG must be between 0 and 1000
109178 #endif
109179 #if SQLITE_MAX_ATTACHED<0 || SQLITE_MAX_ATTACHED>62
109180 # error SQLITE_MAX_ATTACHED must be between 0 and 62
109181 #endif
109182 #if SQLITE_MAX_LIKE_PATTERN_LENGTH<1
109183 # error SQLITE_MAX_LIKE_PATTERN_LENGTH must be at least 1
109184 #endif
109185 #if SQLITE_MAX_COLUMN>32767
109186 # error SQLITE_MAX_COLUMN must not exceed 32767
109187 #endif
109188 #if SQLITE_MAX_TRIGGER_DEPTH<1
109189 # error SQLITE_MAX_TRIGGER_DEPTH must be at least 1
109190 #endif
109194 ** Change the value of a limit. Report the old value.
109195 ** If an invalid limit index is supplied, report -1.
109196 ** Make no changes but still report the old value if the
109197 ** new limit is negative.
109199 ** A new lower limit does not shrink existing constructs.
109200 ** It merely prevents new constructs that exceed the limit
109201 ** from forming.
109203 SQLITE_API int sqlite3_limit(sqlite3 *db, int limitId, int newLimit){
109204 int oldLimit;
109207 /* EVIDENCE-OF: R-30189-54097 For each limit category SQLITE_LIMIT_NAME
109208 ** there is a hard upper bound set at compile-time by a C preprocessor
109209 ** macro called SQLITE_MAX_NAME. (The "_LIMIT_" in the name is changed to
109210 ** "_MAX_".)
109212 assert( aHardLimit[SQLITE_LIMIT_LENGTH]==SQLITE_MAX_LENGTH );
109213 assert( aHardLimit[SQLITE_LIMIT_SQL_LENGTH]==SQLITE_MAX_SQL_LENGTH );
109214 assert( aHardLimit[SQLITE_LIMIT_COLUMN]==SQLITE_MAX_COLUMN );
109215 assert( aHardLimit[SQLITE_LIMIT_EXPR_DEPTH]==SQLITE_MAX_EXPR_DEPTH );
109216 assert( aHardLimit[SQLITE_LIMIT_COMPOUND_SELECT]==SQLITE_MAX_COMPOUND_SELECT);
109217 assert( aHardLimit[SQLITE_LIMIT_VDBE_OP]==SQLITE_MAX_VDBE_OP );
109218 assert( aHardLimit[SQLITE_LIMIT_FUNCTION_ARG]==SQLITE_MAX_FUNCTION_ARG );
109219 assert( aHardLimit[SQLITE_LIMIT_ATTACHED]==SQLITE_MAX_ATTACHED );
109220 assert( aHardLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH]==
109221 SQLITE_MAX_LIKE_PATTERN_LENGTH );
109222 assert( aHardLimit[SQLITE_LIMIT_VARIABLE_NUMBER]==SQLITE_MAX_VARIABLE_NUMBER);
109223 assert( aHardLimit[SQLITE_LIMIT_TRIGGER_DEPTH]==SQLITE_MAX_TRIGGER_DEPTH );
109224 assert( SQLITE_LIMIT_TRIGGER_DEPTH==(SQLITE_N_LIMIT-1) );
109227 if( limitId<0 || limitId>=SQLITE_N_LIMIT ){
109228 return -1;
109230 oldLimit = db->aLimit[limitId];
109231 if( newLimit>=0 ){ /* IMP: R-52476-28732 */
109232 if( newLimit>aHardLimit[limitId] ){
109233 newLimit = aHardLimit[limitId]; /* IMP: R-51463-25634 */
109235 db->aLimit[limitId] = newLimit;
109237 return oldLimit; /* IMP: R-53341-35419 */
109241 ** This routine does the work of opening a database on behalf of
109242 ** sqlite3_open() and sqlite3_open16(). The database filename "zFilename"
109243 ** is UTF-8 encoded.
109245 static int openDatabase(
109246 const char *zFilename, /* Database filename UTF-8 encoded */
109247 sqlite3 **ppDb, /* OUT: Returned database handle */
109248 unsigned flags, /* Operational flags */
109249 const char *zVfs /* Name of the VFS to use */
109251 sqlite3 *db;
109252 int rc;
109253 int isThreadsafe;
109255 *ppDb = 0;
109256 #ifndef SQLITE_OMIT_AUTOINIT
109257 rc = sqlite3_initialize();
109258 if( rc ) return rc;
109259 #endif
109261 /* Only allow sensible combinations of bits in the flags argument.
109262 ** Throw an error if any non-sense combination is used. If we
109263 ** do not block illegal combinations here, it could trigger
109264 ** assert() statements in deeper layers. Sensible combinations
109265 ** are:
109267 ** 1: SQLITE_OPEN_READONLY
109268 ** 2: SQLITE_OPEN_READWRITE
109269 ** 6: SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE
109271 assert( SQLITE_OPEN_READONLY == 0x01 );
109272 assert( SQLITE_OPEN_READWRITE == 0x02 );
109273 assert( SQLITE_OPEN_CREATE == 0x04 );
109274 testcase( (1<<(flags&7))==0x02 ); /* READONLY */
109275 testcase( (1<<(flags&7))==0x04 ); /* READWRITE */
109276 testcase( (1<<(flags&7))==0x40 ); /* READWRITE | CREATE */
109277 if( ((1<<(flags&7)) & 0x46)==0 ) return SQLITE_MISUSE;
109279 if( sqlite3GlobalConfig.bCoreMutex==0 ){
109280 isThreadsafe = 0;
109281 }else if( flags & SQLITE_OPEN_NOMUTEX ){
109282 isThreadsafe = 0;
109283 }else if( flags & SQLITE_OPEN_FULLMUTEX ){
109284 isThreadsafe = 1;
109285 }else{
109286 isThreadsafe = sqlite3GlobalConfig.bFullMutex;
109288 if( flags & SQLITE_OPEN_PRIVATECACHE ){
109289 flags &= ~SQLITE_OPEN_SHAREDCACHE;
109290 }else if( sqlite3GlobalConfig.sharedCacheEnabled ){
109291 flags |= SQLITE_OPEN_SHAREDCACHE;
109294 /* Remove harmful bits from the flags parameter
109296 ** The SQLITE_OPEN_NOMUTEX and SQLITE_OPEN_FULLMUTEX flags were
109297 ** dealt with in the previous code block. Besides these, the only
109298 ** valid input flags for sqlite3_open_v2() are SQLITE_OPEN_READONLY,
109299 ** SQLITE_OPEN_READWRITE, SQLITE_OPEN_CREATE, SQLITE_OPEN_SHAREDCACHE,
109300 ** SQLITE_OPEN_PRIVATECACHE, and some reserved bits. Silently mask
109301 ** off all other flags.
109303 flags &= ~( SQLITE_OPEN_DELETEONCLOSE |
109304 SQLITE_OPEN_EXCLUSIVE |
109305 SQLITE_OPEN_MAIN_DB |
109306 SQLITE_OPEN_TEMP_DB |
109307 SQLITE_OPEN_TRANSIENT_DB |
109308 SQLITE_OPEN_MAIN_JOURNAL |
109309 SQLITE_OPEN_TEMP_JOURNAL |
109310 SQLITE_OPEN_SUBJOURNAL |
109311 SQLITE_OPEN_MASTER_JOURNAL |
109312 SQLITE_OPEN_NOMUTEX |
109313 SQLITE_OPEN_FULLMUTEX |
109314 SQLITE_OPEN_WAL
109317 /* Allocate the sqlite data structure */
109318 db = sqlite3MallocZero( sizeof(sqlite3) );
109319 if( db==0 ) goto opendb_out;
109320 if( isThreadsafe ){
109321 db->mutex = sqlite3MutexAlloc(SQLITE_MUTEX_RECURSIVE);
109322 if( db->mutex==0 ){
109323 sqlite3_free(db);
109324 db = 0;
109325 goto opendb_out;
109328 sqlite3_mutex_enter(db->mutex);
109329 db->errMask = 0xff;
109330 db->nDb = 2;
109331 db->magic = SQLITE_MAGIC_BUSY;
109332 db->aDb = db->aDbStatic;
109334 assert( sizeof(db->aLimit)==sizeof(aHardLimit) );
109335 memcpy(db->aLimit, aHardLimit, sizeof(db->aLimit));
109336 db->autoCommit = 1;
109337 db->nextAutovac = -1;
109338 db->nextPagesize = 0;
109339 db->flags |= SQLITE_ShortColNames | SQLITE_AutoIndex | SQLITE_EnableTrigger
109340 #if SQLITE_DEFAULT_FILE_FORMAT<4
109341 | SQLITE_LegacyFileFmt
109342 #endif
109343 #ifdef SQLITE_ENABLE_LOAD_EXTENSION
109344 | SQLITE_LoadExtension
109345 #endif
109346 #if SQLITE_DEFAULT_RECURSIVE_TRIGGERS
109347 | SQLITE_RecTriggers
109348 #endif
109349 #if defined(SQLITE_DEFAULT_FOREIGN_KEYS) && SQLITE_DEFAULT_FOREIGN_KEYS
109350 | SQLITE_ForeignKeys
109351 #endif
109353 sqlite3HashInit(&db->aCollSeq);
109354 #ifndef SQLITE_OMIT_VIRTUALTABLE
109355 sqlite3HashInit(&db->aModule);
109356 #endif
109358 db->pVfs = sqlite3_vfs_find(zVfs);
109359 if( !db->pVfs ){
109360 rc = SQLITE_ERROR;
109361 sqlite3Error(db, rc, "no such vfs: %s", zVfs);
109362 goto opendb_out;
109365 /* Add the default collation sequence BINARY. BINARY works for both UTF-8
109366 ** and UTF-16, so add a version for each to avoid any unnecessary
109367 ** conversions. The only error that can occur here is a malloc() failure.
109369 createCollation(db, "BINARY", SQLITE_UTF8, SQLITE_COLL_BINARY, 0,
109370 binCollFunc, 0);
109371 createCollation(db, "BINARY", SQLITE_UTF16BE, SQLITE_COLL_BINARY, 0,
109372 binCollFunc, 0);
109373 createCollation(db, "BINARY", SQLITE_UTF16LE, SQLITE_COLL_BINARY, 0,
109374 binCollFunc, 0);
109375 createCollation(db, "RTRIM", SQLITE_UTF8, SQLITE_COLL_USER, (void*)1,
109376 binCollFunc, 0);
109377 if( db->mallocFailed ){
109378 goto opendb_out;
109380 db->pDfltColl = sqlite3FindCollSeq(db, SQLITE_UTF8, "BINARY", 0);
109381 assert( db->pDfltColl!=0 );
109383 /* Also add a UTF-8 case-insensitive collation sequence. */
109384 createCollation(db, "NOCASE", SQLITE_UTF8, SQLITE_COLL_NOCASE, 0,
109385 nocaseCollatingFunc, 0);
109387 /* Open the backend database driver */
109388 db->openFlags = flags;
109389 rc = sqlite3BtreeOpen(zFilename, db, &db->aDb[0].pBt, 0,
109390 flags | SQLITE_OPEN_MAIN_DB);
109391 if( rc!=SQLITE_OK ){
109392 if( rc==SQLITE_IOERR_NOMEM ){
109393 rc = SQLITE_NOMEM;
109395 sqlite3Error(db, rc, 0);
109396 goto opendb_out;
109398 db->aDb[0].pSchema = sqlite3SchemaGet(db, db->aDb[0].pBt);
109399 db->aDb[1].pSchema = sqlite3SchemaGet(db, 0);
109402 /* The default safety_level for the main database is 'full'; for the temp
109403 ** database it is 'NONE'. This matches the pager layer defaults.
109405 db->aDb[0].zName = "main";
109406 db->aDb[0].safety_level = 3;
109407 db->aDb[1].zName = "temp";
109408 db->aDb[1].safety_level = 1;
109410 db->magic = SQLITE_MAGIC_OPEN;
109411 if( db->mallocFailed ){
109412 goto opendb_out;
109415 /* Register all built-in functions, but do not attempt to read the
109416 ** database schema yet. This is delayed until the first time the database
109417 ** is accessed.
109419 sqlite3Error(db, SQLITE_OK, 0);
109420 sqlite3RegisterBuiltinFunctions(db);
109422 /* Load automatic extensions - extensions that have been registered
109423 ** using the sqlite3_automatic_extension() API.
109425 sqlite3AutoLoadExtensions(db);
109426 rc = sqlite3_errcode(db);
109427 if( rc!=SQLITE_OK ){
109428 goto opendb_out;
109431 #ifdef SQLITE_ENABLE_FTS1
109432 if( !db->mallocFailed ){
109433 extern int sqlite3Fts1Init(sqlite3*);
109434 rc = sqlite3Fts1Init(db);
109436 #endif
109438 #ifdef SQLITE_ENABLE_FTS2
109439 if( !db->mallocFailed && rc==SQLITE_OK ){
109440 extern int sqlite3Fts2Init(sqlite3*);
109441 rc = sqlite3Fts2Init(db);
109443 #endif
109445 #ifdef SQLITE_ENABLE_FTS3
109446 if( !db->mallocFailed && rc==SQLITE_OK ){
109447 rc = sqlite3Fts3Init(db);
109449 #endif
109451 #ifdef SQLITE_ENABLE_ICU
109452 if( !db->mallocFailed && rc==SQLITE_OK ){
109453 rc = sqlite3IcuInit(db);
109455 #endif
109457 #ifdef SQLITE_ENABLE_RTREE
109458 if( !db->mallocFailed && rc==SQLITE_OK){
109459 rc = sqlite3RtreeInit(db);
109461 #endif
109463 sqlite3Error(db, rc, 0);
109465 /* -DSQLITE_DEFAULT_LOCKING_MODE=1 makes EXCLUSIVE the default locking
109466 ** mode. -DSQLITE_DEFAULT_LOCKING_MODE=0 make NORMAL the default locking
109467 ** mode. Doing nothing at all also makes NORMAL the default.
109469 #ifdef SQLITE_DEFAULT_LOCKING_MODE
109470 db->dfltLockMode = SQLITE_DEFAULT_LOCKING_MODE;
109471 sqlite3PagerLockingMode(sqlite3BtreePager(db->aDb[0].pBt),
109472 SQLITE_DEFAULT_LOCKING_MODE);
109473 #endif
109475 /* Enable the lookaside-malloc subsystem */
109476 setupLookaside(db, 0, sqlite3GlobalConfig.szLookaside,
109477 sqlite3GlobalConfig.nLookaside);
109479 sqlite3_wal_autocheckpoint(db, SQLITE_DEFAULT_WAL_AUTOCHECKPOINT);
109481 opendb_out:
109482 if( db ){
109483 assert( db->mutex!=0 || isThreadsafe==0 || sqlite3GlobalConfig.bFullMutex==0 );
109484 sqlite3_mutex_leave(db->mutex);
109486 rc = sqlite3_errcode(db);
109487 if( rc==SQLITE_NOMEM ){
109488 sqlite3_close(db);
109489 db = 0;
109490 }else if( rc!=SQLITE_OK ){
109491 db->magic = SQLITE_MAGIC_SICK;
109493 *ppDb = db;
109494 return sqlite3ApiExit(0, rc);
109498 ** Open a new database handle.
109500 SQLITE_API int sqlite3_open(
109501 const char *zFilename,
109502 sqlite3 **ppDb
109504 return openDatabase(zFilename, ppDb,
109505 SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, 0);
109507 SQLITE_API int sqlite3_open_v2(
109508 const char *filename, /* Database filename (UTF-8) */
109509 sqlite3 **ppDb, /* OUT: SQLite db handle */
109510 int flags, /* Flags */
109511 const char *zVfs /* Name of VFS module to use */
109513 return openDatabase(filename, ppDb, flags, zVfs);
109516 #ifndef SQLITE_OMIT_UTF16
109518 ** Open a new database handle.
109520 SQLITE_API int sqlite3_open16(
109521 const void *zFilename,
109522 sqlite3 **ppDb
109524 char const *zFilename8; /* zFilename encoded in UTF-8 instead of UTF-16 */
109525 sqlite3_value *pVal;
109526 int rc;
109528 assert( zFilename );
109529 assert( ppDb );
109530 *ppDb = 0;
109531 #ifndef SQLITE_OMIT_AUTOINIT
109532 rc = sqlite3_initialize();
109533 if( rc ) return rc;
109534 #endif
109535 pVal = sqlite3ValueNew(0);
109536 sqlite3ValueSetStr(pVal, -1, zFilename, SQLITE_UTF16NATIVE, SQLITE_STATIC);
109537 zFilename8 = sqlite3ValueText(pVal, SQLITE_UTF8);
109538 if( zFilename8 ){
109539 rc = openDatabase(zFilename8, ppDb,
109540 SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, 0);
109541 assert( *ppDb || rc==SQLITE_NOMEM );
109542 if( rc==SQLITE_OK && !DbHasProperty(*ppDb, 0, DB_SchemaLoaded) ){
109543 ENC(*ppDb) = SQLITE_UTF16NATIVE;
109545 }else{
109546 rc = SQLITE_NOMEM;
109548 sqlite3ValueFree(pVal);
109550 return sqlite3ApiExit(0, rc);
109552 #endif /* SQLITE_OMIT_UTF16 */
109555 ** Register a new collation sequence with the database handle db.
109557 SQLITE_API int sqlite3_create_collation(
109558 sqlite3* db,
109559 const char *zName,
109560 int enc,
109561 void* pCtx,
109562 int(*xCompare)(void*,int,const void*,int,const void*)
109564 int rc;
109565 sqlite3_mutex_enter(db->mutex);
109566 assert( !db->mallocFailed );
109567 rc = createCollation(db, zName, (u8)enc, SQLITE_COLL_USER, pCtx, xCompare, 0);
109568 rc = sqlite3ApiExit(db, rc);
109569 sqlite3_mutex_leave(db->mutex);
109570 return rc;
109574 ** Register a new collation sequence with the database handle db.
109576 SQLITE_API int sqlite3_create_collation_v2(
109577 sqlite3* db,
109578 const char *zName,
109579 int enc,
109580 void* pCtx,
109581 int(*xCompare)(void*,int,const void*,int,const void*),
109582 void(*xDel)(void*)
109584 int rc;
109585 sqlite3_mutex_enter(db->mutex);
109586 assert( !db->mallocFailed );
109587 rc = createCollation(db, zName, (u8)enc, SQLITE_COLL_USER, pCtx, xCompare, xDel);
109588 rc = sqlite3ApiExit(db, rc);
109589 sqlite3_mutex_leave(db->mutex);
109590 return rc;
109593 #ifndef SQLITE_OMIT_UTF16
109595 ** Register a new collation sequence with the database handle db.
109597 SQLITE_API int sqlite3_create_collation16(
109598 sqlite3* db,
109599 const void *zName,
109600 int enc,
109601 void* pCtx,
109602 int(*xCompare)(void*,int,const void*,int,const void*)
109604 int rc = SQLITE_OK;
109605 char *zName8;
109606 sqlite3_mutex_enter(db->mutex);
109607 assert( !db->mallocFailed );
109608 zName8 = sqlite3Utf16to8(db, zName, -1, SQLITE_UTF16NATIVE);
109609 if( zName8 ){
109610 rc = createCollation(db, zName8, (u8)enc, SQLITE_COLL_USER, pCtx, xCompare, 0);
109611 sqlite3DbFree(db, zName8);
109613 rc = sqlite3ApiExit(db, rc);
109614 sqlite3_mutex_leave(db->mutex);
109615 return rc;
109617 #endif /* SQLITE_OMIT_UTF16 */
109620 ** Register a collation sequence factory callback with the database handle
109621 ** db. Replace any previously installed collation sequence factory.
109623 SQLITE_API int sqlite3_collation_needed(
109624 sqlite3 *db,
109625 void *pCollNeededArg,
109626 void(*xCollNeeded)(void*,sqlite3*,int eTextRep,const char*)
109628 sqlite3_mutex_enter(db->mutex);
109629 db->xCollNeeded = xCollNeeded;
109630 db->xCollNeeded16 = 0;
109631 db->pCollNeededArg = pCollNeededArg;
109632 sqlite3_mutex_leave(db->mutex);
109633 return SQLITE_OK;
109636 #ifndef SQLITE_OMIT_UTF16
109638 ** Register a collation sequence factory callback with the database handle
109639 ** db. Replace any previously installed collation sequence factory.
109641 SQLITE_API int sqlite3_collation_needed16(
109642 sqlite3 *db,
109643 void *pCollNeededArg,
109644 void(*xCollNeeded16)(void*,sqlite3*,int eTextRep,const void*)
109646 sqlite3_mutex_enter(db->mutex);
109647 db->xCollNeeded = 0;
109648 db->xCollNeeded16 = xCollNeeded16;
109649 db->pCollNeededArg = pCollNeededArg;
109650 sqlite3_mutex_leave(db->mutex);
109651 return SQLITE_OK;
109653 #endif /* SQLITE_OMIT_UTF16 */
109655 #ifndef SQLITE_OMIT_DEPRECATED
109657 ** This function is now an anachronism. It used to be used to recover from a
109658 ** malloc() failure, but SQLite now does this automatically.
109660 SQLITE_API int sqlite3_global_recover(void){
109661 return SQLITE_OK;
109663 #endif
109666 ** Test to see whether or not the database connection is in autocommit
109667 ** mode. Return TRUE if it is and FALSE if not. Autocommit mode is on
109668 ** by default. Autocommit is disabled by a BEGIN statement and reenabled
109669 ** by the next COMMIT or ROLLBACK.
109671 ******* THIS IS AN EXPERIMENTAL API AND IS SUBJECT TO CHANGE ******
109673 SQLITE_API int sqlite3_get_autocommit(sqlite3 *db){
109674 return db->autoCommit;
109678 ** The following routines are subtitutes for constants SQLITE_CORRUPT,
109679 ** SQLITE_MISUSE, SQLITE_CANTOPEN, SQLITE_IOERR and possibly other error
109680 ** constants. They server two purposes:
109682 ** 1. Serve as a convenient place to set a breakpoint in a debugger
109683 ** to detect when version error conditions occurs.
109685 ** 2. Invoke sqlite3_log() to provide the source code location where
109686 ** a low-level error is first detected.
109688 SQLITE_PRIVATE int sqlite3CorruptError(int lineno){
109689 testcase( sqlite3GlobalConfig.xLog!=0 );
109690 sqlite3_log(SQLITE_CORRUPT,
109691 "database corruption at line %d of [%.10s]",
109692 lineno, 20+sqlite3_sourceid());
109693 return SQLITE_CORRUPT;
109695 SQLITE_PRIVATE int sqlite3MisuseError(int lineno){
109696 testcase( sqlite3GlobalConfig.xLog!=0 );
109697 sqlite3_log(SQLITE_MISUSE,
109698 "misuse at line %d of [%.10s]",
109699 lineno, 20+sqlite3_sourceid());
109700 return SQLITE_MISUSE;
109702 SQLITE_PRIVATE int sqlite3CantopenError(int lineno){
109703 testcase( sqlite3GlobalConfig.xLog!=0 );
109704 sqlite3_log(SQLITE_CANTOPEN,
109705 "cannot open file at line %d of [%.10s]",
109706 lineno, 20+sqlite3_sourceid());
109707 return SQLITE_CANTOPEN;
109711 #ifndef SQLITE_OMIT_DEPRECATED
109713 ** This is a convenience routine that makes sure that all thread-specific
109714 ** data for this thread has been deallocated.
109716 ** SQLite no longer uses thread-specific data so this routine is now a
109717 ** no-op. It is retained for historical compatibility.
109719 SQLITE_API void sqlite3_thread_cleanup(void){
109721 #endif
109724 ** Return meta information about a specific column of a database table.
109725 ** See comment in sqlite3.h (sqlite.h.in) for details.
109727 #ifdef SQLITE_ENABLE_COLUMN_METADATA
109728 SQLITE_API int sqlite3_table_column_metadata(
109729 sqlite3 *db, /* Connection handle */
109730 const char *zDbName, /* Database name or NULL */
109731 const char *zTableName, /* Table name */
109732 const char *zColumnName, /* Column name */
109733 char const **pzDataType, /* OUTPUT: Declared data type */
109734 char const **pzCollSeq, /* OUTPUT: Collation sequence name */
109735 int *pNotNull, /* OUTPUT: True if NOT NULL constraint exists */
109736 int *pPrimaryKey, /* OUTPUT: True if column part of PK */
109737 int *pAutoinc /* OUTPUT: True if column is auto-increment */
109739 int rc;
109740 char *zErrMsg = 0;
109741 Table *pTab = 0;
109742 Column *pCol = 0;
109743 int iCol;
109745 char const *zDataType = 0;
109746 char const *zCollSeq = 0;
109747 int notnull = 0;
109748 int primarykey = 0;
109749 int autoinc = 0;
109751 /* Ensure the database schema has been loaded */
109752 sqlite3_mutex_enter(db->mutex);
109753 sqlite3BtreeEnterAll(db);
109754 rc = sqlite3Init(db, &zErrMsg);
109755 if( SQLITE_OK!=rc ){
109756 goto error_out;
109759 /* Locate the table in question */
109760 pTab = sqlite3FindTable(db, zTableName, zDbName);
109761 if( !pTab || pTab->pSelect ){
109762 pTab = 0;
109763 goto error_out;
109766 /* Find the column for which info is requested */
109767 if( sqlite3IsRowid(zColumnName) ){
109768 iCol = pTab->iPKey;
109769 if( iCol>=0 ){
109770 pCol = &pTab->aCol[iCol];
109772 }else{
109773 for(iCol=0; iCol<pTab->nCol; iCol++){
109774 pCol = &pTab->aCol[iCol];
109775 if( 0==sqlite3StrICmp(pCol->zName, zColumnName) ){
109776 break;
109779 if( iCol==pTab->nCol ){
109780 pTab = 0;
109781 goto error_out;
109785 /* The following block stores the meta information that will be returned
109786 ** to the caller in local variables zDataType, zCollSeq, notnull, primarykey
109787 ** and autoinc. At this point there are two possibilities:
109789 ** 1. The specified column name was rowid", "oid" or "_rowid_"
109790 ** and there is no explicitly declared IPK column.
109792 ** 2. The table is not a view and the column name identified an
109793 ** explicitly declared column. Copy meta information from *pCol.
109795 if( pCol ){
109796 zDataType = pCol->zType;
109797 zCollSeq = pCol->zColl;
109798 notnull = pCol->notNull!=0;
109799 primarykey = pCol->isPrimKey!=0;
109800 autoinc = pTab->iPKey==iCol && (pTab->tabFlags & TF_Autoincrement)!=0;
109801 }else{
109802 zDataType = "INTEGER";
109803 primarykey = 1;
109805 if( !zCollSeq ){
109806 zCollSeq = "BINARY";
109809 error_out:
109810 sqlite3BtreeLeaveAll(db);
109812 /* Whether the function call succeeded or failed, set the output parameters
109813 ** to whatever their local counterparts contain. If an error did occur,
109814 ** this has the effect of zeroing all output parameters.
109816 if( pzDataType ) *pzDataType = zDataType;
109817 if( pzCollSeq ) *pzCollSeq = zCollSeq;
109818 if( pNotNull ) *pNotNull = notnull;
109819 if( pPrimaryKey ) *pPrimaryKey = primarykey;
109820 if( pAutoinc ) *pAutoinc = autoinc;
109822 if( SQLITE_OK==rc && !pTab ){
109823 sqlite3DbFree(db, zErrMsg);
109824 zErrMsg = sqlite3MPrintf(db, "no such table column: %s.%s", zTableName,
109825 zColumnName);
109826 rc = SQLITE_ERROR;
109828 sqlite3Error(db, rc, (zErrMsg?"%s":0), zErrMsg);
109829 sqlite3DbFree(db, zErrMsg);
109830 rc = sqlite3ApiExit(db, rc);
109831 sqlite3_mutex_leave(db->mutex);
109832 return rc;
109834 #endif
109837 ** Sleep for a little while. Return the amount of time slept.
109839 SQLITE_API int sqlite3_sleep(int ms){
109840 sqlite3_vfs *pVfs;
109841 int rc;
109842 pVfs = sqlite3_vfs_find(0);
109843 if( pVfs==0 ) return 0;
109845 /* This function works in milliseconds, but the underlying OsSleep()
109846 ** API uses microseconds. Hence the 1000's.
109848 rc = (sqlite3OsSleep(pVfs, 1000*ms)/1000);
109849 return rc;
109853 ** Enable or disable the extended result codes.
109855 SQLITE_API int sqlite3_extended_result_codes(sqlite3 *db, int onoff){
109856 sqlite3_mutex_enter(db->mutex);
109857 db->errMask = onoff ? 0xffffffff : 0xff;
109858 sqlite3_mutex_leave(db->mutex);
109859 return SQLITE_OK;
109863 ** Invoke the xFileControl method on a particular database.
109865 SQLITE_API int sqlite3_file_control(sqlite3 *db, const char *zDbName, int op, void *pArg){
109866 int rc = SQLITE_ERROR;
109867 int iDb;
109868 sqlite3_mutex_enter(db->mutex);
109869 if( zDbName==0 ){
109870 iDb = 0;
109871 }else{
109872 for(iDb=0; iDb<db->nDb; iDb++){
109873 if( strcmp(db->aDb[iDb].zName, zDbName)==0 ) break;
109876 if( iDb<db->nDb ){
109877 Btree *pBtree = db->aDb[iDb].pBt;
109878 if( pBtree ){
109879 Pager *pPager;
109880 sqlite3_file *fd;
109881 sqlite3BtreeEnter(pBtree);
109882 pPager = sqlite3BtreePager(pBtree);
109883 assert( pPager!=0 );
109884 fd = sqlite3PagerFile(pPager);
109885 assert( fd!=0 );
109886 if( op==SQLITE_FCNTL_FILE_POINTER ){
109887 *(sqlite3_file**)pArg = fd;
109888 rc = SQLITE_OK;
109889 }else if( fd->pMethods ){
109890 rc = sqlite3OsFileControl(fd, op, pArg);
109891 }else{
109892 rc = SQLITE_NOTFOUND;
109894 sqlite3BtreeLeave(pBtree);
109897 sqlite3_mutex_leave(db->mutex);
109898 return rc;
109902 ** Interface to the testing logic.
109904 SQLITE_API int sqlite3_test_control(int op, ...){
109905 int rc = 0;
109906 #ifndef SQLITE_OMIT_BUILTIN_TEST
109907 va_list ap;
109908 va_start(ap, op);
109909 switch( op ){
109912 ** Save the current state of the PRNG.
109914 case SQLITE_TESTCTRL_PRNG_SAVE: {
109915 sqlite3PrngSaveState();
109916 break;
109920 ** Restore the state of the PRNG to the last state saved using
109921 ** PRNG_SAVE. If PRNG_SAVE has never before been called, then
109922 ** this verb acts like PRNG_RESET.
109924 case SQLITE_TESTCTRL_PRNG_RESTORE: {
109925 sqlite3PrngRestoreState();
109926 break;
109930 ** Reset the PRNG back to its uninitialized state. The next call
109931 ** to sqlite3_randomness() will reseed the PRNG using a single call
109932 ** to the xRandomness method of the default VFS.
109934 case SQLITE_TESTCTRL_PRNG_RESET: {
109935 sqlite3PrngResetState();
109936 break;
109940 ** sqlite3_test_control(BITVEC_TEST, size, program)
109942 ** Run a test against a Bitvec object of size. The program argument
109943 ** is an array of integers that defines the test. Return -1 on a
109944 ** memory allocation error, 0 on success, or non-zero for an error.
109945 ** See the sqlite3BitvecBuiltinTest() for additional information.
109947 case SQLITE_TESTCTRL_BITVEC_TEST: {
109948 int sz = va_arg(ap, int);
109949 int *aProg = va_arg(ap, int*);
109950 rc = sqlite3BitvecBuiltinTest(sz, aProg);
109951 break;
109955 ** sqlite3_test_control(BENIGN_MALLOC_HOOKS, xBegin, xEnd)
109957 ** Register hooks to call to indicate which malloc() failures
109958 ** are benign.
109960 case SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS: {
109961 typedef void (*void_function)(void);
109962 void_function xBenignBegin;
109963 void_function xBenignEnd;
109964 xBenignBegin = va_arg(ap, void_function);
109965 xBenignEnd = va_arg(ap, void_function);
109966 sqlite3BenignMallocHooks(xBenignBegin, xBenignEnd);
109967 break;
109971 ** sqlite3_test_control(SQLITE_TESTCTRL_PENDING_BYTE, unsigned int X)
109973 ** Set the PENDING byte to the value in the argument, if X>0.
109974 ** Make no changes if X==0. Return the value of the pending byte
109975 ** as it existing before this routine was called.
109977 ** IMPORTANT: Changing the PENDING byte from 0x40000000 results in
109978 ** an incompatible database file format. Changing the PENDING byte
109979 ** while any database connection is open results in undefined and
109980 ** dileterious behavior.
109982 case SQLITE_TESTCTRL_PENDING_BYTE: {
109983 rc = PENDING_BYTE;
109984 #ifndef SQLITE_OMIT_WSD
109986 unsigned int newVal = va_arg(ap, unsigned int);
109987 if( newVal ) sqlite3PendingByte = newVal;
109989 #endif
109990 break;
109994 ** sqlite3_test_control(SQLITE_TESTCTRL_ASSERT, int X)
109996 ** This action provides a run-time test to see whether or not
109997 ** assert() was enabled at compile-time. If X is true and assert()
109998 ** is enabled, then the return value is true. If X is true and
109999 ** assert() is disabled, then the return value is zero. If X is
110000 ** false and assert() is enabled, then the assertion fires and the
110001 ** process aborts. If X is false and assert() is disabled, then the
110002 ** return value is zero.
110004 case SQLITE_TESTCTRL_ASSERT: {
110005 volatile int x = 0;
110006 assert( (x = va_arg(ap,int))!=0 );
110007 rc = x;
110008 break;
110013 ** sqlite3_test_control(SQLITE_TESTCTRL_ALWAYS, int X)
110015 ** This action provides a run-time test to see how the ALWAYS and
110016 ** NEVER macros were defined at compile-time.
110018 ** The return value is ALWAYS(X).
110020 ** The recommended test is X==2. If the return value is 2, that means
110021 ** ALWAYS() and NEVER() are both no-op pass-through macros, which is the
110022 ** default setting. If the return value is 1, then ALWAYS() is either
110023 ** hard-coded to true or else it asserts if its argument is false.
110024 ** The first behavior (hard-coded to true) is the case if
110025 ** SQLITE_TESTCTRL_ASSERT shows that assert() is disabled and the second
110026 ** behavior (assert if the argument to ALWAYS() is false) is the case if
110027 ** SQLITE_TESTCTRL_ASSERT shows that assert() is enabled.
110029 ** The run-time test procedure might look something like this:
110031 ** if( sqlite3_test_control(SQLITE_TESTCTRL_ALWAYS, 2)==2 ){
110032 ** // ALWAYS() and NEVER() are no-op pass-through macros
110033 ** }else if( sqlite3_test_control(SQLITE_TESTCTRL_ASSERT, 1) ){
110034 ** // ALWAYS(x) asserts that x is true. NEVER(x) asserts x is false.
110035 ** }else{
110036 ** // ALWAYS(x) is a constant 1. NEVER(x) is a constant 0.
110039 case SQLITE_TESTCTRL_ALWAYS: {
110040 int x = va_arg(ap,int);
110041 rc = ALWAYS(x);
110042 break;
110045 /* sqlite3_test_control(SQLITE_TESTCTRL_RESERVE, sqlite3 *db, int N)
110047 ** Set the nReserve size to N for the main database on the database
110048 ** connection db.
110050 case SQLITE_TESTCTRL_RESERVE: {
110051 sqlite3 *db = va_arg(ap, sqlite3*);
110052 int x = va_arg(ap,int);
110053 sqlite3_mutex_enter(db->mutex);
110054 sqlite3BtreeSetPageSize(db->aDb[0].pBt, 0, x, 0);
110055 sqlite3_mutex_leave(db->mutex);
110056 break;
110059 /* sqlite3_test_control(SQLITE_TESTCTRL_OPTIMIZATIONS, sqlite3 *db, int N)
110061 ** Enable or disable various optimizations for testing purposes. The
110062 ** argument N is a bitmask of optimizations to be disabled. For normal
110063 ** operation N should be 0. The idea is that a test program (like the
110064 ** SQL Logic Test or SLT test module) can run the same SQL multiple times
110065 ** with various optimizations disabled to verify that the same answer
110066 ** is obtained in every case.
110068 case SQLITE_TESTCTRL_OPTIMIZATIONS: {
110069 sqlite3 *db = va_arg(ap, sqlite3*);
110070 int x = va_arg(ap,int);
110071 db->flags = (x & SQLITE_OptMask) | (db->flags & ~SQLITE_OptMask);
110072 break;
110075 #ifdef SQLITE_N_KEYWORD
110076 /* sqlite3_test_control(SQLITE_TESTCTRL_ISKEYWORD, const char *zWord)
110078 ** If zWord is a keyword recognized by the parser, then return the
110079 ** number of keywords. Or if zWord is not a keyword, return 0.
110081 ** This test feature is only available in the amalgamation since
110082 ** the SQLITE_N_KEYWORD macro is not defined in this file if SQLite
110083 ** is built using separate source files.
110085 case SQLITE_TESTCTRL_ISKEYWORD: {
110086 const char *zWord = va_arg(ap, const char*);
110087 int n = sqlite3Strlen30(zWord);
110088 rc = (sqlite3KeywordCode((u8*)zWord, n)!=TK_ID) ? SQLITE_N_KEYWORD : 0;
110089 break;
110091 #endif
110093 /* sqlite3_test_control(SQLITE_TESTCTRL_PGHDRSZ)
110095 ** Return the size of a pcache header in bytes.
110097 case SQLITE_TESTCTRL_PGHDRSZ: {
110098 rc = sizeof(PgHdr);
110099 break;
110102 /* sqlite3_test_control(SQLITE_TESTCTRL_SCRATCHMALLOC, sz, &pNew, pFree);
110104 ** Pass pFree into sqlite3ScratchFree().
110105 ** If sz>0 then allocate a scratch buffer into pNew.
110107 case SQLITE_TESTCTRL_SCRATCHMALLOC: {
110108 void *pFree, **ppNew;
110109 int sz;
110110 sz = va_arg(ap, int);
110111 ppNew = va_arg(ap, void**);
110112 pFree = va_arg(ap, void*);
110113 if( sz ) *ppNew = sqlite3ScratchMalloc(sz);
110114 sqlite3ScratchFree(pFree);
110115 break;
110119 va_end(ap);
110120 #endif /* SQLITE_OMIT_BUILTIN_TEST */
110121 return rc;
110124 /************** End of main.c ************************************************/
110125 /************** Begin file notify.c ******************************************/
110127 ** 2009 March 3
110129 ** The author disclaims copyright to this source code. In place of
110130 ** a legal notice, here is a blessing:
110132 ** May you do good and not evil.
110133 ** May you find forgiveness for yourself and forgive others.
110134 ** May you share freely, never taking more than you give.
110136 *************************************************************************
110138 ** This file contains the implementation of the sqlite3_unlock_notify()
110139 ** API method and its associated functionality.
110142 /* Omit this entire file if SQLITE_ENABLE_UNLOCK_NOTIFY is not defined. */
110143 #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
110146 ** Public interfaces:
110148 ** sqlite3ConnectionBlocked()
110149 ** sqlite3ConnectionUnlocked()
110150 ** sqlite3ConnectionClosed()
110151 ** sqlite3_unlock_notify()
110154 #define assertMutexHeld() \
110155 assert( sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER)) )
110158 ** Head of a linked list of all sqlite3 objects created by this process
110159 ** for which either sqlite3.pBlockingConnection or sqlite3.pUnlockConnection
110160 ** is not NULL. This variable may only accessed while the STATIC_MASTER
110161 ** mutex is held.
110163 static sqlite3 *SQLITE_WSD sqlite3BlockedList = 0;
110165 #ifndef NDEBUG
110167 ** This function is a complex assert() that verifies the following
110168 ** properties of the blocked connections list:
110170 ** 1) Each entry in the list has a non-NULL value for either
110171 ** pUnlockConnection or pBlockingConnection, or both.
110173 ** 2) All entries in the list that share a common value for
110174 ** xUnlockNotify are grouped together.
110176 ** 3) If the argument db is not NULL, then none of the entries in the
110177 ** blocked connections list have pUnlockConnection or pBlockingConnection
110178 ** set to db. This is used when closing connection db.
110180 static void checkListProperties(sqlite3 *db){
110181 sqlite3 *p;
110182 for(p=sqlite3BlockedList; p; p=p->pNextBlocked){
110183 int seen = 0;
110184 sqlite3 *p2;
110186 /* Verify property (1) */
110187 assert( p->pUnlockConnection || p->pBlockingConnection );
110189 /* Verify property (2) */
110190 for(p2=sqlite3BlockedList; p2!=p; p2=p2->pNextBlocked){
110191 if( p2->xUnlockNotify==p->xUnlockNotify ) seen = 1;
110192 assert( p2->xUnlockNotify==p->xUnlockNotify || !seen );
110193 assert( db==0 || p->pUnlockConnection!=db );
110194 assert( db==0 || p->pBlockingConnection!=db );
110198 #else
110199 # define checkListProperties(x)
110200 #endif
110203 ** Remove connection db from the blocked connections list. If connection
110204 ** db is not currently a part of the list, this function is a no-op.
110206 static void removeFromBlockedList(sqlite3 *db){
110207 sqlite3 **pp;
110208 assertMutexHeld();
110209 for(pp=&sqlite3BlockedList; *pp; pp = &(*pp)->pNextBlocked){
110210 if( *pp==db ){
110211 *pp = (*pp)->pNextBlocked;
110212 break;
110218 ** Add connection db to the blocked connections list. It is assumed
110219 ** that it is not already a part of the list.
110221 static void addToBlockedList(sqlite3 *db){
110222 sqlite3 **pp;
110223 assertMutexHeld();
110225 pp=&sqlite3BlockedList;
110226 *pp && (*pp)->xUnlockNotify!=db->xUnlockNotify;
110227 pp=&(*pp)->pNextBlocked
110229 db->pNextBlocked = *pp;
110230 *pp = db;
110234 ** Obtain the STATIC_MASTER mutex.
110236 static void enterMutex(void){
110237 sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
110238 checkListProperties(0);
110242 ** Release the STATIC_MASTER mutex.
110244 static void leaveMutex(void){
110245 assertMutexHeld();
110246 checkListProperties(0);
110247 sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
110251 ** Register an unlock-notify callback.
110253 ** This is called after connection "db" has attempted some operation
110254 ** but has received an SQLITE_LOCKED error because another connection
110255 ** (call it pOther) in the same process was busy using the same shared
110256 ** cache. pOther is found by looking at db->pBlockingConnection.
110258 ** If there is no blocking connection, the callback is invoked immediately,
110259 ** before this routine returns.
110261 ** If pOther is already blocked on db, then report SQLITE_LOCKED, to indicate
110262 ** a deadlock.
110264 ** Otherwise, make arrangements to invoke xNotify when pOther drops
110265 ** its locks.
110267 ** Each call to this routine overrides any prior callbacks registered
110268 ** on the same "db". If xNotify==0 then any prior callbacks are immediately
110269 ** cancelled.
110271 SQLITE_API int sqlite3_unlock_notify(
110272 sqlite3 *db,
110273 void (*xNotify)(void **, int),
110274 void *pArg
110276 int rc = SQLITE_OK;
110278 sqlite3_mutex_enter(db->mutex);
110279 enterMutex();
110281 if( xNotify==0 ){
110282 removeFromBlockedList(db);
110283 db->pBlockingConnection = 0;
110284 db->pUnlockConnection = 0;
110285 db->xUnlockNotify = 0;
110286 db->pUnlockArg = 0;
110287 }else if( 0==db->pBlockingConnection ){
110288 /* The blocking transaction has been concluded. Or there never was a
110289 ** blocking transaction. In either case, invoke the notify callback
110290 ** immediately.
110292 xNotify(&pArg, 1);
110293 }else{
110294 sqlite3 *p;
110296 for(p=db->pBlockingConnection; p && p!=db; p=p->pUnlockConnection){}
110297 if( p ){
110298 rc = SQLITE_LOCKED; /* Deadlock detected. */
110299 }else{
110300 db->pUnlockConnection = db->pBlockingConnection;
110301 db->xUnlockNotify = xNotify;
110302 db->pUnlockArg = pArg;
110303 removeFromBlockedList(db);
110304 addToBlockedList(db);
110308 leaveMutex();
110309 assert( !db->mallocFailed );
110310 sqlite3Error(db, rc, (rc?"database is deadlocked":0));
110311 sqlite3_mutex_leave(db->mutex);
110312 return rc;
110316 ** This function is called while stepping or preparing a statement
110317 ** associated with connection db. The operation will return SQLITE_LOCKED
110318 ** to the user because it requires a lock that will not be available
110319 ** until connection pBlocker concludes its current transaction.
110321 SQLITE_PRIVATE void sqlite3ConnectionBlocked(sqlite3 *db, sqlite3 *pBlocker){
110322 enterMutex();
110323 if( db->pBlockingConnection==0 && db->pUnlockConnection==0 ){
110324 addToBlockedList(db);
110326 db->pBlockingConnection = pBlocker;
110327 leaveMutex();
110331 ** This function is called when
110332 ** the transaction opened by database db has just finished. Locks held
110333 ** by database connection db have been released.
110335 ** This function loops through each entry in the blocked connections
110336 ** list and does the following:
110338 ** 1) If the sqlite3.pBlockingConnection member of a list entry is
110339 ** set to db, then set pBlockingConnection=0.
110341 ** 2) If the sqlite3.pUnlockConnection member of a list entry is
110342 ** set to db, then invoke the configured unlock-notify callback and
110343 ** set pUnlockConnection=0.
110345 ** 3) If the two steps above mean that pBlockingConnection==0 and
110346 ** pUnlockConnection==0, remove the entry from the blocked connections
110347 ** list.
110349 SQLITE_PRIVATE void sqlite3ConnectionUnlocked(sqlite3 *db){
110350 void (*xUnlockNotify)(void **, int) = 0; /* Unlock-notify cb to invoke */
110351 int nArg = 0; /* Number of entries in aArg[] */
110352 sqlite3 **pp; /* Iterator variable */
110353 void **aArg; /* Arguments to the unlock callback */
110354 void **aDyn = 0; /* Dynamically allocated space for aArg[] */
110355 void *aStatic[16]; /* Starter space for aArg[]. No malloc required */
110357 aArg = aStatic;
110358 enterMutex(); /* Enter STATIC_MASTER mutex */
110360 /* This loop runs once for each entry in the blocked-connections list. */
110361 for(pp=&sqlite3BlockedList; *pp; /* no-op */ ){
110362 sqlite3 *p = *pp;
110364 /* Step 1. */
110365 if( p->pBlockingConnection==db ){
110366 p->pBlockingConnection = 0;
110369 /* Step 2. */
110370 if( p->pUnlockConnection==db ){
110371 assert( p->xUnlockNotify );
110372 if( p->xUnlockNotify!=xUnlockNotify && nArg!=0 ){
110373 xUnlockNotify(aArg, nArg);
110374 nArg = 0;
110377 sqlite3BeginBenignMalloc();
110378 assert( aArg==aDyn || (aDyn==0 && aArg==aStatic) );
110379 assert( nArg<=(int)ArraySize(aStatic) || aArg==aDyn );
110380 if( (!aDyn && nArg==(int)ArraySize(aStatic))
110381 || (aDyn && nArg==(int)(sqlite3MallocSize(aDyn)/sizeof(void*)))
110383 /* The aArg[] array needs to grow. */
110384 void **pNew = (void **)sqlite3Malloc(nArg*sizeof(void *)*2);
110385 if( pNew ){
110386 memcpy(pNew, aArg, nArg*sizeof(void *));
110387 sqlite3_free(aDyn);
110388 aDyn = aArg = pNew;
110389 }else{
110390 /* This occurs when the array of context pointers that need to
110391 ** be passed to the unlock-notify callback is larger than the
110392 ** aStatic[] array allocated on the stack and the attempt to
110393 ** allocate a larger array from the heap has failed.
110395 ** This is a difficult situation to handle. Returning an error
110396 ** code to the caller is insufficient, as even if an error code
110397 ** is returned the transaction on connection db will still be
110398 ** closed and the unlock-notify callbacks on blocked connections
110399 ** will go unissued. This might cause the application to wait
110400 ** indefinitely for an unlock-notify callback that will never
110401 ** arrive.
110403 ** Instead, invoke the unlock-notify callback with the context
110404 ** array already accumulated. We can then clear the array and
110405 ** begin accumulating any further context pointers without
110406 ** requiring any dynamic allocation. This is sub-optimal because
110407 ** it means that instead of one callback with a large array of
110408 ** context pointers the application will receive two or more
110409 ** callbacks with smaller arrays of context pointers, which will
110410 ** reduce the applications ability to prioritize multiple
110411 ** connections. But it is the best that can be done under the
110412 ** circumstances.
110414 xUnlockNotify(aArg, nArg);
110415 nArg = 0;
110418 sqlite3EndBenignMalloc();
110420 aArg[nArg++] = p->pUnlockArg;
110421 xUnlockNotify = p->xUnlockNotify;
110422 p->pUnlockConnection = 0;
110423 p->xUnlockNotify = 0;
110424 p->pUnlockArg = 0;
110427 /* Step 3. */
110428 if( p->pBlockingConnection==0 && p->pUnlockConnection==0 ){
110429 /* Remove connection p from the blocked connections list. */
110430 *pp = p->pNextBlocked;
110431 p->pNextBlocked = 0;
110432 }else{
110433 pp = &p->pNextBlocked;
110437 if( nArg!=0 ){
110438 xUnlockNotify(aArg, nArg);
110440 sqlite3_free(aDyn);
110441 leaveMutex(); /* Leave STATIC_MASTER mutex */
110445 ** This is called when the database connection passed as an argument is
110446 ** being closed. The connection is removed from the blocked list.
110448 SQLITE_PRIVATE void sqlite3ConnectionClosed(sqlite3 *db){
110449 sqlite3ConnectionUnlocked(db);
110450 enterMutex();
110451 removeFromBlockedList(db);
110452 checkListProperties(db);
110453 leaveMutex();
110455 #endif
110457 /************** End of notify.c **********************************************/
110458 /************** Begin file recover.c *****************************************/
110460 ** 2012 Jan 11
110462 ** The author disclaims copyright to this source code. In place of
110463 ** a legal notice, here is a blessing:
110465 ** May you do good and not evil.
110466 ** May you find forgiveness for yourself and forgive others.
110467 ** May you share freely, never taking more than you give.
110469 /* TODO(shess): THIS MODULE IS STILL EXPERIMENTAL. DO NOT USE IT. */
110470 /* Implements a virtual table "recover" which can be used to recover
110471 * data from a corrupt table. The table is walked manually, with
110472 * corrupt items skipped. Additionally, any errors while reading will
110473 * be skipped.
110475 * Given a table with this definition:
110477 * CREATE TABLE Stuff (
110478 * name TEXT PRIMARY KEY,
110479 * value TEXT NOT NULL
110482 * to recover the data from teh table, you could do something like:
110484 * -- Attach another database, the original is not trustworthy.
110485 * ATTACH DATABASE '/tmp/db.db' AS rdb;
110486 * -- Create a new version of the table.
110487 * CREATE TABLE rdb.Stuff (
110488 * name TEXT PRIMARY KEY,
110489 * value TEXT NOT NULL
110491 * -- This will read the original table's data.
110492 * CREATE VIRTUAL TABLE temp.recover_Stuff using recover(
110493 * main.Stuff,
110494 * name TEXT STRICT NOT NULL, -- only real TEXT data allowed
110495 * value TEXT STRICT NOT NULL
110497 * -- Corruption means the UNIQUE constraint may no longer hold for
110498 * -- Stuff, so either OR REPLACE or OR IGNORE must be used.
110499 * INSERT OR REPLACE INTO rdb.Stuff (rowid, name, value )
110500 * SELECT rowid, name, value FROM temp.recover_Stuff;
110501 * DROP TABLE temp.recover_Stuff;
110502 * DETACH DATABASE rdb;
110503 * -- Move db.db to replace original db in filesystem.
110506 * Usage
110508 * Given the goal of dealing with corruption, it would not be safe to
110509 * create a recovery table in the database being recovered. So
110510 * recovery tables must be created in the temp database. They are not
110511 * appropriate to persist, in any case. [As a bonus, sqlite_master
110512 * tables can be recovered. Perhaps more cute than useful, though.]
110514 * The parameters are a specifier for the table to read, and a column
110515 * definition for each bit of data stored in that table. The named
110516 * table must be convertable to a root page number by reading the
110517 * sqlite_master table. Bare table names are assumed to be in
110518 * database 0 ("main"), other databases can be specified in db.table
110519 * fashion.
110521 * Column definitions are similar to BUT NOT THE SAME AS those
110522 * provided to CREATE statements:
110523 * column-def: column-name [type-name [STRICT] [NOT NULL]]
110524 * type-name: (ANY|ROWID|INTEGER|FLOAT|NUMERIC|TEXT|BLOB)
110526 * Only those exact type names are accepted, there is no type
110527 * intuition. The only constraints accepted are STRICT (see below)
110528 * and NOT NULL. Anything unexpected will cause the create to fail.
110530 * ANY is a convenience to indicate that manifest typing is desired.
110531 * It is equivalent to not specifying a type at all. The results for
110532 * such columns will have the type of the data's storage. The exposed
110533 * schema will contain no type for that column.
110535 * ROWID is used for columns representing aliases to the rowid
110536 * (INTEGER PRIMARY KEY, with or without AUTOINCREMENT), to make the
110537 * concept explicit. Such columns are actually stored as NULL, so
110538 * they cannot be simply ignored. The exposed schema will be INTEGER
110539 * for that column.
110541 * NOT NULL causes rows with a NULL in that column to be skipped. It
110542 * also adds NOT NULL to the column in the exposed schema. If the
110543 * table has ever had columns added using ALTER TABLE, then those
110544 * columns implicitly contain NULL for rows which have not been
110545 * updated. [Workaround using COALESCE() in your SELECT statement.]
110547 * The created table is read-only, with no indices. Any SELECT will
110548 * be a full-table scan, returning each valid row read from the
110549 * storage of the backing table. The rowid will be the rowid of the
110550 * row from the backing table. "Valid" means:
110551 * - The cell metadata for the row is well-formed. Mainly this means that
110552 * the cell header info describes a payload of the size indicated by
110553 * the cell's payload size.
110554 * - The cell does not run off the page.
110555 * - The cell does not overlap any other cell on the page.
110556 * - The cell contains doesn't contain too many columns.
110557 * - The types of the serialized data match the indicated types (see below).
110560 * Type affinity versus type storage.
110562 * http://www.sqlite.org/datatype3.html describes SQLite's type
110563 * affinity system. The system provides for automated coercion of
110564 * types in certain cases, transparently enough that many developers
110565 * do not realize that it is happening. Importantly, it implies that
110566 * the raw data stored in the database may not have the obvious type.
110568 * Differences between the stored data types and the expected data
110569 * types may be a signal of corruption. This module makes some
110570 * allowances for automatic coercion. It is important to be concious
110571 * of the difference between the schema exposed by the module, and the
110572 * data types read from storage. The following table describes how
110573 * the module interprets things:
110575 * type schema data STRICT
110576 * ---- ------ ---- ------
110577 * ANY <none> any any
110578 * ROWID INTEGER n/a n/a
110579 * INTEGER INTEGER integer integer
110580 * FLOAT FLOAT integer or float float
110581 * NUMERIC NUMERIC integer, float, or text integer or float
110582 * TEXT TEXT text or blob text
110583 * BLOB BLOB blob blob
110585 * type is the type provided to the recover module, schema is the
110586 * schema exposed by the module, data is the acceptable types of data
110587 * decoded from storage, and STRICT is a modification of that.
110589 * A very loose recovery system might use ANY for all columns, then
110590 * use the appropriate sqlite3_column_*() calls to coerce to expected
110591 * types. This doesn't provide much protection if a page from a
110592 * different table with the same column count is linked into an
110593 * inappropriate btree.
110595 * A very tight recovery system might use STRICT to enforce typing on
110596 * all columns, preferring to skip rows which are valid at the storage
110597 * level but don't contain the right types. Note that FLOAT STRICT is
110598 * almost certainly not appropriate, since integral values are
110599 * transparently stored as integers, when that is more efficient.
110601 * Another option is to use ANY for all columns and inspect each
110602 * result manually (using sqlite3_column_*). This should only be
110603 * necessary in cases where developers have used manifest typing (test
110604 * to make sure before you decide that you aren't using manifest
110605 * typing!).
110608 * Caveats
110610 * Leaf pages not referenced by interior nodes will not be found.
110612 * Leaf pages referenced from interior nodes of other tables will not
110613 * be resolved.
110615 * Rows referencing invalid overflow pages will be skipped.
110617 * SQlite rows have a header which describes how to interpret the rest
110618 * of the payload. The header can be valid in cases where the rest of
110619 * the record is actually corrupt (in the sense that the data is not
110620 * the intended data). This can especially happen WRT overflow pages,
110621 * as lack of atomic updates between pages is the primary form of
110622 * corruption I have seen in the wild.
110624 /* The implementation is via a series of cursors. The cursor
110625 * implementations follow the pattern:
110627 * // Creates the cursor using various initialization info.
110628 * int cursorCreate(...);
110630 * // Returns 1 if there is no more data, 0 otherwise.
110631 * int cursorEOF(Cursor *pCursor);
110633 * // Various accessors can be used if not at EOF.
110635 * // Move to the next item.
110636 * int cursorNext(Cursor *pCursor);
110638 * // Destroy the memory associated with the cursor.
110639 * void cursorDestroy(Cursor *pCursor);
110641 * References in the following are to sections at
110642 * http://www.sqlite.org/fileformat2.html .
110644 * RecoverLeafCursor iterates the records in a leaf table node
110645 * described in section 1.5 "B-tree Pages". When the node is
110646 * exhausted, an interior cursor is used to get the next leaf node,
110647 * and iteration continues there.
110649 * RecoverInteriorCursor iterates the child pages in an interior table
110650 * node described in section 1.5 "B-tree Pages". When the node is
110651 * exhausted, a parent interior cursor is used to get the next
110652 * interior node at the same level, and iteration continues there.
110654 * Together these record the path from the leaf level to the root of
110655 * the tree. Iteration happens from the leaves rather than the root
110656 * both for efficiency and putting the special case at the front of
110657 * the list is easier to implement.
110659 * RecoverCursor uses a RecoverLeafCursor to iterate the rows of a
110660 * table, returning results via the SQLite virtual table interface.
110662 /* TODO(shess): It might be useful to allow DEFAULT in types to
110663 * specify what to do for NULL when an ALTER TABLE case comes up.
110664 * Unfortunately, simply adding it to the exposed schema and using
110665 * sqlite3_result_null() does not cause the default to be generate.
110666 * Handling it ourselves seems hard, unfortunately.
110670 /* Internal SQLite things that are used:
110671 * u32, u64, i64 types.
110672 * Btree, Pager, and DbPage structs.
110673 * DbPage.pData, .pPager, and .pgno
110674 * sqlite3 struct.
110675 * sqlite3BtreePager() and sqlite3BtreeGetPageSize()
110676 * sqlite3PagerAcquire() and sqlite3PagerUnref()
110677 * getVarint().
110680 /* For debugging. */
110681 #if 0
110682 #define FNENTRY() fprintf(stderr, "In %s\n", __FUNCTION__)
110683 #else
110684 #define FNENTRY()
110685 #endif
110687 /* Generic constants and helper functions. */
110689 static const unsigned char kTableLeafPage = 0x0D;
110690 static const unsigned char kTableInteriorPage = 0x05;
110692 /* From section 1.5. */
110693 static const unsigned kiPageTypeOffset = 0;
110694 static const unsigned kiPageFreeBlockOffset = 1;
110695 static const unsigned kiPageCellCountOffset = 3;
110696 static const unsigned kiPageCellContentOffset = 5;
110697 static const unsigned kiPageFragmentedBytesOffset = 7;
110698 static const unsigned knPageLeafHeaderBytes = 8;
110699 /* Interior pages contain an additional field. */
110700 static const unsigned kiPageRightChildOffset = 8;
110701 static const unsigned kiPageInteriorHeaderBytes = 12;
110703 /* Accepted types are specified by a mask. */
110704 #define MASK_ROWID (1<<0)
110705 #define MASK_INTEGER (1<<1)
110706 #define MASK_FLOAT (1<<2)
110707 #define MASK_TEXT (1<<3)
110708 #define MASK_BLOB (1<<4)
110709 #define MASK_NULL (1<<5)
110711 /* Helpers to decode fixed-size fields. */
110712 static u32 decodeUnsigned16(const unsigned char *pData){
110713 return (pData[0]<<8) + pData[1];
110715 static u32 decodeUnsigned32(const unsigned char *pData){
110716 return (decodeUnsigned16(pData)<<16) + decodeUnsigned16(pData+2);
110718 static i64 decodeSigned(const unsigned char *pData, unsigned nBytes){
110719 i64 r = (char)(*pData);
110720 while( --nBytes ){
110721 r <<= 8;
110722 r += *(++pData);
110724 return r;
110726 /* Derived from vdbeaux.c, sqlite3VdbeSerialGet(), case 7. */
110727 /* TODO(shess): Determine if swapMixedEndianFloat() applies. */
110728 static double decodeFloat64(const unsigned char *pData){
110729 #if !defined(NDEBUG)
110730 static const u64 t1 = ((u64)0x3ff00000)<<32;
110731 static const double r1 = 1.0;
110732 u64 t2 = t1;
110733 assert( sizeof(r1)==sizeof(t2) && memcmp(&r1, &t2, sizeof(r1))==0 );
110734 #endif
110735 i64 x = decodeSigned(pData, 8);
110736 double d;
110737 memcpy(&d, &x, sizeof(x));
110738 return d;
110741 /* Return true if a varint can safely be read from pData/nData. */
110742 /* TODO(shess): DbPage points into the middle of a buffer which
110743 * contains the page data before DbPage. So code should always be
110744 * able to read a small number of varints safely. Consider whether to
110745 * trust that or not.
110747 static int checkVarint(const unsigned char *pData, unsigned nData){
110748 unsigned i;
110750 /* In the worst case the decoder takes all 8 bits of the 9th byte. */
110751 if( nData>=9 ){
110752 return 1;
110755 /* Look for a high-bit-clear byte in what's left. */
110756 for( i=0; i<nData; ++i ){
110757 if( !(pData[i]&0x80) ){
110758 return 1;
110762 /* Cannot decode in the space given. */
110763 return 0;
110766 /* Return 1 if n varints can be read from pData/nData. */
110767 static int checkVarints(const unsigned char *pData, unsigned nData,
110768 unsigned n){
110769 unsigned nCur = 0; /* Byte offset within current varint. */
110770 unsigned nFound = 0; /* Number of varints found. */
110771 unsigned i;
110773 /* In the worst case the decoder takes all 8 bits of the 9th byte. */
110774 if( nData>=9*n ){
110775 return 1;
110778 for( i=0; nFound<n && i<nData; ++i ){
110779 nCur++;
110780 if( nCur==9 || !(pData[i]&0x80) ){
110781 nFound++;
110782 nCur = 0;
110786 return nFound==n;
110789 /* ctype and str[n]casecmp() can be affected by locale (eg, tr_TR).
110790 * These versions consider only the ASCII space.
110792 /* TODO(shess): It may be reasonable to just remove the need for these
110793 * entirely. The module could require "TEXT STRICT NOT NULL", not
110794 * "Text Strict Not Null" or whatever the developer felt like typing
110795 * that day. Handling corrupt data is a PERFECT place to be pedantic.
110797 static int ascii_isspace(char c){
110798 /* From fts3_expr.c */
110799 return c==' ' || c=='\t' || c=='\n' || c=='\r' || c=='\v' || c=='\f';
110801 static int ascii_isalnum(int x){
110802 /* From fts3_tokenizer1.c */
110803 return (x>='0' && x<='9') || (x>='A' && x<='Z') || (x>='a' && x<='z');
110805 static int ascii_tolower(int x){
110806 /* From fts3_tokenizer1.c */
110807 return (x>='A' && x<='Z') ? x-'A'+'a' : x;
110809 /* TODO(shess): Consider sqlite3_strnicmp() */
110810 static int ascii_strncasecmp(const char *s1, const char *s2, size_t n){
110811 const unsigned char *us1 = (const unsigned char *)s1;
110812 const unsigned char *us2 = (const unsigned char *)s2;
110813 while( *us1 && *us2 && n && ascii_tolower(*us1)==ascii_tolower(*us2) ){
110814 us1++, us2++, n--;
110816 return n ? ascii_tolower(*us1)-ascii_tolower(*us2) : 0;
110818 static int ascii_strcasecmp(const char *s1, const char *s2){
110819 /* If s2 is equal through strlen(s1), will exit while() due to s1's
110820 * trailing NUL, and return NUL-s2[strlen(s1)].
110822 return ascii_strncasecmp(s1, s2, strlen(s1)+1);
110825 /* For some reason I kept making mistakes with offset calculations. */
110826 static const unsigned char *PageData(DbPage *pPage, unsigned iOffset){
110827 assert( iOffset<=pPage->nPageSize );
110828 return (unsigned char *)pPage->pData + iOffset;
110831 /* The first page in the file contains a file header in the first 100
110832 * bytes. The page's header information comes after that. Note that
110833 * the offsets in the page's header information are relative to the
110834 * beginning of the page, NOT the end of the page header.
110836 static const unsigned char *PageHeader(DbPage *pPage){
110837 if( pPage->pgno==1 ){
110838 const unsigned nDatabaseHeader = 100;
110839 return PageData(pPage, nDatabaseHeader);
110840 }else{
110841 return PageData(pPage, 0);
110845 /* Helper to fetch the pager and page size for the named database. */
110846 static int GetPager(sqlite3 *db, const char *zName,
110847 Pager **pPager, unsigned *pnPageSize){
110848 Btree *pBt = NULL;
110849 int i;
110850 for( i=0; i<db->nDb; ++i ){
110851 if( ascii_strcasecmp(db->aDb[i].zName, zName)==0 ){
110852 pBt = db->aDb[i].pBt;
110853 break;
110856 if( !pBt ){
110857 return SQLITE_ERROR;
110860 *pPager = sqlite3BtreePager(pBt);
110861 *pnPageSize = sqlite3BtreeGetPageSize(pBt) - sqlite3BtreeGetReserve(pBt);
110862 return SQLITE_OK;
110865 /* iSerialType is a type read from a record header. See "2.1 Record Format".
110868 /* Storage size of iSerialType in bytes. My interpretation of SQLite
110869 * documentation is that text and blob fields can have 32-bit length.
110870 * Values past 2^31-12 will need more than 32 bits to encode, which is
110871 * why iSerialType is u64.
110873 static u32 SerialTypeLength(u64 iSerialType){
110874 switch( iSerialType ){
110875 case 0 : return 0; /* NULL */
110876 case 1 : return 1; /* Various integers. */
110877 case 2 : return 2;
110878 case 3 : return 3;
110879 case 4 : return 4;
110880 case 5 : return 6;
110881 case 6 : return 8;
110882 case 7 : return 8; /* 64-bit float. */
110883 case 8 : return 0; /* Constant 0. */
110884 case 9 : return 0; /* Constant 1. */
110885 case 10 : case 11 : assert( !"RESERVED TYPE"); return 0;
110887 return (u32)((iSerialType>>1) - 6);
110890 /* True if iSerialType refers to a blob. */
110891 static int SerialTypeIsBlob(u64 iSerialType){
110892 assert( iSerialType>=12 );
110893 return (iSerialType%2)==0;
110896 /* Returns true if the serialized type represented by iSerialType is
110897 * compatible with the given type mask.
110899 static int SerialTypeIsCompatible(u64 iSerialType, unsigned char mask){
110900 switch( iSerialType ){
110901 case 0 : return (mask&MASK_NULL)!=0;
110902 case 1 : return (mask&MASK_INTEGER)!=0;
110903 case 2 : return (mask&MASK_INTEGER)!=0;
110904 case 3 : return (mask&MASK_INTEGER)!=0;
110905 case 4 : return (mask&MASK_INTEGER)!=0;
110906 case 5 : return (mask&MASK_INTEGER)!=0;
110907 case 6 : return (mask&MASK_INTEGER)!=0;
110908 case 7 : return (mask&MASK_FLOAT)!=0;
110909 case 8 : return (mask&MASK_INTEGER)!=0;
110910 case 9 : return (mask&MASK_INTEGER)!=0;
110911 case 10 : assert( !"RESERVED TYPE"); return 0;
110912 case 11 : assert( !"RESERVED TYPE"); return 0;
110914 return (mask&(SerialTypeIsBlob(iSerialType) ? MASK_BLOB : MASK_TEXT));
110917 /* Versions of strdup() with return values appropriate for
110918 * sqlite3_free(). malloc.c has sqlite3DbStrDup()/NDup(), but those
110919 * need sqlite3DbFree(), which seems intrusive.
110921 static char *sqlite3_strndup(const char *z, unsigned n){
110922 char *zNew;
110924 if( z==NULL ){
110925 return NULL;
110928 zNew = sqlite3_malloc(n+1);
110929 if( zNew!=NULL ){
110930 memcpy(zNew, z, n);
110931 zNew[n] = '\0';
110933 return zNew;
110935 static char *sqlite3_strdup(const char *z){
110936 if( z==NULL ){
110937 return NULL;
110939 return sqlite3_strndup(z, strlen(z));
110942 /* Fetch the page number of zTable in zDb from sqlite_master in zDb,
110943 * and put it in *piRootPage.
110945 static int getRootPage(sqlite3 *db, const char *zDb, const char *zTable,
110946 u32 *piRootPage){
110947 char *zSql; /* SQL selecting root page of named element. */
110948 sqlite3_stmt *pStmt;
110949 int rc;
110951 if( strcmp(zTable, "sqlite_master")==0 ){
110952 *piRootPage = 1;
110953 return SQLITE_OK;
110956 zSql = sqlite3_mprintf("SELECT rootpage FROM %s.sqlite_master "
110957 "WHERE type = 'table' AND tbl_name = %Q",
110958 zDb, zTable);
110959 if( !zSql ){
110960 return SQLITE_NOMEM;
110963 rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
110964 sqlite3_free(zSql);
110965 if( rc!=SQLITE_OK ){
110966 return rc;
110969 /* Require a result. */
110970 rc = sqlite3_step(pStmt);
110971 if( rc==SQLITE_DONE ){
110972 rc = SQLITE_CORRUPT;
110973 }else if( rc==SQLITE_ROW ){
110974 *piRootPage = sqlite3_column_int(pStmt, 0);
110976 /* Require only one result. */
110977 rc = sqlite3_step(pStmt);
110978 if( rc==SQLITE_DONE ){
110979 rc = SQLITE_OK;
110980 }else if( rc==SQLITE_ROW ){
110981 rc = SQLITE_CORRUPT;
110984 sqlite3_finalize(pStmt);
110985 return rc;
110988 static int getEncoding(sqlite3 *db, const char *zDb, int* piEncoding){
110989 sqlite3_stmt *pStmt;
110990 int rc;
110991 char *zSql = sqlite3_mprintf("PRAGMA %s.encoding", zDb);
110992 if( !zSql ){
110993 return SQLITE_NOMEM;
110996 rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
110997 sqlite3_free(zSql);
110998 if( rc!=SQLITE_OK ){
110999 return rc;
111002 /* Require a result. */
111003 rc = sqlite3_step(pStmt);
111004 if( rc==SQLITE_DONE ){
111005 /* This case should not be possible. */
111006 rc = SQLITE_CORRUPT;
111007 }else if( rc==SQLITE_ROW ){
111008 if( sqlite3_column_type(pStmt, 0)==SQLITE_TEXT ){
111009 const char* z = (const char *)sqlite3_column_text(pStmt, 0);
111010 /* These strings match the literals in pragma.c. */
111011 if( !strcmp(z, "UTF-16le") ){
111012 *piEncoding = SQLITE_UTF16LE;
111013 }else if( !strcmp(z, "UTF-16be") ){
111014 *piEncoding = SQLITE_UTF16BE;
111015 }else if( !strcmp(z, "UTF-8") ){
111016 *piEncoding = SQLITE_UTF8;
111017 }else{
111018 /* This case should not be possible. */
111019 *piEncoding = SQLITE_UTF8;
111021 }else{
111022 /* This case should not be possible. */
111023 *piEncoding = SQLITE_UTF8;
111026 /* Require only one result. */
111027 rc = sqlite3_step(pStmt);
111028 if( rc==SQLITE_DONE ){
111029 rc = SQLITE_OK;
111030 }else if( rc==SQLITE_ROW ){
111031 /* This case should not be possible. */
111032 rc = SQLITE_CORRUPT;
111035 sqlite3_finalize(pStmt);
111036 return rc;
111039 /* Cursor for iterating interior nodes. Interior page cells contain a
111040 * child page number and a rowid. The child page contains items left
111041 * of the rowid (less than). The rightmost page of the subtree is
111042 * stored in the page header.
111044 * interiorCursorDestroy - release all resources associated with the
111045 * cursor and any parent cursors.
111046 * interiorCursorCreate - create a cursor with the given parent and page.
111047 * interiorCursorEOF - returns true if neither the cursor nor the
111048 * parent cursors can return any more data.
111049 * interiorCursorNextPage - fetch the next child page from the cursor.
111051 * Logically, interiorCursorNextPage() returns the next child page
111052 * number from the page the cursor is currently reading, calling the
111053 * parent cursor as necessary to get new pages to read, until done.
111054 * SQLITE_ROW if a page is returned, SQLITE_DONE if out of pages,
111055 * error otherwise. Unfortunately, if the table is corrupted
111056 * unexpected pages can be returned. If any unexpected page is found,
111057 * leaf or otherwise, it is returned to the caller for processing,
111058 * with the interior cursor left empty. The next call to
111059 * interiorCursorNextPage() will recurse to the parent cursor until an
111060 * interior page to iterate is returned.
111062 * Note that while interiorCursorNextPage() will refuse to follow
111063 * loops, it does not keep track of pages returned for purposes of
111064 * preventing duplication.
111066 * Note that interiorCursorEOF() could return false (not at EOF), and
111067 * interiorCursorNextPage() could still return SQLITE_DONE. This
111068 * could happen if there are more cells to iterate in an interior
111069 * page, but those cells refer to invalid pages.
111071 typedef struct RecoverInteriorCursor RecoverInteriorCursor;
111072 struct RecoverInteriorCursor {
111073 RecoverInteriorCursor *pParent; /* Parent node to this node. */
111074 DbPage *pPage; /* Reference to leaf page. */
111075 unsigned nPageSize; /* Size of page. */
111076 unsigned nChildren; /* Number of children on the page. */
111077 unsigned iChild; /* Index of next child to return. */
111080 static void interiorCursorDestroy(RecoverInteriorCursor *pCursor){
111081 /* Destroy all the cursors to the root. */
111082 while( pCursor ){
111083 RecoverInteriorCursor *p = pCursor;
111084 pCursor = pCursor->pParent;
111086 if( p->pPage ){
111087 sqlite3PagerUnref(p->pPage);
111088 p->pPage = NULL;
111091 memset(p, 0xA5, sizeof(*p));
111092 sqlite3_free(p);
111096 /* Internal helper. Reset storage in preparation for iterating pPage. */
111097 static void interiorCursorSetPage(RecoverInteriorCursor *pCursor,
111098 DbPage *pPage){
111099 assert( PageHeader(pPage)[kiPageTypeOffset]==kTableInteriorPage );
111101 if( pCursor->pPage ){
111102 sqlite3PagerUnref(pCursor->pPage);
111103 pCursor->pPage = NULL;
111105 pCursor->pPage = pPage;
111106 pCursor->iChild = 0;
111108 /* A child for each cell, plus one in the header. */
111109 /* TODO(shess): Sanity-check the count? Page header plus per-cell
111110 * cost of 16-bit offset, 32-bit page number, and one varint
111111 * (minimum 1 byte).
111113 pCursor->nChildren = decodeUnsigned16(PageHeader(pPage) +
111114 kiPageCellCountOffset) + 1;
111117 static int interiorCursorCreate(RecoverInteriorCursor *pParent,
111118 DbPage *pPage, int nPageSize,
111119 RecoverInteriorCursor **ppCursor){
111120 RecoverInteriorCursor *pCursor =
111121 sqlite3_malloc(sizeof(RecoverInteriorCursor));
111122 if( !pCursor ){
111123 return SQLITE_NOMEM;
111126 memset(pCursor, 0, sizeof(*pCursor));
111127 pCursor->pParent = pParent;
111128 pCursor->nPageSize = nPageSize;
111129 interiorCursorSetPage(pCursor, pPage);
111130 *ppCursor = pCursor;
111131 return SQLITE_OK;
111134 /* Internal helper. Return the child page number at iChild. */
111135 static unsigned interiorCursorChildPage(RecoverInteriorCursor *pCursor){
111136 const unsigned char *pPageHeader; /* Header of the current page. */
111137 const unsigned char *pCellOffsets; /* Offset to page's cell offsets. */
111138 unsigned iCellOffset; /* Offset of target cell. */
111140 assert( pCursor->iChild<pCursor->nChildren );
111142 /* Rightmost child is in the header. */
111143 pPageHeader = PageHeader(pCursor->pPage);
111144 if( pCursor->iChild==pCursor->nChildren-1 ){
111145 return decodeUnsigned32(pPageHeader + kiPageRightChildOffset);
111148 /* Each cell is a 4-byte integer page number and a varint rowid
111149 * which is greater than the rowid of items in that sub-tree (this
111150 * module ignores ordering). The offset is from the beginning of the
111151 * page, not from the page header.
111153 pCellOffsets = pPageHeader + kiPageInteriorHeaderBytes;
111154 iCellOffset = decodeUnsigned16(pCellOffsets + pCursor->iChild*2);
111155 if( iCellOffset<=pCursor->nPageSize-4 ){
111156 return decodeUnsigned32(PageData(pCursor->pPage, iCellOffset));
111159 /* TODO(shess): Check for cell overlaps? Cells require 4 bytes plus
111160 * a varint. Check could be identical to leaf check (or even a
111161 * shared helper testing for "Cells starting in this range"?).
111164 /* If the offset is broken, return an invalid page number. */
111165 return 0;
111168 static int interiorCursorEOF(RecoverInteriorCursor *pCursor){
111169 /* Find a parent with remaining children. EOF if none found. */
111170 while( pCursor && pCursor->iChild>=pCursor->nChildren ){
111171 pCursor = pCursor->pParent;
111173 return pCursor==NULL;
111176 /* Internal helper. Used to detect if iPage would cause a loop. */
111177 static int interiorCursorPageInUse(RecoverInteriorCursor *pCursor,
111178 unsigned iPage){
111179 /* Find any parent using the indicated page. */
111180 while( pCursor && pCursor->pPage->pgno!=iPage ){
111181 pCursor = pCursor->pParent;
111183 return pCursor!=NULL;
111186 /* Get the next page from the interior cursor at *ppCursor. Returns
111187 * SQLITE_ROW with the page in *ppPage, or SQLITE_DONE if out of
111188 * pages, or the error SQLite returned.
111190 * If the tree is uneven, then when the cursor attempts to get a new
111191 * interior page from the parent cursor, it may get a non-interior
111192 * page. In that case, the new page is returned, and *ppCursor is
111193 * updated to point to the parent cursor (this cursor is freed).
111195 /* TODO(shess): I've tried to avoid recursion in most of this code,
111196 * but this case is more challenging because the recursive call is in
111197 * the middle of operation. One option for converting it without
111198 * adding memory management would be to retain the head pointer and
111199 * use a helper to "back up" as needed. Another option would be to
111200 * reverse the list during traversal.
111202 static int interiorCursorNextPage(RecoverInteriorCursor **ppCursor,
111203 DbPage **ppPage){
111204 RecoverInteriorCursor *pCursor = *ppCursor;
111205 while( 1 ){
111206 int rc;
111207 const unsigned char *pPageHeader; /* Header of found page. */
111209 /* Find a valid child page which isn't on the stack. */
111210 while( pCursor->iChild<pCursor->nChildren ){
111211 const unsigned iPage = interiorCursorChildPage(pCursor);
111212 pCursor->iChild++;
111213 if( interiorCursorPageInUse(pCursor, iPage) ){
111214 fprintf(stderr, "Loop detected at %d\n", iPage);
111215 }else{
111216 int rc = sqlite3PagerAcquire(pCursor->pPage->pPager, iPage, ppPage, 0);
111217 if( rc==SQLITE_OK ){
111218 return SQLITE_ROW;
111223 /* This page has no more children. Get next page from parent. */
111224 if( !pCursor->pParent ){
111225 return SQLITE_DONE;
111227 rc = interiorCursorNextPage(&pCursor->pParent, ppPage);
111228 if( rc!=SQLITE_ROW ){
111229 return rc;
111232 /* If a non-interior page is received, that either means that the
111233 * tree is uneven, or that a child was re-used (say as an overflow
111234 * page). Remove this cursor and let the caller handle the page.
111236 pPageHeader = PageHeader(*ppPage);
111237 if( pPageHeader[kiPageTypeOffset]!=kTableInteriorPage ){
111238 *ppCursor = pCursor->pParent;
111239 pCursor->pParent = NULL;
111240 interiorCursorDestroy(pCursor);
111241 return SQLITE_ROW;
111244 /* Iterate the new page. */
111245 interiorCursorSetPage(pCursor, *ppPage);
111246 *ppPage = NULL;
111249 assert(NULL); /* NOTREACHED() */
111250 return SQLITE_CORRUPT;
111253 /* Large rows are spilled to overflow pages. The row's main page
111254 * stores the overflow page number after the local payload, with a
111255 * linked list forward from there as necessary. overflowMaybeCreate()
111256 * and overflowGetSegment() provide an abstraction for accessing such
111257 * data while centralizing the code.
111259 * overflowDestroy - releases all resources associated with the structure.
111260 * overflowMaybeCreate - create the overflow structure if it is needed
111261 * to represent the given record. See function comment.
111262 * overflowGetSegment - fetch a segment from the record, accounting
111263 * for overflow pages. Segments which are not
111264 * entirely contained with a page are constructed
111265 * into a buffer which is returned. See function comment.
111267 typedef struct RecoverOverflow RecoverOverflow;
111268 struct RecoverOverflow {
111269 RecoverOverflow *pNextOverflow;
111270 DbPage *pPage;
111271 unsigned nPageSize;
111274 static void overflowDestroy(RecoverOverflow *pOverflow){
111275 while( pOverflow ){
111276 RecoverOverflow *p = pOverflow;
111277 pOverflow = p->pNextOverflow;
111279 if( p->pPage ){
111280 sqlite3PagerUnref(p->pPage);
111281 p->pPage = NULL;
111284 memset(p, 0xA5, sizeof(*p));
111285 sqlite3_free(p);
111289 /* Internal helper. Used to detect if iPage would cause a loop. */
111290 static int overflowPageInUse(RecoverOverflow *pOverflow, unsigned iPage){
111291 while( pOverflow && pOverflow->pPage->pgno!=iPage ){
111292 pOverflow = pOverflow->pNextOverflow;
111294 return pOverflow!=NULL;
111297 /* Setup to access an nRecordBytes record beginning at iRecordOffset
111298 * in pPage. If nRecordBytes can be satisfied entirely from pPage,
111299 * then no overflow pages are needed an *pnLocalRecordBytes is set to
111300 * nRecordBytes. Otherwise, *ppOverflow is set to the head of a list
111301 * of overflow pages, and *pnLocalRecordBytes is set to the number of
111302 * bytes local to pPage.
111304 * overflowGetSegment() will do the right thing regardless of whether
111305 * those values are set to be in-page or not.
111307 static int overflowMaybeCreate(DbPage *pPage, unsigned nPageSize,
111308 unsigned iRecordOffset, unsigned nRecordBytes,
111309 unsigned *pnLocalRecordBytes,
111310 RecoverOverflow **ppOverflow){
111311 unsigned nLocalRecordBytes; /* Record bytes in the leaf page. */
111312 unsigned iNextPage; /* Next page number for record data. */
111313 unsigned nBytes; /* Maximum record bytes as of current page. */
111314 int rc;
111315 RecoverOverflow *pFirstOverflow; /* First in linked list of pages. */
111316 RecoverOverflow *pLastOverflow; /* End of linked list. */
111318 /* Calculations from the "Table B-Tree Leaf Cell" part of section
111319 * 1.5 of http://www.sqlite.org/fileformat2.html . maxLocal and
111320 * minLocal to match naming in btree.c.
111322 const unsigned maxLocal = nPageSize - 35;
111323 const unsigned minLocal = ((nPageSize-12)*32/255)-23; /* m */
111325 /* Always fit anything smaller than maxLocal. */
111326 if( nRecordBytes<=maxLocal ){
111327 *pnLocalRecordBytes = nRecordBytes;
111328 *ppOverflow = NULL;
111329 return SQLITE_OK;
111332 /* Calculate the remainder after accounting for minLocal on the leaf
111333 * page and what packs evenly into overflow pages. If the remainder
111334 * does not fit into maxLocal, then a partially-full overflow page
111335 * will be required in any case, so store as little as possible locally.
111337 nLocalRecordBytes = minLocal+((nRecordBytes-minLocal)%(nPageSize-4));
111338 if( maxLocal<nLocalRecordBytes ){
111339 nLocalRecordBytes = minLocal;
111342 /* Don't read off the end of the page. */
111343 if( iRecordOffset+nLocalRecordBytes+4>nPageSize ){
111344 return SQLITE_CORRUPT;
111347 /* First overflow page number is after the local bytes. */
111348 iNextPage =
111349 decodeUnsigned32(PageData(pPage, iRecordOffset + nLocalRecordBytes));
111350 nBytes = nLocalRecordBytes;
111352 /* While there are more pages to read, and more bytes are needed,
111353 * get another page.
111355 pFirstOverflow = pLastOverflow = NULL;
111356 rc = SQLITE_OK;
111357 while( iNextPage && nBytes<nRecordBytes ){
111358 RecoverOverflow *pOverflow; /* New overflow page for the list. */
111360 rc = sqlite3PagerAcquire(pPage->pPager, iNextPage, &pPage, 0);
111361 if( rc!=SQLITE_OK ){
111362 break;
111365 pOverflow = sqlite3_malloc(sizeof(RecoverOverflow));
111366 if( !pOverflow ){
111367 sqlite3PagerUnref(pPage);
111368 rc = SQLITE_NOMEM;
111369 break;
111371 memset(pOverflow, 0, sizeof(*pOverflow));
111372 pOverflow->pPage = pPage;
111373 pOverflow->nPageSize = nPageSize;
111375 if( !pFirstOverflow ){
111376 pFirstOverflow = pOverflow;
111377 }else{
111378 pLastOverflow->pNextOverflow = pOverflow;
111380 pLastOverflow = pOverflow;
111382 iNextPage = decodeUnsigned32(pPage->pData);
111383 nBytes += nPageSize-4;
111385 /* Avoid loops. */
111386 if( overflowPageInUse(pFirstOverflow, iNextPage) ){
111387 fprintf(stderr, "Overflow loop detected at %d\n", iNextPage);
111388 rc = SQLITE_CORRUPT;
111389 break;
111393 /* If there were not enough pages, or too many, things are corrupt.
111394 * Not having enough pages is an obvious problem, all the data
111395 * cannot be read. Too many pages means that the contents of the
111396 * row between the main page and the overflow page(s) is
111397 * inconsistent (most likely one or more of the overflow pages does
111398 * not really belong to this row).
111400 if( rc==SQLITE_OK && (nBytes<nRecordBytes || iNextPage) ){
111401 rc = SQLITE_CORRUPT;
111404 if( rc==SQLITE_OK ){
111405 *ppOverflow = pFirstOverflow;
111406 *pnLocalRecordBytes = nLocalRecordBytes;
111407 }else if( pFirstOverflow ){
111408 overflowDestroy(pFirstOverflow);
111410 return rc;
111413 /* Use in concert with overflowMaybeCreate() to efficiently read parts
111414 * of a potentially-overflowing record. pPage and iRecordOffset are
111415 * the values passed into overflowMaybeCreate(), nLocalRecordBytes and
111416 * pOverflow are the values returned by that call.
111418 * On SQLITE_OK, *ppBase points to nRequestBytes of data at
111419 * iRequestOffset within the record. If the data exists contiguously
111420 * in a page, a direct pointer is returned, otherwise a buffer from
111421 * sqlite3_malloc() is returned with the data. *pbFree is set true if
111422 * sqlite3_free() should be called on *ppBase.
111424 /* Operation of this function is subtle. At any time, pPage is the
111425 * current page, with iRecordOffset and nLocalRecordBytes being record
111426 * data within pPage, and pOverflow being the overflow page after
111427 * pPage. This allows the code to handle both the initial leaf page
111428 * and overflow pages consistently by adjusting the values
111429 * appropriately.
111431 static int overflowGetSegment(DbPage *pPage, unsigned iRecordOffset,
111432 unsigned nLocalRecordBytes,
111433 RecoverOverflow *pOverflow,
111434 unsigned iRequestOffset, unsigned nRequestBytes,
111435 unsigned char **ppBase, int *pbFree){
111436 unsigned nBase; /* Amount of data currently collected. */
111437 unsigned char *pBase; /* Buffer to collect record data into. */
111439 /* Skip to the page containing the start of the data. */
111440 while( iRequestOffset>=nLocalRecordBytes && pOverflow ){
111441 /* Factor out current page's contribution. */
111442 iRequestOffset -= nLocalRecordBytes;
111444 /* Move forward to the next page in the list. */
111445 pPage = pOverflow->pPage;
111446 iRecordOffset = 4;
111447 nLocalRecordBytes = pOverflow->nPageSize - iRecordOffset;
111448 pOverflow = pOverflow->pNextOverflow;
111451 /* If the requested data is entirely within this page, return a
111452 * pointer into the page.
111454 if( iRequestOffset+nRequestBytes<=nLocalRecordBytes ){
111455 /* TODO(shess): "assignment discards qualifiers from pointer target type"
111456 * Having ppBase be const makes sense, but sqlite3_free() takes non-const.
111458 *ppBase = (unsigned char *)PageData(pPage, iRecordOffset + iRequestOffset);
111459 *pbFree = 0;
111460 return SQLITE_OK;
111463 /* The data range would require additional pages. */
111464 if( !pOverflow ){
111465 /* Should never happen, the range is outside the nRecordBytes
111466 * passed to overflowMaybeCreate().
111468 assert(NULL); /* NOTREACHED */
111469 return SQLITE_ERROR;
111472 /* Get a buffer to construct into. */
111473 nBase = 0;
111474 pBase = sqlite3_malloc(nRequestBytes);
111475 if( !pBase ){
111476 return SQLITE_NOMEM;
111478 while( nBase<nRequestBytes ){
111479 /* Copy over data present on this page. */
111480 unsigned nCopyBytes = nRequestBytes - nBase;
111481 if( nLocalRecordBytes-iRequestOffset<nCopyBytes ){
111482 nCopyBytes = nLocalRecordBytes - iRequestOffset;
111484 memcpy(pBase + nBase, PageData(pPage, iRecordOffset + iRequestOffset),
111485 nCopyBytes);
111486 nBase += nCopyBytes;
111488 if( pOverflow ){
111489 /* Copy from start of record data in future pages. */
111490 iRequestOffset = 0;
111492 /* Move forward to the next page in the list. Should match
111493 * first while() loop.
111495 pPage = pOverflow->pPage;
111496 iRecordOffset = 4;
111497 nLocalRecordBytes = pOverflow->nPageSize - iRecordOffset;
111498 pOverflow = pOverflow->pNextOverflow;
111499 }else if( nBase<nRequestBytes ){
111500 /* Ran out of overflow pages with data left to deliver. Not
111501 * possible if the requested range fits within nRecordBytes
111502 * passed to overflowMaybeCreate() when creating pOverflow.
111504 assert(NULL); /* NOTREACHED */
111505 sqlite3_free(pBase);
111506 return SQLITE_ERROR;
111509 assert( nBase==nRequestBytes );
111510 *ppBase = pBase;
111511 *pbFree = 1;
111512 return SQLITE_OK;
111515 /* Primary structure for iterating the contents of a table.
111517 * leafCursorDestroy - release all resources associated with the cursor.
111518 * leafCursorCreate - create a cursor to iterate items from tree at
111519 * the provided root page.
111520 * leafCursorNextValidCell - get the cursor ready to access data from
111521 * the next valid cell in the table.
111522 * leafCursorCellRowid - get the current cell's rowid.
111523 * leafCursorCellColumns - get current cell's column count.
111524 * leafCursorCellColInfo - get type and data for a column in current cell.
111526 * leafCursorNextValidCell skips cells which fail simple integrity
111527 * checks, such as overlapping other cells, or being located at
111528 * impossible offsets, or where header data doesn't correctly describe
111529 * payload data. Returns SQLITE_ROW if a valid cell is found,
111530 * SQLITE_DONE if all pages in the tree were exhausted.
111532 * leafCursorCellColInfo() accounts for overflow pages in the style of
111533 * overflowGetSegment().
111535 typedef struct RecoverLeafCursor RecoverLeafCursor;
111536 struct RecoverLeafCursor {
111537 RecoverInteriorCursor *pParent; /* Parent node to this node. */
111538 DbPage *pPage; /* Reference to leaf page. */
111539 unsigned nPageSize; /* Size of pPage. */
111540 unsigned nCells; /* Number of cells in pPage. */
111541 unsigned iCell; /* Current cell. */
111543 /* Info parsed from data in iCell. */
111544 i64 iRowid; /* rowid parsed. */
111545 unsigned nRecordCols; /* how many items in the record. */
111546 u64 iRecordOffset; /* offset to record data. */
111547 /* TODO(shess): nRecordBytes and nRecordHeaderBytes are used in
111548 * leafCursorCellColInfo() to prevent buffer overruns.
111549 * leafCursorCellDecode() already verified that the cell is valid, so
111550 * those checks should be redundant.
111552 u64 nRecordBytes; /* Size of record data. */
111553 unsigned nLocalRecordBytes; /* Amount of record data in-page. */
111554 unsigned nRecordHeaderBytes; /* Size of record header data. */
111555 unsigned char *pRecordHeader; /* Pointer to record header data. */
111556 int bFreeRecordHeader; /* True if record header requires free. */
111557 RecoverOverflow *pOverflow; /* Cell overflow info, if needed. */
111560 /* Internal helper shared between next-page and create-cursor. If
111561 * pPage is a leaf page, it will be stored in the cursor and state
111562 * initialized for reading cells.
111564 * If pPage is an interior page, a new parent cursor is created and
111565 * injected on the stack. This is necessary to handle trees with
111566 * uneven depth, but also is used during initial setup.
111568 * If pPage is not a table page at all, it is discarded.
111570 * If SQLITE_OK is returned, the caller no longer owns pPage,
111571 * otherwise the caller is responsible for discarding it.
111573 static int leafCursorLoadPage(RecoverLeafCursor *pCursor, DbPage *pPage){
111574 const unsigned char *pPageHeader; /* Header of *pPage */
111576 /* Release the current page. */
111577 if( pCursor->pPage ){
111578 sqlite3PagerUnref(pCursor->pPage);
111579 pCursor->pPage = NULL;
111580 pCursor->iCell = pCursor->nCells = 0;
111583 /* If the page is an unexpected interior node, inject a new stack
111584 * layer and try again from there.
111586 pPageHeader = PageHeader(pPage);
111587 if( pPageHeader[kiPageTypeOffset]==kTableInteriorPage ){
111588 RecoverInteriorCursor *pParent;
111589 int rc = interiorCursorCreate(pCursor->pParent, pPage, pCursor->nPageSize,
111590 &pParent);
111591 if( rc!=SQLITE_OK ){
111592 return rc;
111594 pCursor->pParent = pParent;
111595 return SQLITE_OK;
111598 /* Not a leaf page, skip it. */
111599 if( pPageHeader[kiPageTypeOffset]!=kTableLeafPage ){
111600 sqlite3PagerUnref(pPage);
111601 return SQLITE_OK;
111604 /* Take ownership of the page and start decoding. */
111605 pCursor->pPage = pPage;
111606 pCursor->iCell = 0;
111607 pCursor->nCells = decodeUnsigned16(pPageHeader + kiPageCellCountOffset);
111608 return SQLITE_OK;
111611 /* Get the next leaf-level page in the tree. Returns SQLITE_ROW when
111612 * a leaf page is found, SQLITE_DONE when no more leaves exist, or any
111613 * error which occurred.
111615 static int leafCursorNextPage(RecoverLeafCursor *pCursor){
111616 if( !pCursor->pParent ){
111617 return SQLITE_DONE;
111620 /* Repeatedly load the parent's next child page until a leaf is found. */
111622 DbPage *pNextPage;
111623 int rc = interiorCursorNextPage(&pCursor->pParent, &pNextPage);
111624 if( rc!=SQLITE_ROW ){
111625 assert( rc==SQLITE_DONE );
111626 return rc;
111629 rc = leafCursorLoadPage(pCursor, pNextPage);
111630 if( rc!=SQLITE_OK ){
111631 sqlite3PagerUnref(pNextPage);
111632 return rc;
111634 } while( !pCursor->pPage );
111636 return SQLITE_ROW;
111639 static void leafCursorDestroyCellData(RecoverLeafCursor *pCursor){
111640 if( pCursor->bFreeRecordHeader ){
111641 sqlite3_free(pCursor->pRecordHeader);
111643 pCursor->bFreeRecordHeader = 0;
111644 pCursor->pRecordHeader = NULL;
111646 if( pCursor->pOverflow ){
111647 overflowDestroy(pCursor->pOverflow);
111648 pCursor->pOverflow = NULL;
111652 static void leafCursorDestroy(RecoverLeafCursor *pCursor){
111653 leafCursorDestroyCellData(pCursor);
111655 if( pCursor->pParent ){
111656 interiorCursorDestroy(pCursor->pParent);
111657 pCursor->pParent = NULL;
111660 if( pCursor->pPage ){
111661 sqlite3PagerUnref(pCursor->pPage);
111662 pCursor->pPage = NULL;
111665 memset(pCursor, 0xA5, sizeof(*pCursor));
111666 sqlite3_free(pCursor);
111669 /* Create a cursor to iterate the rows from the leaf pages of a table
111670 * rooted at iRootPage.
111672 /* TODO(shess): recoverOpen() calls this to setup the cursor, and I
111673 * think that recoverFilter() may make a hard assumption that the
111674 * cursor returned will turn up at least one valid cell.
111676 * The cases I can think of which break this assumption are:
111677 * - pPage is a valid leaf page with no valid cells.
111678 * - pPage is a valid interior page with no valid leaves.
111679 * - pPage is a valid interior page who's leaves contain no valid cells.
111680 * - pPage is not a valid leaf or interior page.
111682 static int leafCursorCreate(Pager *pPager, unsigned nPageSize,
111683 u32 iRootPage, RecoverLeafCursor **ppCursor){
111684 DbPage *pPage; /* Reference to page at iRootPage. */
111685 RecoverLeafCursor *pCursor; /* Leaf cursor being constructed. */
111686 int rc;
111688 /* Start out with the root page. */
111689 rc = sqlite3PagerAcquire(pPager, iRootPage, &pPage, 0);
111690 if( rc!=SQLITE_OK ){
111691 return rc;
111694 pCursor = sqlite3_malloc(sizeof(RecoverLeafCursor));
111695 if( !pCursor ){
111696 sqlite3PagerUnref(pPage);
111697 return SQLITE_NOMEM;
111699 memset(pCursor, 0, sizeof(*pCursor));
111701 pCursor->nPageSize = nPageSize;
111703 rc = leafCursorLoadPage(pCursor, pPage);
111704 if( rc!=SQLITE_OK ){
111705 sqlite3PagerUnref(pPage);
111706 leafCursorDestroy(pCursor);
111707 return rc;
111710 /* pPage wasn't a leaf page, find the next leaf page. */
111711 if( !pCursor->pPage ){
111712 rc = leafCursorNextPage(pCursor);
111713 if( rc!=SQLITE_DONE && rc!=SQLITE_ROW ){
111714 leafCursorDestroy(pCursor);
111715 return rc;
111719 *ppCursor = pCursor;
111720 return SQLITE_OK;
111723 /* Useful for setting breakpoints. */
111724 static int ValidateError(){
111725 return SQLITE_ERROR;
111728 /* Setup the cursor for reading the information from cell iCell. */
111729 static int leafCursorCellDecode(RecoverLeafCursor *pCursor){
111730 const unsigned char *pPageHeader; /* Header of current page. */
111731 const unsigned char *pCellOffsets; /* Pointer to page's cell offsets. */
111732 unsigned iCellOffset; /* Offset of current cell (iCell). */
111733 const unsigned char *pCell; /* Pointer to data at iCellOffset. */
111734 unsigned nCellMaxBytes; /* Maximum local size of iCell. */
111735 unsigned iEndOffset; /* End of iCell's in-page data. */
111736 u64 nRecordBytes; /* Expected size of cell, w/overflow. */
111737 u64 iRowid; /* iCell's rowid (in table). */
111738 unsigned nRead; /* Amount of cell read. */
111739 unsigned nRecordHeaderRead; /* Header data read. */
111740 u64 nRecordHeaderBytes; /* Header size expected. */
111741 unsigned nRecordCols; /* Columns read from header. */
111742 u64 nRecordColBytes; /* Bytes in payload for those columns. */
111743 unsigned i;
111744 int rc;
111746 assert( pCursor->iCell<pCursor->nCells );
111748 leafCursorDestroyCellData(pCursor);
111750 /* Find the offset to the row. */
111751 pPageHeader = PageHeader(pCursor->pPage);
111752 pCellOffsets = pPageHeader + knPageLeafHeaderBytes;
111753 iCellOffset = decodeUnsigned16(pCellOffsets + pCursor->iCell*2);
111754 if( iCellOffset>=pCursor->nPageSize ){
111755 return ValidateError();
111758 pCell = PageData(pCursor->pPage, iCellOffset);
111759 nCellMaxBytes = pCursor->nPageSize - iCellOffset;
111761 /* B-tree leaf cells lead with varint record size, varint rowid and
111762 * varint header size.
111764 /* TODO(shess): The smallest page size is 512 bytes, which has an m
111765 * of 39. Three varints need at most 27 bytes to encode. I think.
111767 if( !checkVarints(pCell, nCellMaxBytes, 3) ){
111768 return ValidateError();
111771 nRead = getVarint(pCell, &nRecordBytes);
111772 assert( iCellOffset+nRead<=pCursor->nPageSize );
111773 pCursor->nRecordBytes = nRecordBytes;
111775 nRead += getVarint(pCell + nRead, &iRowid);
111776 assert( iCellOffset+nRead<=pCursor->nPageSize );
111777 pCursor->iRowid = (i64)iRowid;
111779 pCursor->iRecordOffset = iCellOffset + nRead;
111781 /* Start overflow setup here because nLocalRecordBytes is needed to
111782 * check cell overlap.
111784 rc = overflowMaybeCreate(pCursor->pPage, pCursor->nPageSize,
111785 pCursor->iRecordOffset, pCursor->nRecordBytes,
111786 &pCursor->nLocalRecordBytes,
111787 &pCursor->pOverflow);
111788 if( rc!=SQLITE_OK ){
111789 return ValidateError();
111792 /* Check that no other cell starts within this cell. */
111793 iEndOffset = pCursor->iRecordOffset + pCursor->nLocalRecordBytes;
111794 for( i=0; i<pCursor->nCells; ++i ){
111795 const unsigned iOtherOffset = decodeUnsigned16(pCellOffsets + i*2);
111796 if( iOtherOffset>iCellOffset && iOtherOffset<iEndOffset ){
111797 return ValidateError();
111801 nRecordHeaderRead = getVarint(pCell + nRead, &nRecordHeaderBytes);
111802 assert( nRecordHeaderBytes<=nRecordBytes );
111803 pCursor->nRecordHeaderBytes = nRecordHeaderBytes;
111805 /* Large headers could overflow if pages are small. */
111806 rc = overflowGetSegment(pCursor->pPage,
111807 pCursor->iRecordOffset, pCursor->nLocalRecordBytes,
111808 pCursor->pOverflow, 0, nRecordHeaderBytes,
111809 &pCursor->pRecordHeader, &pCursor->bFreeRecordHeader);
111810 if( rc!=SQLITE_OK ){
111811 return ValidateError();
111814 /* Tally up the column count and size of data. */
111815 nRecordCols = 0;
111816 nRecordColBytes = 0;
111817 while( nRecordHeaderRead<nRecordHeaderBytes ){
111818 u64 iSerialType; /* Type descriptor for current column. */
111819 if( !checkVarint(pCursor->pRecordHeader + nRecordHeaderRead,
111820 nRecordHeaderBytes - nRecordHeaderRead) ){
111821 return ValidateError();
111823 nRecordHeaderRead += getVarint(pCursor->pRecordHeader + nRecordHeaderRead,
111824 &iSerialType);
111825 if( iSerialType==10 || iSerialType==11 ){
111826 return ValidateError();
111828 nRecordColBytes += SerialTypeLength(iSerialType);
111829 nRecordCols++;
111831 pCursor->nRecordCols = nRecordCols;
111833 /* Parsing the header used as many bytes as expected. */
111834 if( nRecordHeaderRead!=nRecordHeaderBytes ){
111835 return ValidateError();
111838 /* Calculated record is size of expected record. */
111839 if( nRecordHeaderBytes+nRecordColBytes!=nRecordBytes ){
111840 return ValidateError();
111843 return SQLITE_OK;
111846 static i64 leafCursorCellRowid(RecoverLeafCursor *pCursor){
111847 return pCursor->iRowid;
111850 static unsigned leafCursorCellColumns(RecoverLeafCursor *pCursor){
111851 return pCursor->nRecordCols;
111854 /* Get the column info for the cell. Pass NULL for ppBase to prevent
111855 * retrieving the data segment. If *pbFree is true, *ppBase must be
111856 * freed by the caller using sqlite3_free().
111858 static int leafCursorCellColInfo(RecoverLeafCursor *pCursor,
111859 unsigned iCol, u64 *piColType,
111860 unsigned char **ppBase, int *pbFree){
111861 const unsigned char *pRecordHeader; /* Current cell's header. */
111862 u64 nRecordHeaderBytes; /* Bytes in pRecordHeader. */
111863 unsigned nRead; /* Bytes read from header. */
111864 u64 iColEndOffset; /* Offset to end of column in cell. */
111865 unsigned nColsSkipped; /* Count columns as procesed. */
111866 u64 iSerialType; /* Type descriptor for current column. */
111868 /* Implicit NULL for columns past the end. This case happens when
111869 * rows have not been updated since an ALTER TABLE added columns.
111870 * It is more convenient to address here than in callers.
111872 if( iCol>=pCursor->nRecordCols ){
111873 *piColType = 0;
111874 if( ppBase ){
111875 *ppBase = 0;
111876 *pbFree = 0;
111878 return SQLITE_OK;
111881 /* Must be able to decode header size. */
111882 pRecordHeader = pCursor->pRecordHeader;
111883 if( !checkVarint(pRecordHeader, pCursor->nRecordHeaderBytes) ){
111884 return SQLITE_CORRUPT;
111887 /* Rather than caching the header size and how many bytes it took,
111888 * decode it every time.
111890 nRead = getVarint(pRecordHeader, &nRecordHeaderBytes);
111891 assert( nRecordHeaderBytes==pCursor->nRecordHeaderBytes );
111893 /* Scan forward to the indicated column. Scans to _after_ column
111894 * for later range checking.
111896 /* TODO(shess): This could get expensive for very wide tables. An
111897 * array of iSerialType could be built in leafCursorCellDecode(), but
111898 * the number of columns is dynamic per row, so it would add memory
111899 * management complexity. Enough info to efficiently forward
111900 * iterate could be kept, if all clients forward iterate
111901 * (recoverColumn() may not).
111903 iColEndOffset = 0;
111904 nColsSkipped = 0;
111905 while( nColsSkipped<=iCol && nRead<nRecordHeaderBytes ){
111906 if( !checkVarint(pRecordHeader + nRead, nRecordHeaderBytes - nRead) ){
111907 return SQLITE_CORRUPT;
111909 nRead += getVarint(pRecordHeader + nRead, &iSerialType);
111910 iColEndOffset += SerialTypeLength(iSerialType);
111911 nColsSkipped++;
111914 /* Column's data extends past record's end. */
111915 if( nRecordHeaderBytes+iColEndOffset>pCursor->nRecordBytes ){
111916 return SQLITE_CORRUPT;
111919 *piColType = iSerialType;
111920 if( ppBase ){
111921 const u32 nColBytes = SerialTypeLength(iSerialType);
111923 /* Offset from start of record to beginning of column. */
111924 const unsigned iColOffset = nRecordHeaderBytes+iColEndOffset-nColBytes;
111926 return overflowGetSegment(pCursor->pPage, pCursor->iRecordOffset,
111927 pCursor->nLocalRecordBytes, pCursor->pOverflow,
111928 iColOffset, nColBytes, ppBase, pbFree);
111930 return SQLITE_OK;
111933 static int leafCursorNextValidCell(RecoverLeafCursor *pCursor){
111934 while( 1 ){
111935 int rc;
111937 /* Move to the next cell. */
111938 pCursor->iCell++;
111940 /* No more cells, get the next leaf. */
111941 if( pCursor->iCell>=pCursor->nCells ){
111942 rc = leafCursorNextPage(pCursor);
111943 if( rc!=SQLITE_ROW ){
111944 return rc;
111946 assert( pCursor->iCell==0 );
111949 /* If the cell is valid, indicate that a row is available. */
111950 rc = leafCursorCellDecode(pCursor);
111951 if( rc==SQLITE_OK ){
111952 return SQLITE_ROW;
111955 /* Iterate until done or a valid row is found. */
111956 /* TODO(shess): Remove debugging output. */
111957 fprintf(stderr, "Skipping invalid cell\n");
111959 return SQLITE_ERROR;
111962 typedef struct Recover Recover;
111963 struct Recover {
111964 sqlite3_vtab base;
111965 sqlite3 *db; /* Host database connection */
111966 char *zDb; /* Database containing target table */
111967 char *zTable; /* Target table */
111968 unsigned nCols; /* Number of columns in target table */
111969 unsigned char *pTypes; /* Types of columns in target table */
111972 /* Internal helper for deleting the module. */
111973 static void recoverRelease(Recover *pRecover){
111974 sqlite3_free(pRecover->zDb);
111975 sqlite3_free(pRecover->zTable);
111976 sqlite3_free(pRecover->pTypes);
111977 memset(pRecover, 0xA5, sizeof(*pRecover));
111978 sqlite3_free(pRecover);
111981 /* Helper function for initializing the module. Forward-declared so
111982 * recoverCreate() and recoverConnect() can see it.
111984 static int recoverInit(
111985 sqlite3 *, void *, int, const char *const*, sqlite3_vtab **, char **
111988 static int recoverCreate(
111989 sqlite3 *db,
111990 void *pAux,
111991 int argc, const char *const*argv,
111992 sqlite3_vtab **ppVtab,
111993 char **pzErr
111995 FNENTRY();
111996 return recoverInit(db, pAux, argc, argv, ppVtab, pzErr);
111999 /* This should never be called. */
112000 static int recoverConnect(
112001 sqlite3 *db,
112002 void *pAux,
112003 int argc, const char *const*argv,
112004 sqlite3_vtab **ppVtab,
112005 char **pzErr
112007 FNENTRY();
112008 return recoverInit(db, pAux, argc, argv, ppVtab, pzErr);
112011 /* No indices supported. */
112012 static int recoverBestIndex(sqlite3_vtab *tab, sqlite3_index_info *pIdxInfo){
112013 FNENTRY();
112014 return SQLITE_OK;
112017 /* Logically, this should never be called. */
112018 static int recoverDisconnect(sqlite3_vtab *pVtab){
112019 FNENTRY();
112020 recoverRelease((Recover*)pVtab);
112021 return SQLITE_OK;
112024 static int recoverDestroy(sqlite3_vtab *pVtab){
112025 FNENTRY();
112026 recoverRelease((Recover*)pVtab);
112027 return SQLITE_OK;
112030 typedef struct RecoverCursor RecoverCursor;
112031 struct RecoverCursor {
112032 sqlite3_vtab_cursor base;
112033 RecoverLeafCursor *pLeafCursor;
112034 int iEncoding;
112035 int bEOF;
112038 static int recoverOpen(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor){
112039 Recover *pRecover = (Recover*)pVTab;
112040 u32 iRootPage; /* Root page of the backing table. */
112041 int iEncoding; /* UTF encoding for backing database. */
112042 unsigned nPageSize; /* Size of pages in backing database. */
112043 Pager *pPager; /* Backing database pager. */
112044 RecoverLeafCursor *pLeafCursor; /* Cursor to read table's leaf pages. */
112045 RecoverCursor *pCursor; /* Cursor to read rows from leaves. */
112046 int rc;
112048 FNENTRY();
112050 iRootPage = 0;
112051 rc = getRootPage(pRecover->db, pRecover->zDb, pRecover->zTable,
112052 &iRootPage);
112053 if( rc!=SQLITE_OK ){
112054 return rc;
112057 iEncoding = 0;
112058 rc = getEncoding(pRecover->db, pRecover->zDb, &iEncoding);
112059 if( rc!=SQLITE_OK ){
112060 return rc;
112063 rc = GetPager(pRecover->db, pRecover->zDb, &pPager, &nPageSize);
112064 if( rc!=SQLITE_OK ){
112065 return rc;
112068 rc = leafCursorCreate(pPager, nPageSize, iRootPage, &pLeafCursor);
112069 if( rc!=SQLITE_OK ){
112070 return rc;
112073 pCursor = sqlite3_malloc(sizeof(RecoverCursor));
112074 if( !pCursor ){
112075 leafCursorDestroy(pLeafCursor);
112076 return SQLITE_NOMEM;
112078 memset(pCursor, 0, sizeof(*pCursor));
112079 pCursor->base.pVtab = pVTab;
112080 pCursor->pLeafCursor = pLeafCursor;
112081 pCursor->iEncoding = iEncoding;
112083 *ppCursor = (sqlite3_vtab_cursor*)pCursor;
112084 return SQLITE_OK;
112087 static int recoverClose(sqlite3_vtab_cursor *cur){
112088 RecoverCursor *pCursor = (RecoverCursor*)cur;
112089 FNENTRY();
112090 if( pCursor->pLeafCursor ){
112091 leafCursorDestroy(pCursor->pLeafCursor);
112092 pCursor->pLeafCursor = NULL;
112094 memset(pCursor, 0xA5, sizeof(*pCursor));
112095 sqlite3_free(cur);
112096 return SQLITE_OK;
112099 /* Helpful place to set a breakpoint. */
112100 static int RecoverInvalidCell(){
112101 return SQLITE_ERROR;
112104 /* Returns SQLITE_OK if the cell has an appropriate number of columns
112105 * with the appropriate types of data.
112107 static int recoverValidateLeafCell(Recover *pRecover, RecoverCursor *pCursor){
112108 unsigned i;
112110 /* If the row's storage has too many columns, skip it. */
112111 if( leafCursorCellColumns(pCursor->pLeafCursor)>pRecover->nCols ){
112112 return RecoverInvalidCell();
112115 /* Skip rows with unexpected types. */
112116 for( i=0; i<pRecover->nCols; ++i ){
112117 u64 iType; /* Storage type of column i. */
112118 int rc;
112120 /* ROWID alias. */
112121 if( (pRecover->pTypes[i]&MASK_ROWID) ){
112122 continue;
112125 rc = leafCursorCellColInfo(pCursor->pLeafCursor, i, &iType, NULL, NULL);
112126 assert( rc==SQLITE_OK );
112127 if( rc!=SQLITE_OK || !SerialTypeIsCompatible(iType, pRecover->pTypes[i]) ){
112128 return RecoverInvalidCell();
112132 return SQLITE_OK;
112135 static int recoverNext(sqlite3_vtab_cursor *pVtabCursor){
112136 RecoverCursor *pCursor = (RecoverCursor*)pVtabCursor;
112137 Recover *pRecover = (Recover*)pCursor->base.pVtab;
112138 int rc;
112140 FNENTRY();
112142 /* Scan forward to the next cell with valid storage, then check that
112143 * the stored data matches the schema.
112145 while( (rc = leafCursorNextValidCell(pCursor->pLeafCursor))==SQLITE_ROW ){
112146 if( recoverValidateLeafCell(pRecover, pCursor)==SQLITE_OK ){
112147 return SQLITE_OK;
112151 if( rc==SQLITE_DONE ){
112152 pCursor->bEOF = 1;
112153 return SQLITE_OK;
112156 assert( rc!=SQLITE_OK );
112157 return rc;
112160 static int recoverFilter(
112161 sqlite3_vtab_cursor *pVtabCursor,
112162 int idxNum, const char *idxStr,
112163 int argc, sqlite3_value **argv
112165 RecoverCursor *pCursor = (RecoverCursor*)pVtabCursor;
112166 Recover *pRecover = (Recover*)pCursor->base.pVtab;
112167 int rc;
112169 FNENTRY();
112171 /* Load the first cell, and iterate forward if it's not valid. */
112172 /* TODO(shess): What happens if no cells at all are valid? */
112173 rc = leafCursorCellDecode(pCursor->pLeafCursor);
112174 if( rc!=SQLITE_OK || recoverValidateLeafCell(pRecover, pCursor)!=SQLITE_OK ){
112175 return recoverNext(pVtabCursor);
112178 return SQLITE_OK;
112181 static int recoverEof(sqlite3_vtab_cursor *pVtabCursor){
112182 RecoverCursor *pCursor = (RecoverCursor*)pVtabCursor;
112183 FNENTRY();
112184 return pCursor->bEOF;
112187 static int recoverColumn(sqlite3_vtab_cursor *cur, sqlite3_context *ctx, int i){
112188 RecoverCursor *pCursor = (RecoverCursor*)cur;
112189 Recover *pRecover = (Recover*)pCursor->base.pVtab;
112190 u64 iColType; /* Storage type of column i. */
112191 unsigned char *pColData; /* Column i's data. */
112192 int shouldFree; /* Non-zero if pColData should be freed. */
112193 int rc;
112195 FNENTRY();
112197 if( i>=pRecover->nCols ){
112198 return SQLITE_ERROR;
112201 /* ROWID alias. */
112202 if( (pRecover->pTypes[i]&MASK_ROWID) ){
112203 sqlite3_result_int64(ctx, leafCursorCellRowid(pCursor->pLeafCursor));
112204 return SQLITE_OK;
112207 pColData = NULL;
112208 shouldFree = 0;
112209 rc = leafCursorCellColInfo(pCursor->pLeafCursor, i, &iColType,
112210 &pColData, &shouldFree);
112211 if( rc!=SQLITE_OK ){
112212 return rc;
112214 /* recoverValidateLeafCell() should guarantee that this will never
112215 * occur.
112217 if( !SerialTypeIsCompatible(iColType, pRecover->pTypes[i]) ){
112218 if( shouldFree ){
112219 sqlite3_free(pColData);
112221 return SQLITE_ERROR;
112224 switch( iColType ){
112225 case 0 : sqlite3_result_null(ctx); break;
112226 case 1 : sqlite3_result_int64(ctx, decodeSigned(pColData, 1)); break;
112227 case 2 : sqlite3_result_int64(ctx, decodeSigned(pColData, 2)); break;
112228 case 3 : sqlite3_result_int64(ctx, decodeSigned(pColData, 3)); break;
112229 case 4 : sqlite3_result_int64(ctx, decodeSigned(pColData, 4)); break;
112230 case 5 : sqlite3_result_int64(ctx, decodeSigned(pColData, 6)); break;
112231 case 6 : sqlite3_result_int64(ctx, decodeSigned(pColData, 8)); break;
112232 case 7 : sqlite3_result_double(ctx, decodeFloat64(pColData)); break;
112233 case 8 : sqlite3_result_int(ctx, 0); break;
112234 case 9 : sqlite3_result_int(ctx, 1); break;
112235 case 10 : assert( iColType!=10 ); break;
112236 case 11 : assert( iColType!=11 ); break;
112238 default : {
112239 u32 l = SerialTypeLength(iColType);
112241 /* If pColData was already allocated, arrange to pass ownership. */
112242 sqlite3_destructor_type pFn = SQLITE_TRANSIENT;
112243 if( shouldFree ){
112244 pFn = sqlite3_free;
112245 shouldFree = 0;
112248 if( SerialTypeIsBlob(iColType) ){
112249 sqlite3_result_blob(ctx, pColData, l, pFn);
112250 }else{
112251 if( pCursor->iEncoding==SQLITE_UTF16LE ){
112252 sqlite3_result_text16le(ctx, (const void*)pColData, l, pFn);
112253 }else if( pCursor->iEncoding==SQLITE_UTF16BE ){
112254 sqlite3_result_text16be(ctx, (const void*)pColData, l, pFn);
112255 }else{
112256 sqlite3_result_text(ctx, (const char*)pColData, l, pFn);
112259 } break;
112261 if( shouldFree ){
112262 sqlite3_free(pColData);
112264 return SQLITE_OK;
112267 static int recoverRowid(sqlite3_vtab_cursor *pVtabCursor, sqlite_int64 *pRowid){
112268 RecoverCursor *pCursor = (RecoverCursor*)pVtabCursor;
112269 FNENTRY();
112270 *pRowid = leafCursorCellRowid(pCursor->pLeafCursor);
112271 return SQLITE_OK;
112274 static sqlite3_module recoverModule = {
112275 0, /* iVersion */
112276 recoverCreate, /* xCreate - create a table */
112277 recoverConnect, /* xConnect - connect to an existing table */
112278 recoverBestIndex, /* xBestIndex - Determine search strategy */
112279 recoverDisconnect, /* xDisconnect - Disconnect from a table */
112280 recoverDestroy, /* xDestroy - Drop a table */
112281 recoverOpen, /* xOpen - open a cursor */
112282 recoverClose, /* xClose - close a cursor */
112283 recoverFilter, /* xFilter - configure scan constraints */
112284 recoverNext, /* xNext - advance a cursor */
112285 recoverEof, /* xEof */
112286 recoverColumn, /* xColumn - read data */
112287 recoverRowid, /* xRowid - read data */
112288 0, /* xUpdate - write data */
112289 0, /* xBegin - begin transaction */
112290 0, /* xSync - sync transaction */
112291 0, /* xCommit - commit transaction */
112292 0, /* xRollback - rollback transaction */
112293 0, /* xFindFunction - function overloading */
112294 0, /* xRename - rename the table */
112297 int recoverVtableInit(sqlite3 *db){
112298 return sqlite3_create_module_v2(db, "recover", &recoverModule, NULL, 0);
112301 /* This section of code is for parsing the create input and
112302 * initializing the module.
112305 /* Find the next word in zText and place the endpoints in pzWord*.
112306 * Returns true if the word is non-empty. "Word" is defined as
112307 * ASCII alphanumeric plus '_' at this time.
112309 static int findWord(const char *zText,
112310 const char **pzWordStart, const char **pzWordEnd){
112311 int r;
112312 while( ascii_isspace(*zText) ){
112313 zText++;
112315 *pzWordStart = zText;
112316 while( ascii_isalnum(*zText) || *zText=='_' ){
112317 zText++;
112319 r = zText>*pzWordStart; /* In case pzWordStart==pzWordEnd */
112320 *pzWordEnd = zText;
112321 return r;
112324 /* Return true if the next word in zText is zWord, also setting
112325 * *pzContinue to the character after the word.
112327 static int expectWord(const char *zText, const char *zWord,
112328 const char **pzContinue){
112329 const char *zWordStart, *zWordEnd;
112330 if( findWord(zText, &zWordStart, &zWordEnd) &&
112331 ascii_strncasecmp(zWord, zWordStart, zWordEnd - zWordStart)==0 ){
112332 *pzContinue = zWordEnd;
112333 return 1;
112335 return 0;
112338 /* Parse the name and type information out of parameter. In case of
112339 * success, *pzNameStart/End contain the name of the column,
112340 * *pzTypeStart/End contain the top-level type, and *pTypeMask has the
112341 * type mask to use for the column.
112343 static int findNameAndType(const char *parameter,
112344 const char **pzNameStart, const char **pzNameEnd,
112345 const char **pzTypeStart, const char **pzTypeEnd,
112346 unsigned char *pTypeMask){
112347 unsigned nNameLen; /* Length of found name. */
112348 const char *zEnd; /* Current end of parsed column information. */
112349 int bNotNull; /* Non-zero if NULL is not allowed for name. */
112350 int bStrict; /* Non-zero if column requires exact type match. */
112351 const char *zDummy; /* Dummy parameter, result unused. */
112352 unsigned i;
112354 /* strictMask is used for STRICT, strictMask|otherMask if STRICT is
112355 * not supplied. zReplace provides an alternate type to expose to
112356 * the caller.
112358 static struct {
112359 const char *zName;
112360 unsigned char strictMask;
112361 unsigned char otherMask;
112362 const char *zReplace;
112363 } kTypeInfo[] = {
112364 { "ANY",
112365 MASK_INTEGER | MASK_FLOAT | MASK_BLOB | MASK_TEXT | MASK_NULL,
112366 0, "",
112368 { "ROWID", MASK_INTEGER | MASK_ROWID, 0, "INTEGER", },
112369 { "INTEGER", MASK_INTEGER | MASK_NULL, 0, NULL, },
112370 { "FLOAT", MASK_FLOAT | MASK_NULL, MASK_INTEGER, NULL, },
112371 { "NUMERIC", MASK_INTEGER | MASK_FLOAT | MASK_NULL, MASK_TEXT, NULL, },
112372 { "TEXT", MASK_TEXT | MASK_NULL, MASK_BLOB, NULL, },
112373 { "BLOB", MASK_BLOB | MASK_NULL, 0, NULL, },
112376 if( !findWord(parameter, pzNameStart, pzNameEnd) ){
112377 return SQLITE_MISUSE;
112380 /* Manifest typing, accept any storage type. */
112381 if( !findWord(*pzNameEnd, pzTypeStart, pzTypeEnd) ){
112382 *pzTypeEnd = *pzTypeStart = "";
112383 *pTypeMask = MASK_INTEGER | MASK_FLOAT | MASK_BLOB | MASK_TEXT | MASK_NULL;
112384 return SQLITE_OK;
112387 nNameLen = *pzTypeEnd - *pzTypeStart;
112388 for( i=0; i<ArraySize(kTypeInfo); ++i ){
112389 if( ascii_strncasecmp(kTypeInfo[i].zName, *pzTypeStart, nNameLen)==0 ){
112390 break;
112393 if( i==ArraySize(kTypeInfo) ){
112394 return SQLITE_MISUSE;
112397 zEnd = *pzTypeEnd;
112398 bStrict = 0;
112399 if( expectWord(zEnd, "STRICT", &zEnd) ){
112400 /* TODO(shess): Ick. But I don't want another single-purpose
112401 * flag, either.
112403 if( kTypeInfo[i].zReplace && !kTypeInfo[i].zReplace[0] ){
112404 return SQLITE_MISUSE;
112406 bStrict = 1;
112409 bNotNull = 0;
112410 if( expectWord(zEnd, "NOT", &zEnd) ){
112411 if( expectWord(zEnd, "NULL", &zEnd) ){
112412 bNotNull = 1;
112413 }else{
112414 /* Anything other than NULL after NOT is an error. */
112415 return SQLITE_MISUSE;
112419 /* Anything else is an error. */
112420 if( findWord(zEnd, &zDummy, &zDummy) ){
112421 return SQLITE_MISUSE;
112424 *pTypeMask = kTypeInfo[i].strictMask;
112425 if( !bStrict ){
112426 *pTypeMask |= kTypeInfo[i].otherMask;
112428 if( bNotNull ){
112429 *pTypeMask &= ~MASK_NULL;
112431 if( kTypeInfo[i].zReplace ){
112432 *pzTypeStart = kTypeInfo[i].zReplace;
112433 *pzTypeEnd = *pzTypeStart + strlen(*pzTypeStart);
112435 return SQLITE_OK;
112438 /* Parse the arguments, placing type masks in *pTypes and the exposed
112439 * schema in *pzCreateSql (for sqlite3_declare_vtab).
112441 static int ParseColumnsAndGenerateCreate(unsigned nCols,
112442 const char *const *pCols,
112443 char **pzCreateSql,
112444 unsigned char *pTypes,
112445 char **pzErr){
112446 unsigned i;
112447 char *zCreateSql = sqlite3_mprintf("CREATE TABLE x(");
112448 if( !zCreateSql ){
112449 return SQLITE_NOMEM;
112452 for( i=0; i<nCols; i++ ){
112453 const char *zSep = (i < nCols - 1 ? ", " : ")");
112454 const char *zNotNull = "";
112455 const char *zNameStart, *zNameEnd;
112456 const char *zTypeStart, *zTypeEnd;
112457 int rc = findNameAndType(pCols[i],
112458 &zNameStart, &zNameEnd,
112459 &zTypeStart, &zTypeEnd,
112460 &pTypes[i]);
112461 if( rc!=SQLITE_OK ){
112462 *pzErr = sqlite3_mprintf("unable to parse column %d", i);
112463 sqlite3_free(zCreateSql);
112464 return rc;
112467 if( !(pTypes[i]&MASK_NULL) ){
112468 zNotNull = " NOT NULL";
112471 /* Add name and type to the create statement. */
112472 zCreateSql = sqlite3_mprintf("%z%.*s %.*s%s%s",
112473 zCreateSql,
112474 zNameEnd - zNameStart, zNameStart,
112475 zTypeEnd - zTypeStart, zTypeStart,
112476 zNotNull, zSep);
112477 if( !zCreateSql ){
112478 return SQLITE_NOMEM;
112482 *pzCreateSql = zCreateSql;
112483 return SQLITE_OK;
112486 /* Helper function for initializing the module. */
112487 /* argv[0] module name
112488 * argv[1] db name for virtual table
112489 * argv[2] virtual table name
112490 * argv[3] backing table name
112491 * argv[4] columns
112493 /* TODO(shess): Since connect isn't supported, could inline into
112494 * recoverCreate().
112496 /* TODO(shess): Explore cases where it would make sense to set *pzErr. */
112497 static int recoverInit(
112498 sqlite3 *db, /* Database connection */
112499 void *pAux, /* unused */
112500 int argc, const char *const*argv, /* Parameters to CREATE TABLE statement */
112501 sqlite3_vtab **ppVtab, /* OUT: New virtual table */
112502 char **pzErr /* OUT: Error message, if any */
112504 const unsigned kTypeCol = 4; /* First argument with column type info. */
112505 Recover *pRecover; /* Virtual table structure being created. */
112506 char *zDot; /* Any dot found in "db.table" backing. */
112507 u32 iRootPage; /* Root page of backing table. */
112508 char *zCreateSql; /* Schema of created virtual table. */
112509 int rc;
112511 /* Require to be in the temp database. */
112512 if( ascii_strcasecmp(argv[1], "temp")!=0 ){
112513 *pzErr = sqlite3_mprintf("recover table must be in temp database");
112514 return SQLITE_MISUSE;
112517 /* Need the backing table and at least one column. */
112518 if( argc<=kTypeCol ){
112519 *pzErr = sqlite3_mprintf("no columns specified");
112520 return SQLITE_MISUSE;
112523 pRecover = sqlite3_malloc(sizeof(Recover));
112524 if( !pRecover ){
112525 return SQLITE_NOMEM;
112527 memset(pRecover, 0, sizeof(*pRecover));
112528 pRecover->base.pModule = &recoverModule;
112529 pRecover->db = db;
112531 /* Parse out db.table, assuming main if no dot. */
112532 zDot = strchr(argv[3], '.');
112533 if( !zDot ){
112534 pRecover->zDb = sqlite3_strdup(db->aDb[0].zName);
112535 pRecover->zTable = sqlite3_strdup(argv[3]);
112536 }else if( zDot>argv[3] && zDot[1]!='\0' ){
112537 pRecover->zDb = sqlite3_strndup(argv[3], zDot - argv[3]);
112538 pRecover->zTable = sqlite3_strdup(zDot + 1);
112539 }else{
112540 /* ".table" or "db." not allowed. */
112541 *pzErr = sqlite3_mprintf("ill-formed table specifier");
112542 recoverRelease(pRecover);
112543 return SQLITE_ERROR;
112546 pRecover->nCols = argc - kTypeCol;
112547 pRecover->pTypes = sqlite3_malloc(pRecover->nCols);
112548 if( !pRecover->zDb || !pRecover->zTable || !pRecover->pTypes ){
112549 recoverRelease(pRecover);
112550 return SQLITE_NOMEM;
112553 /* Require the backing table to exist. */
112554 /* TODO(shess): Be more pedantic about the form of the descriptor
112555 * string. This already fails for poorly-formed strings, simply
112556 * because there won't be a root page, but it would make more sense
112557 * to be explicit.
112559 rc = getRootPage(pRecover->db, pRecover->zDb, pRecover->zTable, &iRootPage);
112560 if( rc!=SQLITE_OK ){
112561 *pzErr = sqlite3_mprintf("unable to find backing table");
112562 recoverRelease(pRecover);
112563 return rc;
112566 /* Parse the column definitions. */
112567 rc = ParseColumnsAndGenerateCreate(pRecover->nCols, argv + kTypeCol,
112568 &zCreateSql, pRecover->pTypes, pzErr);
112569 if( rc!=SQLITE_OK ){
112570 recoverRelease(pRecover);
112571 return rc;
112574 rc = sqlite3_declare_vtab(db, zCreateSql);
112575 sqlite3_free(zCreateSql);
112576 if( rc!=SQLITE_OK ){
112577 recoverRelease(pRecover);
112578 return rc;
112581 *ppVtab = (sqlite3_vtab *)pRecover;
112582 return SQLITE_OK;
112585 /************** End of recover.c *********************************************/
112586 /************** Begin file fts3.c ********************************************/
112588 ** 2006 Oct 10
112590 ** The author disclaims copyright to this source code. In place of
112591 ** a legal notice, here is a blessing:
112593 ** May you do good and not evil.
112594 ** May you find forgiveness for yourself and forgive others.
112595 ** May you share freely, never taking more than you give.
112597 ******************************************************************************
112599 ** This is an SQLite module implementing full-text search.
112603 ** The code in this file is only compiled if:
112605 ** * The FTS3 module is being built as an extension
112606 ** (in which case SQLITE_CORE is not defined), or
112608 ** * The FTS3 module is being built into the core of
112609 ** SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
112612 /* The full-text index is stored in a series of b+tree (-like)
112613 ** structures called segments which map terms to doclists. The
112614 ** structures are like b+trees in layout, but are constructed from the
112615 ** bottom up in optimal fashion and are not updatable. Since trees
112616 ** are built from the bottom up, things will be described from the
112617 ** bottom up.
112620 **** Varints ****
112621 ** The basic unit of encoding is a variable-length integer called a
112622 ** varint. We encode variable-length integers in little-endian order
112623 ** using seven bits * per byte as follows:
112625 ** KEY:
112626 ** A = 0xxxxxxx 7 bits of data and one flag bit
112627 ** B = 1xxxxxxx 7 bits of data and one flag bit
112629 ** 7 bits - A
112630 ** 14 bits - BA
112631 ** 21 bits - BBA
112632 ** and so on.
112634 ** This is similar in concept to how sqlite encodes "varints" but
112635 ** the encoding is not the same. SQLite varints are big-endian
112636 ** are are limited to 9 bytes in length whereas FTS3 varints are
112637 ** little-endian and can be up to 10 bytes in length (in theory).
112639 ** Example encodings:
112641 ** 1: 0x01
112642 ** 127: 0x7f
112643 ** 128: 0x81 0x00
112646 **** Document lists ****
112647 ** A doclist (document list) holds a docid-sorted list of hits for a
112648 ** given term. Doclists hold docids and associated token positions.
112649 ** A docid is the unique integer identifier for a single document.
112650 ** A position is the index of a word within the document. The first
112651 ** word of the document has a position of 0.
112653 ** FTS3 used to optionally store character offsets using a compile-time
112654 ** option. But that functionality is no longer supported.
112656 ** A doclist is stored like this:
112658 ** array {
112659 ** varint docid;
112660 ** array { (position list for column 0)
112661 ** varint position; (2 more than the delta from previous position)
112663 ** array {
112664 ** varint POS_COLUMN; (marks start of position list for new column)
112665 ** varint column; (index of new column)
112666 ** array {
112667 ** varint position; (2 more than the delta from previous position)
112670 ** varint POS_END; (marks end of positions for this document.
112673 ** Here, array { X } means zero or more occurrences of X, adjacent in
112674 ** memory. A "position" is an index of a token in the token stream
112675 ** generated by the tokenizer. Note that POS_END and POS_COLUMN occur
112676 ** in the same logical place as the position element, and act as sentinals
112677 ** ending a position list array. POS_END is 0. POS_COLUMN is 1.
112678 ** The positions numbers are not stored literally but rather as two more
112679 ** than the difference from the prior position, or the just the position plus
112680 ** 2 for the first position. Example:
112682 ** label: A B C D E F G H I J K
112683 ** value: 123 5 9 1 1 14 35 0 234 72 0
112685 ** The 123 value is the first docid. For column zero in this document
112686 ** there are two matches at positions 3 and 10 (5-2 and 9-2+3). The 1
112687 ** at D signals the start of a new column; the 1 at E indicates that the
112688 ** new column is column number 1. There are two positions at 12 and 45
112689 ** (14-2 and 35-2+12). The 0 at H indicate the end-of-document. The
112690 ** 234 at I is the next docid. It has one position 72 (72-2) and then
112691 ** terminates with the 0 at K.
112693 ** A "position-list" is the list of positions for multiple columns for
112694 ** a single docid. A "column-list" is the set of positions for a single
112695 ** column. Hence, a position-list consists of one or more column-lists,
112696 ** a document record consists of a docid followed by a position-list and
112697 ** a doclist consists of one or more document records.
112699 ** A bare doclist omits the position information, becoming an
112700 ** array of varint-encoded docids.
112702 **** Segment leaf nodes ****
112703 ** Segment leaf nodes store terms and doclists, ordered by term. Leaf
112704 ** nodes are written using LeafWriter, and read using LeafReader (to
112705 ** iterate through a single leaf node's data) and LeavesReader (to
112706 ** iterate through a segment's entire leaf layer). Leaf nodes have
112707 ** the format:
112709 ** varint iHeight; (height from leaf level, always 0)
112710 ** varint nTerm; (length of first term)
112711 ** char pTerm[nTerm]; (content of first term)
112712 ** varint nDoclist; (length of term's associated doclist)
112713 ** char pDoclist[nDoclist]; (content of doclist)
112714 ** array {
112715 ** (further terms are delta-encoded)
112716 ** varint nPrefix; (length of prefix shared with previous term)
112717 ** varint nSuffix; (length of unshared suffix)
112718 ** char pTermSuffix[nSuffix];(unshared suffix of next term)
112719 ** varint nDoclist; (length of term's associated doclist)
112720 ** char pDoclist[nDoclist]; (content of doclist)
112723 ** Here, array { X } means zero or more occurrences of X, adjacent in
112724 ** memory.
112726 ** Leaf nodes are broken into blocks which are stored contiguously in
112727 ** the %_segments table in sorted order. This means that when the end
112728 ** of a node is reached, the next term is in the node with the next
112729 ** greater node id.
112731 ** New data is spilled to a new leaf node when the current node
112732 ** exceeds LEAF_MAX bytes (default 2048). New data which itself is
112733 ** larger than STANDALONE_MIN (default 1024) is placed in a standalone
112734 ** node (a leaf node with a single term and doclist). The goal of
112735 ** these settings is to pack together groups of small doclists while
112736 ** making it efficient to directly access large doclists. The
112737 ** assumption is that large doclists represent terms which are more
112738 ** likely to be query targets.
112740 ** TODO(shess) It may be useful for blocking decisions to be more
112741 ** dynamic. For instance, it may make more sense to have a 2.5k leaf
112742 ** node rather than splitting into 2k and .5k nodes. My intuition is
112743 ** that this might extend through 2x or 4x the pagesize.
112746 **** Segment interior nodes ****
112747 ** Segment interior nodes store blockids for subtree nodes and terms
112748 ** to describe what data is stored by the each subtree. Interior
112749 ** nodes are written using InteriorWriter, and read using
112750 ** InteriorReader. InteriorWriters are created as needed when
112751 ** SegmentWriter creates new leaf nodes, or when an interior node
112752 ** itself grows too big and must be split. The format of interior
112753 ** nodes:
112755 ** varint iHeight; (height from leaf level, always >0)
112756 ** varint iBlockid; (block id of node's leftmost subtree)
112757 ** optional {
112758 ** varint nTerm; (length of first term)
112759 ** char pTerm[nTerm]; (content of first term)
112760 ** array {
112761 ** (further terms are delta-encoded)
112762 ** varint nPrefix; (length of shared prefix with previous term)
112763 ** varint nSuffix; (length of unshared suffix)
112764 ** char pTermSuffix[nSuffix]; (unshared suffix of next term)
112768 ** Here, optional { X } means an optional element, while array { X }
112769 ** means zero or more occurrences of X, adjacent in memory.
112771 ** An interior node encodes n terms separating n+1 subtrees. The
112772 ** subtree blocks are contiguous, so only the first subtree's blockid
112773 ** is encoded. The subtree at iBlockid will contain all terms less
112774 ** than the first term encoded (or all terms if no term is encoded).
112775 ** Otherwise, for terms greater than or equal to pTerm[i] but less
112776 ** than pTerm[i+1], the subtree for that term will be rooted at
112777 ** iBlockid+i. Interior nodes only store enough term data to
112778 ** distinguish adjacent children (if the rightmost term of the left
112779 ** child is "something", and the leftmost term of the right child is
112780 ** "wicked", only "w" is stored).
112782 ** New data is spilled to a new interior node at the same height when
112783 ** the current node exceeds INTERIOR_MAX bytes (default 2048).
112784 ** INTERIOR_MIN_TERMS (default 7) keeps large terms from monopolizing
112785 ** interior nodes and making the tree too skinny. The interior nodes
112786 ** at a given height are naturally tracked by interior nodes at
112787 ** height+1, and so on.
112790 **** Segment directory ****
112791 ** The segment directory in table %_segdir stores meta-information for
112792 ** merging and deleting segments, and also the root node of the
112793 ** segment's tree.
112795 ** The root node is the top node of the segment's tree after encoding
112796 ** the entire segment, restricted to ROOT_MAX bytes (default 1024).
112797 ** This could be either a leaf node or an interior node. If the top
112798 ** node requires more than ROOT_MAX bytes, it is flushed to %_segments
112799 ** and a new root interior node is generated (which should always fit
112800 ** within ROOT_MAX because it only needs space for 2 varints, the
112801 ** height and the blockid of the previous root).
112803 ** The meta-information in the segment directory is:
112804 ** level - segment level (see below)
112805 ** idx - index within level
112806 ** - (level,idx uniquely identify a segment)
112807 ** start_block - first leaf node
112808 ** leaves_end_block - last leaf node
112809 ** end_block - last block (including interior nodes)
112810 ** root - contents of root node
112812 ** If the root node is a leaf node, then start_block,
112813 ** leaves_end_block, and end_block are all 0.
112816 **** Segment merging ****
112817 ** To amortize update costs, segments are grouped into levels and
112818 ** merged in batches. Each increase in level represents exponentially
112819 ** more documents.
112821 ** New documents (actually, document updates) are tokenized and
112822 ** written individually (using LeafWriter) to a level 0 segment, with
112823 ** incrementing idx. When idx reaches MERGE_COUNT (default 16), all
112824 ** level 0 segments are merged into a single level 1 segment. Level 1
112825 ** is populated like level 0, and eventually MERGE_COUNT level 1
112826 ** segments are merged to a single level 2 segment (representing
112827 ** MERGE_COUNT^2 updates), and so on.
112829 ** A segment merge traverses all segments at a given level in
112830 ** parallel, performing a straightforward sorted merge. Since segment
112831 ** leaf nodes are written in to the %_segments table in order, this
112832 ** merge traverses the underlying sqlite disk structures efficiently.
112833 ** After the merge, all segment blocks from the merged level are
112834 ** deleted.
112836 ** MERGE_COUNT controls how often we merge segments. 16 seems to be
112837 ** somewhat of a sweet spot for insertion performance. 32 and 64 show
112838 ** very similar performance numbers to 16 on insertion, though they're
112839 ** a tiny bit slower (perhaps due to more overhead in merge-time
112840 ** sorting). 8 is about 20% slower than 16, 4 about 50% slower than
112841 ** 16, 2 about 66% slower than 16.
112843 ** At query time, high MERGE_COUNT increases the number of segments
112844 ** which need to be scanned and merged. For instance, with 100k docs
112845 ** inserted:
112847 ** MERGE_COUNT segments
112848 ** 16 25
112849 ** 8 12
112850 ** 4 10
112851 ** 2 6
112853 ** This appears to have only a moderate impact on queries for very
112854 ** frequent terms (which are somewhat dominated by segment merge
112855 ** costs), and infrequent and non-existent terms still seem to be fast
112856 ** even with many segments.
112858 ** TODO(shess) That said, it would be nice to have a better query-side
112859 ** argument for MERGE_COUNT of 16. Also, it is possible/likely that
112860 ** optimizations to things like doclist merging will swing the sweet
112861 ** spot around.
112865 **** Handling of deletions and updates ****
112866 ** Since we're using a segmented structure, with no docid-oriented
112867 ** index into the term index, we clearly cannot simply update the term
112868 ** index when a document is deleted or updated. For deletions, we
112869 ** write an empty doclist (varint(docid) varint(POS_END)), for updates
112870 ** we simply write the new doclist. Segment merges overwrite older
112871 ** data for a particular docid with newer data, so deletes or updates
112872 ** will eventually overtake the earlier data and knock it out. The
112873 ** query logic likewise merges doclists so that newer data knocks out
112874 ** older data.
112876 ** TODO(shess) Provide a VACUUM type operation to clear out all
112877 ** deletions and duplications. This would basically be a forced merge
112878 ** into a single segment.
112880 #define CHROMIUM_FTS3_CHANGES 1
112882 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
112884 #if defined(SQLITE_ENABLE_FTS3) && !defined(SQLITE_CORE)
112885 # define SQLITE_CORE 1
112886 #endif
112888 /************** Include fts3Int.h in the middle of fts3.c ********************/
112889 /************** Begin file fts3Int.h *****************************************/
112891 ** 2009 Nov 12
112893 ** The author disclaims copyright to this source code. In place of
112894 ** a legal notice, here is a blessing:
112896 ** May you do good and not evil.
112897 ** May you find forgiveness for yourself and forgive others.
112898 ** May you share freely, never taking more than you give.
112900 ******************************************************************************
112904 #ifndef _FTSINT_H
112905 #define _FTSINT_H
112907 #if !defined(NDEBUG) && !defined(SQLITE_DEBUG)
112908 # define NDEBUG 1
112909 #endif
112911 /************** Include fts3_tokenizer.h in the middle of fts3Int.h **********/
112912 /************** Begin file fts3_tokenizer.h **********************************/
112914 ** 2006 July 10
112916 ** The author disclaims copyright to this source code.
112918 *************************************************************************
112919 ** Defines the interface to tokenizers used by fulltext-search. There
112920 ** are three basic components:
112922 ** sqlite3_tokenizer_module is a singleton defining the tokenizer
112923 ** interface functions. This is essentially the class structure for
112924 ** tokenizers.
112926 ** sqlite3_tokenizer is used to define a particular tokenizer, perhaps
112927 ** including customization information defined at creation time.
112929 ** sqlite3_tokenizer_cursor is generated by a tokenizer to generate
112930 ** tokens from a particular input.
112932 #ifndef _FTS3_TOKENIZER_H_
112933 #define _FTS3_TOKENIZER_H_
112935 /* TODO(shess) Only used for SQLITE_OK and SQLITE_DONE at this time.
112936 ** If tokenizers are to be allowed to call sqlite3_*() functions, then
112937 ** we will need a way to register the API consistently.
112941 ** Structures used by the tokenizer interface. When a new tokenizer
112942 ** implementation is registered, the caller provides a pointer to
112943 ** an sqlite3_tokenizer_module containing pointers to the callback
112944 ** functions that make up an implementation.
112946 ** When an fts3 table is created, it passes any arguments passed to
112947 ** the tokenizer clause of the CREATE VIRTUAL TABLE statement to the
112948 ** sqlite3_tokenizer_module.xCreate() function of the requested tokenizer
112949 ** implementation. The xCreate() function in turn returns an
112950 ** sqlite3_tokenizer structure representing the specific tokenizer to
112951 ** be used for the fts3 table (customized by the tokenizer clause arguments).
112953 ** To tokenize an input buffer, the sqlite3_tokenizer_module.xOpen()
112954 ** method is called. It returns an sqlite3_tokenizer_cursor object
112955 ** that may be used to tokenize a specific input buffer based on
112956 ** the tokenization rules supplied by a specific sqlite3_tokenizer
112957 ** object.
112959 typedef struct sqlite3_tokenizer_module sqlite3_tokenizer_module;
112960 typedef struct sqlite3_tokenizer sqlite3_tokenizer;
112961 typedef struct sqlite3_tokenizer_cursor sqlite3_tokenizer_cursor;
112963 struct sqlite3_tokenizer_module {
112966 ** Structure version. Should always be set to 0.
112968 int iVersion;
112971 ** Create a new tokenizer. The values in the argv[] array are the
112972 ** arguments passed to the "tokenizer" clause of the CREATE VIRTUAL
112973 ** TABLE statement that created the fts3 table. For example, if
112974 ** the following SQL is executed:
112976 ** CREATE .. USING fts3( ... , tokenizer <tokenizer-name> arg1 arg2)
112978 ** then argc is set to 2, and the argv[] array contains pointers
112979 ** to the strings "arg1" and "arg2".
112981 ** This method should return either SQLITE_OK (0), or an SQLite error
112982 ** code. If SQLITE_OK is returned, then *ppTokenizer should be set
112983 ** to point at the newly created tokenizer structure. The generic
112984 ** sqlite3_tokenizer.pModule variable should not be initialised by
112985 ** this callback. The caller will do so.
112987 int (*xCreate)(
112988 int argc, /* Size of argv array */
112989 const char *const*argv, /* Tokenizer argument strings */
112990 sqlite3_tokenizer **ppTokenizer /* OUT: Created tokenizer */
112994 ** Destroy an existing tokenizer. The fts3 module calls this method
112995 ** exactly once for each successful call to xCreate().
112997 int (*xDestroy)(sqlite3_tokenizer *pTokenizer);
113000 ** Create a tokenizer cursor to tokenize an input buffer. The caller
113001 ** is responsible for ensuring that the input buffer remains valid
113002 ** until the cursor is closed (using the xClose() method).
113004 int (*xOpen)(
113005 sqlite3_tokenizer *pTokenizer, /* Tokenizer object */
113006 const char *pInput, int nBytes, /* Input buffer */
113007 sqlite3_tokenizer_cursor **ppCursor /* OUT: Created tokenizer cursor */
113011 ** Destroy an existing tokenizer cursor. The fts3 module calls this
113012 ** method exactly once for each successful call to xOpen().
113014 int (*xClose)(sqlite3_tokenizer_cursor *pCursor);
113017 ** Retrieve the next token from the tokenizer cursor pCursor. This
113018 ** method should either return SQLITE_OK and set the values of the
113019 ** "OUT" variables identified below, or SQLITE_DONE to indicate that
113020 ** the end of the buffer has been reached, or an SQLite error code.
113022 ** *ppToken should be set to point at a buffer containing the
113023 ** normalized version of the token (i.e. after any case-folding and/or
113024 ** stemming has been performed). *pnBytes should be set to the length
113025 ** of this buffer in bytes. The input text that generated the token is
113026 ** identified by the byte offsets returned in *piStartOffset and
113027 ** *piEndOffset. *piStartOffset should be set to the index of the first
113028 ** byte of the token in the input buffer. *piEndOffset should be set
113029 ** to the index of the first byte just past the end of the token in
113030 ** the input buffer.
113032 ** The buffer *ppToken is set to point at is managed by the tokenizer
113033 ** implementation. It is only required to be valid until the next call
113034 ** to xNext() or xClose().
113036 /* TODO(shess) current implementation requires pInput to be
113037 ** nul-terminated. This should either be fixed, or pInput/nBytes
113038 ** should be converted to zInput.
113040 int (*xNext)(
113041 sqlite3_tokenizer_cursor *pCursor, /* Tokenizer cursor */
113042 const char **ppToken, int *pnBytes, /* OUT: Normalized text for token */
113043 int *piStartOffset, /* OUT: Byte offset of token in input buffer */
113044 int *piEndOffset, /* OUT: Byte offset of end of token in input buffer */
113045 int *piPosition /* OUT: Number of tokens returned before this one */
113049 struct sqlite3_tokenizer {
113050 const sqlite3_tokenizer_module *pModule; /* The module for this tokenizer */
113051 /* Tokenizer implementations will typically add additional fields */
113054 struct sqlite3_tokenizer_cursor {
113055 sqlite3_tokenizer *pTokenizer; /* Tokenizer for this cursor. */
113056 /* Tokenizer implementations will typically add additional fields */
113059 int fts3_global_term_cnt(int iTerm, int iCol);
113060 int fts3_term_cnt(int iTerm, int iCol);
113063 #endif /* _FTS3_TOKENIZER_H_ */
113065 /************** End of fts3_tokenizer.h **************************************/
113066 /************** Continuing where we left off in fts3Int.h ********************/
113067 /************** Include fts3_hash.h in the middle of fts3Int.h ***************/
113068 /************** Begin file fts3_hash.h ***************************************/
113070 ** 2001 September 22
113072 ** The author disclaims copyright to this source code. In place of
113073 ** a legal notice, here is a blessing:
113075 ** May you do good and not evil.
113076 ** May you find forgiveness for yourself and forgive others.
113077 ** May you share freely, never taking more than you give.
113079 *************************************************************************
113080 ** This is the header file for the generic hash-table implemenation
113081 ** used in SQLite. We've modified it slightly to serve as a standalone
113082 ** hash table implementation for the full-text indexing module.
113085 #ifndef _FTS3_HASH_H_
113086 #define _FTS3_HASH_H_
113088 /* Forward declarations of structures. */
113089 typedef struct Fts3Hash Fts3Hash;
113090 typedef struct Fts3HashElem Fts3HashElem;
113092 /* A complete hash table is an instance of the following structure.
113093 ** The internals of this structure are intended to be opaque -- client
113094 ** code should not attempt to access or modify the fields of this structure
113095 ** directly. Change this structure only by using the routines below.
113096 ** However, many of the "procedures" and "functions" for modifying and
113097 ** accessing this structure are really macros, so we can't really make
113098 ** this structure opaque.
113100 struct Fts3Hash {
113101 char keyClass; /* HASH_INT, _POINTER, _STRING, _BINARY */
113102 char copyKey; /* True if copy of key made on insert */
113103 int count; /* Number of entries in this table */
113104 Fts3HashElem *first; /* The first element of the array */
113105 int htsize; /* Number of buckets in the hash table */
113106 struct _fts3ht { /* the hash table */
113107 int count; /* Number of entries with this hash */
113108 Fts3HashElem *chain; /* Pointer to first entry with this hash */
113109 } *ht;
113112 /* Each element in the hash table is an instance of the following
113113 ** structure. All elements are stored on a single doubly-linked list.
113115 ** Again, this structure is intended to be opaque, but it can't really
113116 ** be opaque because it is used by macros.
113118 struct Fts3HashElem {
113119 Fts3HashElem *next, *prev; /* Next and previous elements in the table */
113120 void *data; /* Data associated with this element */
113121 void *pKey; int nKey; /* Key associated with this element */
113125 ** There are 2 different modes of operation for a hash table:
113127 ** FTS3_HASH_STRING pKey points to a string that is nKey bytes long
113128 ** (including the null-terminator, if any). Case
113129 ** is respected in comparisons.
113131 ** FTS3_HASH_BINARY pKey points to binary data nKey bytes long.
113132 ** memcmp() is used to compare keys.
113134 ** A copy of the key is made if the copyKey parameter to fts3HashInit is 1.
113136 #define FTS3_HASH_STRING 1
113137 #define FTS3_HASH_BINARY 2
113140 ** Access routines. To delete, insert a NULL pointer.
113142 SQLITE_PRIVATE void sqlite3Fts3HashInit(Fts3Hash *pNew, char keyClass, char copyKey);
113143 SQLITE_PRIVATE void *sqlite3Fts3HashInsert(Fts3Hash*, const void *pKey, int nKey, void *pData);
113144 SQLITE_PRIVATE void *sqlite3Fts3HashFind(const Fts3Hash*, const void *pKey, int nKey);
113145 SQLITE_PRIVATE void sqlite3Fts3HashClear(Fts3Hash*);
113146 SQLITE_PRIVATE Fts3HashElem *sqlite3Fts3HashFindElem(const Fts3Hash *, const void *, int);
113149 ** Shorthand for the functions above
113151 #define fts3HashInit sqlite3Fts3HashInit
113152 #define fts3HashInsert sqlite3Fts3HashInsert
113153 #define fts3HashFind sqlite3Fts3HashFind
113154 #define fts3HashClear sqlite3Fts3HashClear
113155 #define fts3HashFindElem sqlite3Fts3HashFindElem
113158 ** Macros for looping over all elements of a hash table. The idiom is
113159 ** like this:
113161 ** Fts3Hash h;
113162 ** Fts3HashElem *p;
113163 ** ...
113164 ** for(p=fts3HashFirst(&h); p; p=fts3HashNext(p)){
113165 ** SomeStructure *pData = fts3HashData(p);
113166 ** // do something with pData
113169 #define fts3HashFirst(H) ((H)->first)
113170 #define fts3HashNext(E) ((E)->next)
113171 #define fts3HashData(E) ((E)->data)
113172 #define fts3HashKey(E) ((E)->pKey)
113173 #define fts3HashKeysize(E) ((E)->nKey)
113176 ** Number of entries in a hash table
113178 #define fts3HashCount(H) ((H)->count)
113180 #endif /* _FTS3_HASH_H_ */
113182 /************** End of fts3_hash.h *******************************************/
113183 /************** Continuing where we left off in fts3Int.h ********************/
113186 ** This constant controls how often segments are merged. Once there are
113187 ** FTS3_MERGE_COUNT segments of level N, they are merged into a single
113188 ** segment of level N+1.
113190 #define FTS3_MERGE_COUNT 16
113193 ** This is the maximum amount of data (in bytes) to store in the
113194 ** Fts3Table.pendingTerms hash table. Normally, the hash table is
113195 ** populated as documents are inserted/updated/deleted in a transaction
113196 ** and used to create a new segment when the transaction is committed.
113197 ** However if this limit is reached midway through a transaction, a new
113198 ** segment is created and the hash table cleared immediately.
113200 #define FTS3_MAX_PENDING_DATA (1*1024*1024)
113203 ** Macro to return the number of elements in an array. SQLite has a
113204 ** similar macro called ArraySize(). Use a different name to avoid
113205 ** a collision when building an amalgamation with built-in FTS3.
113207 #define SizeofArray(X) ((int)(sizeof(X)/sizeof(X[0])))
113210 ** Maximum length of a varint encoded integer. The varint format is different
113211 ** from that used by SQLite, so the maximum length is 10, not 9.
113213 #define FTS3_VARINT_MAX 10
113216 ** The testcase() macro is only used by the amalgamation. If undefined,
113217 ** make it a no-op.
113219 #ifndef testcase
113220 # define testcase(X)
113221 #endif
113224 ** Terminator values for position-lists and column-lists.
113226 #define POS_COLUMN (1) /* Column-list terminator */
113227 #define POS_END (0) /* Position-list terminator */
113230 ** This section provides definitions to allow the
113231 ** FTS3 extension to be compiled outside of the
113232 ** amalgamation.
113234 #ifndef SQLITE_AMALGAMATION
113236 ** Macros indicating that conditional expressions are always true or
113237 ** false.
113239 #ifdef SQLITE_COVERAGE_TEST
113240 # define ALWAYS(x) (1)
113241 # define NEVER(X) (0)
113242 #else
113243 # define ALWAYS(x) (x)
113244 # define NEVER(X) (x)
113245 #endif
113248 ** Internal types used by SQLite.
113250 typedef unsigned char u8; /* 1-byte (or larger) unsigned integer */
113251 typedef short int i16; /* 2-byte (or larger) signed integer */
113252 typedef unsigned int u32; /* 4-byte unsigned integer */
113253 typedef sqlite3_uint64 u64; /* 8-byte unsigned integer */
113255 ** Macro used to suppress compiler warnings for unused parameters.
113257 #define UNUSED_PARAMETER(x) (void)(x)
113258 #endif
113260 typedef struct Fts3Table Fts3Table;
113261 typedef struct Fts3Cursor Fts3Cursor;
113262 typedef struct Fts3Expr Fts3Expr;
113263 typedef struct Fts3Phrase Fts3Phrase;
113264 typedef struct Fts3PhraseToken Fts3PhraseToken;
113266 typedef struct Fts3SegFilter Fts3SegFilter;
113267 typedef struct Fts3DeferredToken Fts3DeferredToken;
113268 typedef struct Fts3SegReader Fts3SegReader;
113269 typedef struct Fts3SegReaderCursor Fts3SegReaderCursor;
113272 ** A connection to a fulltext index is an instance of the following
113273 ** structure. The xCreate and xConnect methods create an instance
113274 ** of this structure and xDestroy and xDisconnect free that instance.
113275 ** All other methods receive a pointer to the structure as one of their
113276 ** arguments.
113278 struct Fts3Table {
113279 sqlite3_vtab base; /* Base class used by SQLite core */
113280 sqlite3 *db; /* The database connection */
113281 const char *zDb; /* logical database name */
113282 const char *zName; /* virtual table name */
113283 int nColumn; /* number of named columns in virtual table */
113284 char **azColumn; /* column names. malloced */
113285 sqlite3_tokenizer *pTokenizer; /* tokenizer for inserts and queries */
113287 /* Precompiled statements used by the implementation. Each of these
113288 ** statements is run and reset within a single virtual table API call.
113290 sqlite3_stmt *aStmt[24];
113292 char *zReadExprlist;
113293 char *zWriteExprlist;
113295 int nNodeSize; /* Soft limit for node size */
113296 u8 bHasStat; /* True if %_stat table exists */
113297 u8 bHasDocsize; /* True if %_docsize table exists */
113298 int nPgsz; /* Page size for host database */
113299 char *zSegmentsTbl; /* Name of %_segments table */
113300 sqlite3_blob *pSegments; /* Blob handle open on %_segments table */
113302 /* The following hash table is used to buffer pending index updates during
113303 ** transactions. Variable nPendingData estimates the memory size of the
113304 ** pending data, including hash table overhead, but not malloc overhead.
113305 ** When nPendingData exceeds nMaxPendingData, the buffer is flushed
113306 ** automatically. Variable iPrevDocid is the docid of the most recently
113307 ** inserted record.
113309 int nMaxPendingData;
113310 int nPendingData;
113311 sqlite_int64 iPrevDocid;
113312 Fts3Hash pendingTerms;
113316 ** When the core wants to read from the virtual table, it creates a
113317 ** virtual table cursor (an instance of the following structure) using
113318 ** the xOpen method. Cursors are destroyed using the xClose method.
113320 struct Fts3Cursor {
113321 sqlite3_vtab_cursor base; /* Base class used by SQLite core */
113322 i16 eSearch; /* Search strategy (see below) */
113323 u8 isEof; /* True if at End Of Results */
113324 u8 isRequireSeek; /* True if must seek pStmt to %_content row */
113325 sqlite3_stmt *pStmt; /* Prepared statement in use by the cursor */
113326 Fts3Expr *pExpr; /* Parsed MATCH query string */
113327 int nPhrase; /* Number of matchable phrases in query */
113328 Fts3DeferredToken *pDeferred; /* Deferred search tokens, if any */
113329 sqlite3_int64 iPrevId; /* Previous id read from aDoclist */
113330 char *pNextId; /* Pointer into the body of aDoclist */
113331 char *aDoclist; /* List of docids for full-text queries */
113332 int nDoclist; /* Size of buffer at aDoclist */
113333 int eEvalmode; /* An FTS3_EVAL_XX constant */
113334 int nRowAvg; /* Average size of database rows, in pages */
113336 int isMatchinfoNeeded; /* True when aMatchinfo[] needs filling in */
113337 u32 *aMatchinfo; /* Information about most recent match */
113338 int nMatchinfo; /* Number of elements in aMatchinfo[] */
113339 char *zMatchinfo; /* Matchinfo specification */
113342 #define FTS3_EVAL_FILTER 0
113343 #define FTS3_EVAL_NEXT 1
113344 #define FTS3_EVAL_MATCHINFO 2
113347 ** The Fts3Cursor.eSearch member is always set to one of the following.
113348 ** Actualy, Fts3Cursor.eSearch can be greater than or equal to
113349 ** FTS3_FULLTEXT_SEARCH. If so, then Fts3Cursor.eSearch - 2 is the index
113350 ** of the column to be searched. For example, in
113352 ** CREATE VIRTUAL TABLE ex1 USING fts3(a,b,c,d);
113353 ** SELECT docid FROM ex1 WHERE b MATCH 'one two three';
113355 ** Because the LHS of the MATCH operator is 2nd column "b",
113356 ** Fts3Cursor.eSearch will be set to FTS3_FULLTEXT_SEARCH+1. (+0 for a,
113357 ** +1 for b, +2 for c, +3 for d.) If the LHS of MATCH were "ex1"
113358 ** indicating that all columns should be searched,
113359 ** then eSearch would be set to FTS3_FULLTEXT_SEARCH+4.
113361 #define FTS3_FULLSCAN_SEARCH 0 /* Linear scan of %_content table */
113362 #define FTS3_DOCID_SEARCH 1 /* Lookup by rowid on %_content table */
113363 #define FTS3_FULLTEXT_SEARCH 2 /* Full-text index search */
113366 ** A "phrase" is a sequence of one or more tokens that must match in
113367 ** sequence. A single token is the base case and the most common case.
113368 ** For a sequence of tokens contained in double-quotes (i.e. "one two three")
113369 ** nToken will be the number of tokens in the string.
113371 ** The nDocMatch and nMatch variables contain data that may be used by the
113372 ** matchinfo() function. They are populated when the full-text index is
113373 ** queried for hits on the phrase. If one or more tokens in the phrase
113374 ** are deferred, the nDocMatch and nMatch variables are populated based
113375 ** on the assumption that the
113377 struct Fts3PhraseToken {
113378 char *z; /* Text of the token */
113379 int n; /* Number of bytes in buffer z */
113380 int isPrefix; /* True if token ends with a "*" character */
113381 int bFulltext; /* True if full-text index was used */
113382 Fts3SegReaderCursor *pSegcsr; /* Segment-reader for this token */
113383 Fts3DeferredToken *pDeferred; /* Deferred token object for this token */
113386 struct Fts3Phrase {
113387 /* Variables populated by fts3_expr.c when parsing a MATCH expression */
113388 int nToken; /* Number of tokens in the phrase */
113389 int iColumn; /* Index of column this phrase must match */
113390 int isNot; /* Phrase prefixed by unary not (-) operator */
113391 Fts3PhraseToken aToken[1]; /* One entry for each token in the phrase */
113395 ** A tree of these objects forms the RHS of a MATCH operator.
113397 ** If Fts3Expr.eType is either FTSQUERY_NEAR or FTSQUERY_PHRASE and isLoaded
113398 ** is true, then aDoclist points to a malloced buffer, size nDoclist bytes,
113399 ** containing the results of the NEAR or phrase query in FTS3 doclist
113400 ** format. As usual, the initial "Length" field found in doclists stored
113401 ** on disk is omitted from this buffer.
113403 ** Variable pCurrent always points to the start of a docid field within
113404 ** aDoclist. Since the doclist is usually scanned in docid order, this can
113405 ** be used to accelerate seeking to the required docid within the doclist.
113407 struct Fts3Expr {
113408 int eType; /* One of the FTSQUERY_XXX values defined below */
113409 int nNear; /* Valid if eType==FTSQUERY_NEAR */
113410 Fts3Expr *pParent; /* pParent->pLeft==this or pParent->pRight==this */
113411 Fts3Expr *pLeft; /* Left operand */
113412 Fts3Expr *pRight; /* Right operand */
113413 Fts3Phrase *pPhrase; /* Valid if eType==FTSQUERY_PHRASE */
113415 int isLoaded; /* True if aDoclist/nDoclist are initialized. */
113416 char *aDoclist; /* Buffer containing doclist */
113417 int nDoclist; /* Size of aDoclist in bytes */
113419 sqlite3_int64 iCurrent;
113420 char *pCurrent;
113424 ** Candidate values for Fts3Query.eType. Note that the order of the first
113425 ** four values is in order of precedence when parsing expressions. For
113426 ** example, the following:
113428 ** "a OR b AND c NOT d NEAR e"
113430 ** is equivalent to:
113432 ** "a OR (b AND (c NOT (d NEAR e)))"
113434 #define FTSQUERY_NEAR 1
113435 #define FTSQUERY_NOT 2
113436 #define FTSQUERY_AND 3
113437 #define FTSQUERY_OR 4
113438 #define FTSQUERY_PHRASE 5
113441 /* fts3_write.c */
113442 SQLITE_PRIVATE int sqlite3Fts3UpdateMethod(sqlite3_vtab*,int,sqlite3_value**,sqlite3_int64*);
113443 SQLITE_PRIVATE int sqlite3Fts3PendingTermsFlush(Fts3Table *);
113444 SQLITE_PRIVATE void sqlite3Fts3PendingTermsClear(Fts3Table *);
113445 SQLITE_PRIVATE int sqlite3Fts3Optimize(Fts3Table *);
113446 SQLITE_PRIVATE int sqlite3Fts3SegReaderNew(int, sqlite3_int64,
113447 sqlite3_int64, sqlite3_int64, const char *, int, Fts3SegReader**);
113448 SQLITE_PRIVATE int sqlite3Fts3SegReaderPending(Fts3Table*,const char*,int,int,Fts3SegReader**);
113449 SQLITE_PRIVATE void sqlite3Fts3SegReaderFree(Fts3SegReader *);
113450 SQLITE_PRIVATE int sqlite3Fts3SegReaderCost(Fts3Cursor *, Fts3SegReader *, int *);
113451 SQLITE_PRIVATE int sqlite3Fts3AllSegdirs(Fts3Table*, int, sqlite3_stmt **);
113452 SQLITE_PRIVATE int sqlite3Fts3ReadLock(Fts3Table *);
113453 SQLITE_PRIVATE int sqlite3Fts3ReadBlock(Fts3Table*, sqlite3_int64, char **, int*);
113455 SQLITE_PRIVATE int sqlite3Fts3SelectDoctotal(Fts3Table *, sqlite3_stmt **);
113456 SQLITE_PRIVATE int sqlite3Fts3SelectDocsize(Fts3Table *, sqlite3_int64, sqlite3_stmt **);
113458 SQLITE_PRIVATE void sqlite3Fts3FreeDeferredTokens(Fts3Cursor *);
113459 SQLITE_PRIVATE int sqlite3Fts3DeferToken(Fts3Cursor *, Fts3PhraseToken *, int);
113460 SQLITE_PRIVATE int sqlite3Fts3CacheDeferredDoclists(Fts3Cursor *);
113461 SQLITE_PRIVATE void sqlite3Fts3FreeDeferredDoclists(Fts3Cursor *);
113462 SQLITE_PRIVATE char *sqlite3Fts3DeferredDoclist(Fts3DeferredToken *, int *);
113463 SQLITE_PRIVATE void sqlite3Fts3SegmentsClose(Fts3Table *);
113465 #define FTS3_SEGCURSOR_PENDING -1
113466 #define FTS3_SEGCURSOR_ALL -2
113468 SQLITE_PRIVATE int sqlite3Fts3SegReaderStart(Fts3Table*, Fts3SegReaderCursor*, Fts3SegFilter*);
113469 SQLITE_PRIVATE int sqlite3Fts3SegReaderStep(Fts3Table *, Fts3SegReaderCursor *);
113470 SQLITE_PRIVATE void sqlite3Fts3SegReaderFinish(Fts3SegReaderCursor *);
113471 SQLITE_PRIVATE int sqlite3Fts3SegReaderCursor(
113472 Fts3Table *, int, const char *, int, int, int, Fts3SegReaderCursor *);
113474 /* Flags allowed as part of the 4th argument to SegmentReaderIterate() */
113475 #define FTS3_SEGMENT_REQUIRE_POS 0x00000001
113476 #define FTS3_SEGMENT_IGNORE_EMPTY 0x00000002
113477 #define FTS3_SEGMENT_COLUMN_FILTER 0x00000004
113478 #define FTS3_SEGMENT_PREFIX 0x00000008
113479 #define FTS3_SEGMENT_SCAN 0x00000010
113481 /* Type passed as 4th argument to SegmentReaderIterate() */
113482 struct Fts3SegFilter {
113483 const char *zTerm;
113484 int nTerm;
113485 int iCol;
113486 int flags;
113489 struct Fts3SegReaderCursor {
113490 /* Used internally by sqlite3Fts3SegReaderXXX() calls */
113491 Fts3SegReader **apSegment; /* Array of Fts3SegReader objects */
113492 int nSegment; /* Size of apSegment array */
113493 int nAdvance; /* How many seg-readers to advance */
113494 Fts3SegFilter *pFilter; /* Pointer to filter object */
113495 char *aBuffer; /* Buffer to merge doclists in */
113496 int nBuffer; /* Allocated size of aBuffer[] in bytes */
113498 /* Cost of running this iterator. Used by fts3.c only. */
113499 int nCost;
113501 /* Output values. Valid only after Fts3SegReaderStep() returns SQLITE_ROW. */
113502 char *zTerm; /* Pointer to term buffer */
113503 int nTerm; /* Size of zTerm in bytes */
113504 char *aDoclist; /* Pointer to doclist buffer */
113505 int nDoclist; /* Size of aDoclist[] in bytes */
113508 /* fts3.c */
113509 SQLITE_PRIVATE int sqlite3Fts3PutVarint(char *, sqlite3_int64);
113510 SQLITE_PRIVATE int sqlite3Fts3GetVarint(const char *, sqlite_int64 *);
113511 SQLITE_PRIVATE int sqlite3Fts3GetVarint32(const char *, int *);
113512 SQLITE_PRIVATE int sqlite3Fts3VarintLen(sqlite3_uint64);
113513 SQLITE_PRIVATE void sqlite3Fts3Dequote(char *);
113515 SQLITE_PRIVATE char *sqlite3Fts3FindPositions(Fts3Expr *, sqlite3_int64, int);
113516 SQLITE_PRIVATE int sqlite3Fts3ExprLoadDoclist(Fts3Cursor *, Fts3Expr *);
113517 SQLITE_PRIVATE int sqlite3Fts3ExprLoadFtDoclist(Fts3Cursor *, Fts3Expr *, char **, int *);
113518 SQLITE_PRIVATE int sqlite3Fts3ExprNearTrim(Fts3Expr *, Fts3Expr *, int);
113520 /* fts3_tokenizer.c */
113521 SQLITE_PRIVATE const char *sqlite3Fts3NextToken(const char *, int *);
113522 SQLITE_PRIVATE int sqlite3Fts3InitHashTable(sqlite3 *, Fts3Hash *, const char *);
113523 SQLITE_PRIVATE int sqlite3Fts3InitTokenizer(Fts3Hash *pHash, const char *,
113524 sqlite3_tokenizer **, char **
113526 SQLITE_PRIVATE int sqlite3Fts3IsIdChar(char);
113528 /* fts3_snippet.c */
113529 SQLITE_PRIVATE void sqlite3Fts3Offsets(sqlite3_context*, Fts3Cursor*);
113530 SQLITE_PRIVATE void sqlite3Fts3Snippet(sqlite3_context *, Fts3Cursor *, const char *,
113531 const char *, const char *, int, int
113533 SQLITE_PRIVATE void sqlite3Fts3Matchinfo(sqlite3_context *, Fts3Cursor *, const char *);
113535 /* fts3_expr.c */
113536 SQLITE_PRIVATE int sqlite3Fts3ExprParse(sqlite3_tokenizer *,
113537 char **, int, int, const char *, int, Fts3Expr **
113539 SQLITE_PRIVATE void sqlite3Fts3ExprFree(Fts3Expr *);
113540 #ifdef SQLITE_TEST
113541 SQLITE_PRIVATE int sqlite3Fts3ExprInitTestInterface(sqlite3 *db);
113542 #endif
113544 /* fts3_aux.c */
113545 SQLITE_PRIVATE int sqlite3Fts3InitAux(sqlite3 *db);
113547 #endif /* _FTSINT_H */
113549 /************** End of fts3Int.h *********************************************/
113550 /************** Continuing where we left off in fts3.c ***********************/
113553 #ifndef SQLITE_CORE
113554 SQLITE_EXTENSION_INIT1
113555 #endif
113558 ** Write a 64-bit variable-length integer to memory starting at p[0].
113559 ** The length of data written will be between 1 and FTS3_VARINT_MAX bytes.
113560 ** The number of bytes written is returned.
113562 SQLITE_PRIVATE int sqlite3Fts3PutVarint(char *p, sqlite_int64 v){
113563 unsigned char *q = (unsigned char *) p;
113564 sqlite_uint64 vu = v;
113566 *q++ = (unsigned char) ((vu & 0x7f) | 0x80);
113567 vu >>= 7;
113568 }while( vu!=0 );
113569 q[-1] &= 0x7f; /* turn off high bit in final byte */
113570 assert( q - (unsigned char *)p <= FTS3_VARINT_MAX );
113571 return (int) (q - (unsigned char *)p);
113575 ** Read a 64-bit variable-length integer from memory starting at p[0].
113576 ** Return the number of bytes read, or 0 on error.
113577 ** The value is stored in *v.
113579 SQLITE_PRIVATE int sqlite3Fts3GetVarint(const char *p, sqlite_int64 *v){
113580 const unsigned char *q = (const unsigned char *) p;
113581 sqlite_uint64 x = 0, y = 1;
113582 while( (*q&0x80)==0x80 && q-(unsigned char *)p<FTS3_VARINT_MAX ){
113583 x += y * (*q++ & 0x7f);
113584 y <<= 7;
113586 x += y * (*q++);
113587 *v = (sqlite_int64) x;
113588 return (int) (q - (unsigned char *)p);
113592 ** Similar to sqlite3Fts3GetVarint(), except that the output is truncated to a
113593 ** 32-bit integer before it is returned.
113595 SQLITE_PRIVATE int sqlite3Fts3GetVarint32(const char *p, int *pi){
113596 sqlite_int64 i;
113597 int ret = sqlite3Fts3GetVarint(p, &i);
113598 *pi = (int) i;
113599 return ret;
113603 ** Return the number of bytes required to encode v as a varint
113605 SQLITE_PRIVATE int sqlite3Fts3VarintLen(sqlite3_uint64 v){
113606 int i = 0;
113609 v >>= 7;
113610 }while( v!=0 );
113611 return i;
113615 ** Convert an SQL-style quoted string into a normal string by removing
113616 ** the quote characters. The conversion is done in-place. If the
113617 ** input does not begin with a quote character, then this routine
113618 ** is a no-op.
113620 ** Examples:
113622 ** "abc" becomes abc
113623 ** 'xyz' becomes xyz
113624 ** [pqr] becomes pqr
113625 ** `mno` becomes mno
113628 SQLITE_PRIVATE void sqlite3Fts3Dequote(char *z){
113629 char quote; /* Quote character (if any ) */
113631 quote = z[0];
113632 if( quote=='[' || quote=='\'' || quote=='"' || quote=='`' ){
113633 int iIn = 1; /* Index of next byte to read from input */
113634 int iOut = 0; /* Index of next byte to write to output */
113636 /* If the first byte was a '[', then the close-quote character is a ']' */
113637 if( quote=='[' ) quote = ']';
113639 while( ALWAYS(z[iIn]) ){
113640 if( z[iIn]==quote ){
113641 if( z[iIn+1]!=quote ) break;
113642 z[iOut++] = quote;
113643 iIn += 2;
113644 }else{
113645 z[iOut++] = z[iIn++];
113648 z[iOut] = '\0';
113653 ** Read a single varint from the doclist at *pp and advance *pp to point
113654 ** to the first byte past the end of the varint. Add the value of the varint
113655 ** to *pVal.
113657 static void fts3GetDeltaVarint(char **pp, sqlite3_int64 *pVal){
113658 sqlite3_int64 iVal;
113659 *pp += sqlite3Fts3GetVarint(*pp, &iVal);
113660 *pVal += iVal;
113664 ** As long as *pp has not reached its end (pEnd), then do the same
113665 ** as fts3GetDeltaVarint(): read a single varint and add it to *pVal.
113666 ** But if we have reached the end of the varint, just set *pp=0 and
113667 ** leave *pVal unchanged.
113669 static void fts3GetDeltaVarint2(char **pp, char *pEnd, sqlite3_int64 *pVal){
113670 if( *pp>=pEnd ){
113671 *pp = 0;
113672 }else{
113673 fts3GetDeltaVarint(pp, pVal);
113678 ** The xDisconnect() virtual table method.
113680 static int fts3DisconnectMethod(sqlite3_vtab *pVtab){
113681 Fts3Table *p = (Fts3Table *)pVtab;
113682 int i;
113684 assert( p->nPendingData==0 );
113685 assert( p->pSegments==0 );
113687 /* Free any prepared statements held */
113688 for(i=0; i<SizeofArray(p->aStmt); i++){
113689 sqlite3_finalize(p->aStmt[i]);
113691 sqlite3_free(p->zSegmentsTbl);
113692 sqlite3_free(p->zReadExprlist);
113693 sqlite3_free(p->zWriteExprlist);
113695 /* Invoke the tokenizer destructor to free the tokenizer. */
113696 p->pTokenizer->pModule->xDestroy(p->pTokenizer);
113698 sqlite3_free(p);
113699 return SQLITE_OK;
113703 ** Construct one or more SQL statements from the format string given
113704 ** and then evaluate those statements. The success code is written
113705 ** into *pRc.
113707 ** If *pRc is initially non-zero then this routine is a no-op.
113709 static void fts3DbExec(
113710 int *pRc, /* Success code */
113711 sqlite3 *db, /* Database in which to run SQL */
113712 const char *zFormat, /* Format string for SQL */
113713 ... /* Arguments to the format string */
113715 va_list ap;
113716 char *zSql;
113717 if( *pRc ) return;
113718 va_start(ap, zFormat);
113719 zSql = sqlite3_vmprintf(zFormat, ap);
113720 va_end(ap);
113721 if( zSql==0 ){
113722 *pRc = SQLITE_NOMEM;
113723 }else{
113724 *pRc = sqlite3_exec(db, zSql, 0, 0, 0);
113725 sqlite3_free(zSql);
113730 ** The xDestroy() virtual table method.
113732 static int fts3DestroyMethod(sqlite3_vtab *pVtab){
113733 int rc = SQLITE_OK; /* Return code */
113734 Fts3Table *p = (Fts3Table *)pVtab;
113735 sqlite3 *db = p->db;
113737 /* Drop the shadow tables */
113738 fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_content'", p->zDb, p->zName);
113739 fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_segments'", p->zDb,p->zName);
113740 fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_segdir'", p->zDb, p->zName);
113741 fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_docsize'", p->zDb, p->zName);
113742 fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_stat'", p->zDb, p->zName);
113744 /* If everything has worked, invoke fts3DisconnectMethod() to free the
113745 ** memory associated with the Fts3Table structure and return SQLITE_OK.
113746 ** Otherwise, return an SQLite error code.
113748 return (rc==SQLITE_OK ? fts3DisconnectMethod(pVtab) : rc);
113753 ** Invoke sqlite3_declare_vtab() to declare the schema for the FTS3 table
113754 ** passed as the first argument. This is done as part of the xConnect()
113755 ** and xCreate() methods.
113757 ** If *pRc is non-zero when this function is called, it is a no-op.
113758 ** Otherwise, if an error occurs, an SQLite error code is stored in *pRc
113759 ** before returning.
113761 static void fts3DeclareVtab(int *pRc, Fts3Table *p){
113762 if( *pRc==SQLITE_OK ){
113763 int i; /* Iterator variable */
113764 int rc; /* Return code */
113765 char *zSql; /* SQL statement passed to declare_vtab() */
113766 char *zCols; /* List of user defined columns */
113768 /* Create a list of user columns for the virtual table */
113769 zCols = sqlite3_mprintf("%Q, ", p->azColumn[0]);
113770 for(i=1; zCols && i<p->nColumn; i++){
113771 zCols = sqlite3_mprintf("%z%Q, ", zCols, p->azColumn[i]);
113774 /* Create the whole "CREATE TABLE" statement to pass to SQLite */
113775 zSql = sqlite3_mprintf(
113776 "CREATE TABLE x(%s %Q HIDDEN, docid HIDDEN)", zCols, p->zName
113778 if( !zCols || !zSql ){
113779 rc = SQLITE_NOMEM;
113780 }else{
113781 rc = sqlite3_declare_vtab(p->db, zSql);
113784 sqlite3_free(zSql);
113785 sqlite3_free(zCols);
113786 *pRc = rc;
113791 ** Create the backing store tables (%_content, %_segments and %_segdir)
113792 ** required by the FTS3 table passed as the only argument. This is done
113793 ** as part of the vtab xCreate() method.
113795 ** If the p->bHasDocsize boolean is true (indicating that this is an
113796 ** FTS4 table, not an FTS3 table) then also create the %_docsize and
113797 ** %_stat tables required by FTS4.
113799 static int fts3CreateTables(Fts3Table *p){
113800 int rc = SQLITE_OK; /* Return code */
113801 int i; /* Iterator variable */
113802 char *zContentCols; /* Columns of %_content table */
113803 sqlite3 *db = p->db; /* The database connection */
113805 /* Create a list of user columns for the content table */
113806 zContentCols = sqlite3_mprintf("docid INTEGER PRIMARY KEY");
113807 for(i=0; zContentCols && i<p->nColumn; i++){
113808 char *z = p->azColumn[i];
113809 zContentCols = sqlite3_mprintf("%z, 'c%d%q'", zContentCols, i, z);
113811 if( zContentCols==0 ) rc = SQLITE_NOMEM;
113813 /* Create the content table */
113814 fts3DbExec(&rc, db,
113815 "CREATE TABLE %Q.'%q_content'(%s)",
113816 p->zDb, p->zName, zContentCols
113818 sqlite3_free(zContentCols);
113819 /* Create other tables */
113820 fts3DbExec(&rc, db,
113821 "CREATE TABLE %Q.'%q_segments'(blockid INTEGER PRIMARY KEY, block BLOB);",
113822 p->zDb, p->zName
113824 fts3DbExec(&rc, db,
113825 "CREATE TABLE %Q.'%q_segdir'("
113826 "level INTEGER,"
113827 "idx INTEGER,"
113828 "start_block INTEGER,"
113829 "leaves_end_block INTEGER,"
113830 "end_block INTEGER,"
113831 "root BLOB,"
113832 "PRIMARY KEY(level, idx)"
113833 ");",
113834 p->zDb, p->zName
113836 if( p->bHasDocsize ){
113837 fts3DbExec(&rc, db,
113838 "CREATE TABLE %Q.'%q_docsize'(docid INTEGER PRIMARY KEY, size BLOB);",
113839 p->zDb, p->zName
113842 if( p->bHasStat ){
113843 fts3DbExec(&rc, db,
113844 "CREATE TABLE %Q.'%q_stat'(id INTEGER PRIMARY KEY, value BLOB);",
113845 p->zDb, p->zName
113848 return rc;
113852 ** Store the current database page-size in bytes in p->nPgsz.
113854 ** If *pRc is non-zero when this function is called, it is a no-op.
113855 ** Otherwise, if an error occurs, an SQLite error code is stored in *pRc
113856 ** before returning.
113858 static void fts3DatabasePageSize(int *pRc, Fts3Table *p){
113859 if( *pRc==SQLITE_OK ){
113860 int rc; /* Return code */
113861 char *zSql; /* SQL text "PRAGMA %Q.page_size" */
113862 sqlite3_stmt *pStmt; /* Compiled "PRAGMA %Q.page_size" statement */
113864 zSql = sqlite3_mprintf("PRAGMA %Q.page_size", p->zDb);
113865 if( !zSql ){
113866 rc = SQLITE_NOMEM;
113867 }else{
113868 rc = sqlite3_prepare(p->db, zSql, -1, &pStmt, 0);
113869 if( rc==SQLITE_OK ){
113870 sqlite3_step(pStmt);
113871 p->nPgsz = sqlite3_column_int(pStmt, 0);
113872 rc = sqlite3_finalize(pStmt);
113873 }else if( rc==SQLITE_AUTH ){
113874 p->nPgsz = 1024;
113875 rc = SQLITE_OK;
113878 assert( p->nPgsz>0 || rc!=SQLITE_OK );
113879 sqlite3_free(zSql);
113880 *pRc = rc;
113885 ** "Special" FTS4 arguments are column specifications of the following form:
113887 ** <key> = <value>
113889 ** There may not be whitespace surrounding the "=" character. The <value>
113890 ** term may be quoted, but the <key> may not.
113892 static int fts3IsSpecialColumn(
113893 const char *z,
113894 int *pnKey,
113895 char **pzValue
113897 char *zValue;
113898 const char *zCsr = z;
113900 while( *zCsr!='=' ){
113901 if( *zCsr=='\0' ) return 0;
113902 zCsr++;
113905 *pnKey = (int)(zCsr-z);
113906 zValue = sqlite3_mprintf("%s", &zCsr[1]);
113907 if( zValue ){
113908 sqlite3Fts3Dequote(zValue);
113910 *pzValue = zValue;
113911 return 1;
113915 ** Append the output of a printf() style formatting to an existing string.
113917 static void fts3Appendf(
113918 int *pRc, /* IN/OUT: Error code */
113919 char **pz, /* IN/OUT: Pointer to string buffer */
113920 const char *zFormat, /* Printf format string to append */
113921 ... /* Arguments for printf format string */
113923 if( *pRc==SQLITE_OK ){
113924 va_list ap;
113925 char *z;
113926 va_start(ap, zFormat);
113927 z = sqlite3_vmprintf(zFormat, ap);
113928 if( z && *pz ){
113929 char *z2 = sqlite3_mprintf("%s%s", *pz, z);
113930 sqlite3_free(z);
113931 z = z2;
113933 if( z==0 ) *pRc = SQLITE_NOMEM;
113934 sqlite3_free(*pz);
113935 *pz = z;
113940 ** Return a copy of input string zInput enclosed in double-quotes (") and
113941 ** with all double quote characters escaped. For example:
113943 ** fts3QuoteId("un \"zip\"") -> "un \"\"zip\"\""
113945 ** The pointer returned points to memory obtained from sqlite3_malloc(). It
113946 ** is the callers responsibility to call sqlite3_free() to release this
113947 ** memory.
113949 static char *fts3QuoteId(char const *zInput){
113950 int nRet;
113951 char *zRet;
113952 nRet = 2 + strlen(zInput)*2 + 1;
113953 zRet = sqlite3_malloc(nRet);
113954 if( zRet ){
113955 int i;
113956 char *z = zRet;
113957 *(z++) = '"';
113958 for(i=0; zInput[i]; i++){
113959 if( zInput[i]=='"' ) *(z++) = '"';
113960 *(z++) = zInput[i];
113962 *(z++) = '"';
113963 *(z++) = '\0';
113965 return zRet;
113969 ** Return a list of comma separated SQL expressions that could be used
113970 ** in a SELECT statement such as the following:
113972 ** SELECT <list of expressions> FROM %_content AS x ...
113974 ** to return the docid, followed by each column of text data in order
113975 ** from left to write. If parameter zFunc is not NULL, then instead of
113976 ** being returned directly each column of text data is passed to an SQL
113977 ** function named zFunc first. For example, if zFunc is "unzip" and the
113978 ** table has the three user-defined columns "a", "b", and "c", the following
113979 ** string is returned:
113981 ** "docid, unzip(x.'a'), unzip(x.'b'), unzip(x.'c')"
113983 ** The pointer returned points to a buffer allocated by sqlite3_malloc(). It
113984 ** is the responsibility of the caller to eventually free it.
113986 ** If *pRc is not SQLITE_OK when this function is called, it is a no-op (and
113987 ** a NULL pointer is returned). Otherwise, if an OOM error is encountered
113988 ** by this function, NULL is returned and *pRc is set to SQLITE_NOMEM. If
113989 ** no error occurs, *pRc is left unmodified.
113991 static char *fts3ReadExprList(Fts3Table *p, const char *zFunc, int *pRc){
113992 char *zRet = 0;
113993 char *zFree = 0;
113994 char *zFunction;
113995 int i;
113997 if( !zFunc ){
113998 zFunction = "";
113999 }else{
114000 zFree = zFunction = fts3QuoteId(zFunc);
114002 fts3Appendf(pRc, &zRet, "docid");
114003 for(i=0; i<p->nColumn; i++){
114004 fts3Appendf(pRc, &zRet, ",%s(x.'c%d%q')", zFunction, i, p->azColumn[i]);
114006 sqlite3_free(zFree);
114007 return zRet;
114011 ** Return a list of N comma separated question marks, where N is the number
114012 ** of columns in the %_content table (one for the docid plus one for each
114013 ** user-defined text column).
114015 ** If argument zFunc is not NULL, then all but the first question mark
114016 ** is preceded by zFunc and an open bracket, and followed by a closed
114017 ** bracket. For example, if zFunc is "zip" and the FTS3 table has three
114018 ** user-defined text columns, the following string is returned:
114020 ** "?, zip(?), zip(?), zip(?)"
114022 ** The pointer returned points to a buffer allocated by sqlite3_malloc(). It
114023 ** is the responsibility of the caller to eventually free it.
114025 ** If *pRc is not SQLITE_OK when this function is called, it is a no-op (and
114026 ** a NULL pointer is returned). Otherwise, if an OOM error is encountered
114027 ** by this function, NULL is returned and *pRc is set to SQLITE_NOMEM. If
114028 ** no error occurs, *pRc is left unmodified.
114030 static char *fts3WriteExprList(Fts3Table *p, const char *zFunc, int *pRc){
114031 char *zRet = 0;
114032 char *zFree = 0;
114033 char *zFunction;
114034 int i;
114036 if( !zFunc ){
114037 zFunction = "";
114038 }else{
114039 zFree = zFunction = fts3QuoteId(zFunc);
114041 fts3Appendf(pRc, &zRet, "?");
114042 for(i=0; i<p->nColumn; i++){
114043 fts3Appendf(pRc, &zRet, ",%s(?)", zFunction);
114045 sqlite3_free(zFree);
114046 return zRet;
114050 ** This function is the implementation of both the xConnect and xCreate
114051 ** methods of the FTS3 virtual table.
114053 ** The argv[] array contains the following:
114055 ** argv[0] -> module name ("fts3" or "fts4")
114056 ** argv[1] -> database name
114057 ** argv[2] -> table name
114058 ** argv[...] -> "column name" and other module argument fields.
114060 static int fts3InitVtab(
114061 int isCreate, /* True for xCreate, false for xConnect */
114062 sqlite3 *db, /* The SQLite database connection */
114063 void *pAux, /* Hash table containing tokenizers */
114064 int argc, /* Number of elements in argv array */
114065 const char * const *argv, /* xCreate/xConnect argument array */
114066 sqlite3_vtab **ppVTab, /* Write the resulting vtab structure here */
114067 char **pzErr /* Write any error message here */
114069 Fts3Hash *pHash = (Fts3Hash *)pAux;
114070 Fts3Table *p = 0; /* Pointer to allocated vtab */
114071 int rc = SQLITE_OK; /* Return code */
114072 int i; /* Iterator variable */
114073 int nByte; /* Size of allocation used for *p */
114074 int iCol; /* Column index */
114075 int nString = 0; /* Bytes required to hold all column names */
114076 int nCol = 0; /* Number of columns in the FTS table */
114077 char *zCsr; /* Space for holding column names */
114078 int nDb; /* Bytes required to hold database name */
114079 int nName; /* Bytes required to hold table name */
114080 int isFts4 = (argv[0][3]=='4'); /* True for FTS4, false for FTS3 */
114081 int bNoDocsize = 0; /* True to omit %_docsize table */
114082 const char **aCol; /* Array of column names */
114083 sqlite3_tokenizer *pTokenizer = 0; /* Tokenizer for this table */
114085 char *zCompress = 0;
114086 char *zUncompress = 0;
114088 assert( strlen(argv[0])==4 );
114089 assert( (sqlite3_strnicmp(argv[0], "fts4", 4)==0 && isFts4)
114090 || (sqlite3_strnicmp(argv[0], "fts3", 4)==0 && !isFts4)
114093 nDb = (int)strlen(argv[1]) + 1;
114094 nName = (int)strlen(argv[2]) + 1;
114096 aCol = (const char **)sqlite3_malloc(sizeof(const char *) * (argc-2) );
114097 if( !aCol ) return SQLITE_NOMEM;
114098 memset((void *)aCol, 0, sizeof(const char *) * (argc-2));
114100 /* Loop through all of the arguments passed by the user to the FTS3/4
114101 ** module (i.e. all the column names and special arguments). This loop
114102 ** does the following:
114104 ** + Figures out the number of columns the FTSX table will have, and
114105 ** the number of bytes of space that must be allocated to store copies
114106 ** of the column names.
114108 ** + If there is a tokenizer specification included in the arguments,
114109 ** initializes the tokenizer pTokenizer.
114111 for(i=3; rc==SQLITE_OK && i<argc; i++){
114112 char const *z = argv[i];
114113 int nKey;
114114 char *zVal;
114116 /* Check if this is a tokenizer specification */
114117 if( !pTokenizer
114118 && strlen(z)>8
114119 && 0==sqlite3_strnicmp(z, "tokenize", 8)
114120 && 0==sqlite3Fts3IsIdChar(z[8])
114122 rc = sqlite3Fts3InitTokenizer(pHash, &z[9], &pTokenizer, pzErr);
114125 /* Check if it is an FTS4 special argument. */
114126 else if( isFts4 && fts3IsSpecialColumn(z, &nKey, &zVal) ){
114127 if( !zVal ){
114128 rc = SQLITE_NOMEM;
114129 goto fts3_init_out;
114131 if( nKey==9 && 0==sqlite3_strnicmp(z, "matchinfo", 9) ){
114132 if( strlen(zVal)==4 && 0==sqlite3_strnicmp(zVal, "fts3", 4) ){
114133 bNoDocsize = 1;
114134 }else{
114135 *pzErr = sqlite3_mprintf("unrecognized matchinfo: %s", zVal);
114136 rc = SQLITE_ERROR;
114138 }else if( nKey==8 && 0==sqlite3_strnicmp(z, "compress", 8) ){
114139 zCompress = zVal;
114140 zVal = 0;
114141 }else if( nKey==10 && 0==sqlite3_strnicmp(z, "uncompress", 10) ){
114142 zUncompress = zVal;
114143 zVal = 0;
114144 }else{
114145 *pzErr = sqlite3_mprintf("unrecognized parameter: %s", z);
114146 rc = SQLITE_ERROR;
114148 sqlite3_free(zVal);
114151 /* Otherwise, the argument is a column name. */
114152 else {
114153 nString += (int)(strlen(z) + 1);
114154 aCol[nCol++] = z;
114157 if( rc!=SQLITE_OK ) goto fts3_init_out;
114159 if( nCol==0 ){
114160 assert( nString==0 );
114161 aCol[0] = "content";
114162 nString = 8;
114163 nCol = 1;
114166 if( pTokenizer==0 ){
114167 rc = sqlite3Fts3InitTokenizer(pHash, "simple", &pTokenizer, pzErr);
114168 if( rc!=SQLITE_OK ) goto fts3_init_out;
114170 assert( pTokenizer );
114173 /* Allocate and populate the Fts3Table structure. */
114174 nByte = sizeof(Fts3Table) + /* Fts3Table */
114175 nCol * sizeof(char *) + /* azColumn */
114176 nName + /* zName */
114177 nDb + /* zDb */
114178 nString; /* Space for azColumn strings */
114179 p = (Fts3Table*)sqlite3_malloc(nByte);
114180 if( p==0 ){
114181 rc = SQLITE_NOMEM;
114182 goto fts3_init_out;
114184 memset(p, 0, nByte);
114185 p->db = db;
114186 p->nColumn = nCol;
114187 p->nPendingData = 0;
114188 p->azColumn = (char **)&p[1];
114189 p->pTokenizer = pTokenizer;
114190 p->nNodeSize = 1000;
114191 p->nMaxPendingData = FTS3_MAX_PENDING_DATA;
114192 p->bHasDocsize = (isFts4 && bNoDocsize==0);
114193 p->bHasStat = isFts4;
114194 fts3HashInit(&p->pendingTerms, FTS3_HASH_STRING, 1);
114196 /* Fill in the zName and zDb fields of the vtab structure. */
114197 zCsr = (char *)&p->azColumn[nCol];
114198 p->zName = zCsr;
114199 memcpy(zCsr, argv[2], nName);
114200 zCsr += nName;
114201 p->zDb = zCsr;
114202 memcpy(zCsr, argv[1], nDb);
114203 zCsr += nDb;
114205 /* Fill in the azColumn array */
114206 for(iCol=0; iCol<nCol; iCol++){
114207 char *z;
114208 int n;
114209 z = (char *)sqlite3Fts3NextToken(aCol[iCol], &n);
114210 memcpy(zCsr, z, n);
114211 zCsr[n] = '\0';
114212 sqlite3Fts3Dequote(zCsr);
114213 p->azColumn[iCol] = zCsr;
114214 zCsr += n+1;
114215 assert( zCsr <= &((char *)p)[nByte] );
114218 if( (zCompress==0)!=(zUncompress==0) ){
114219 char const *zMiss = (zCompress==0 ? "compress" : "uncompress");
114220 rc = SQLITE_ERROR;
114221 *pzErr = sqlite3_mprintf("missing %s parameter in fts4 constructor", zMiss);
114223 p->zReadExprlist = fts3ReadExprList(p, zUncompress, &rc);
114224 p->zWriteExprlist = fts3WriteExprList(p, zCompress, &rc);
114225 if( rc!=SQLITE_OK ) goto fts3_init_out;
114227 /* If this is an xCreate call, create the underlying tables in the
114228 ** database. TODO: For xConnect(), it could verify that said tables exist.
114230 if( isCreate ){
114231 rc = fts3CreateTables(p);
114234 /* Figure out the page-size for the database. This is required in order to
114235 ** estimate the cost of loading large doclists from the database (see
114236 ** function sqlite3Fts3SegReaderCost() for details).
114238 fts3DatabasePageSize(&rc, p);
114240 /* Declare the table schema to SQLite. */
114241 fts3DeclareVtab(&rc, p);
114243 fts3_init_out:
114244 sqlite3_free(zCompress);
114245 sqlite3_free(zUncompress);
114246 sqlite3_free((void *)aCol);
114247 if( rc!=SQLITE_OK ){
114248 if( p ){
114249 fts3DisconnectMethod((sqlite3_vtab *)p);
114250 }else if( pTokenizer ){
114251 pTokenizer->pModule->xDestroy(pTokenizer);
114253 }else{
114254 *ppVTab = &p->base;
114256 return rc;
114260 ** The xConnect() and xCreate() methods for the virtual table. All the
114261 ** work is done in function fts3InitVtab().
114263 static int fts3ConnectMethod(
114264 sqlite3 *db, /* Database connection */
114265 void *pAux, /* Pointer to tokenizer hash table */
114266 int argc, /* Number of elements in argv array */
114267 const char * const *argv, /* xCreate/xConnect argument array */
114268 sqlite3_vtab **ppVtab, /* OUT: New sqlite3_vtab object */
114269 char **pzErr /* OUT: sqlite3_malloc'd error message */
114271 return fts3InitVtab(0, db, pAux, argc, argv, ppVtab, pzErr);
114273 static int fts3CreateMethod(
114274 sqlite3 *db, /* Database connection */
114275 void *pAux, /* Pointer to tokenizer hash table */
114276 int argc, /* Number of elements in argv array */
114277 const char * const *argv, /* xCreate/xConnect argument array */
114278 sqlite3_vtab **ppVtab, /* OUT: New sqlite3_vtab object */
114279 char **pzErr /* OUT: sqlite3_malloc'd error message */
114281 return fts3InitVtab(1, db, pAux, argc, argv, ppVtab, pzErr);
114285 ** Implementation of the xBestIndex method for FTS3 tables. There
114286 ** are three possible strategies, in order of preference:
114288 ** 1. Direct lookup by rowid or docid.
114289 ** 2. Full-text search using a MATCH operator on a non-docid column.
114290 ** 3. Linear scan of %_content table.
114292 static int fts3BestIndexMethod(sqlite3_vtab *pVTab, sqlite3_index_info *pInfo){
114293 Fts3Table *p = (Fts3Table *)pVTab;
114294 int i; /* Iterator variable */
114295 int iCons = -1; /* Index of constraint to use */
114297 /* By default use a full table scan. This is an expensive option,
114298 ** so search through the constraints to see if a more efficient
114299 ** strategy is possible.
114301 pInfo->idxNum = FTS3_FULLSCAN_SEARCH;
114302 pInfo->estimatedCost = 500000;
114303 for(i=0; i<pInfo->nConstraint; i++){
114304 struct sqlite3_index_constraint *pCons = &pInfo->aConstraint[i];
114305 if( pCons->usable==0 ) continue;
114307 /* A direct lookup on the rowid or docid column. Assign a cost of 1.0. */
114308 if( pCons->op==SQLITE_INDEX_CONSTRAINT_EQ
114309 && (pCons->iColumn<0 || pCons->iColumn==p->nColumn+1 )
114311 pInfo->idxNum = FTS3_DOCID_SEARCH;
114312 pInfo->estimatedCost = 1.0;
114313 iCons = i;
114316 /* A MATCH constraint. Use a full-text search.
114318 ** If there is more than one MATCH constraint available, use the first
114319 ** one encountered. If there is both a MATCH constraint and a direct
114320 ** rowid/docid lookup, prefer the MATCH strategy. This is done even
114321 ** though the rowid/docid lookup is faster than a MATCH query, selecting
114322 ** it would lead to an "unable to use function MATCH in the requested
114323 ** context" error.
114325 if( pCons->op==SQLITE_INDEX_CONSTRAINT_MATCH
114326 && pCons->iColumn>=0 && pCons->iColumn<=p->nColumn
114328 pInfo->idxNum = FTS3_FULLTEXT_SEARCH + pCons->iColumn;
114329 pInfo->estimatedCost = 2.0;
114330 iCons = i;
114331 break;
114335 if( iCons>=0 ){
114336 pInfo->aConstraintUsage[iCons].argvIndex = 1;
114337 pInfo->aConstraintUsage[iCons].omit = 1;
114339 return SQLITE_OK;
114343 ** Implementation of xOpen method.
114345 static int fts3OpenMethod(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCsr){
114346 sqlite3_vtab_cursor *pCsr; /* Allocated cursor */
114348 UNUSED_PARAMETER(pVTab);
114350 /* Allocate a buffer large enough for an Fts3Cursor structure. If the
114351 ** allocation succeeds, zero it and return SQLITE_OK. Otherwise,
114352 ** if the allocation fails, return SQLITE_NOMEM.
114354 *ppCsr = pCsr = (sqlite3_vtab_cursor *)sqlite3_malloc(sizeof(Fts3Cursor));
114355 if( !pCsr ){
114356 return SQLITE_NOMEM;
114358 memset(pCsr, 0, sizeof(Fts3Cursor));
114359 return SQLITE_OK;
114363 ** Close the cursor. For additional information see the documentation
114364 ** on the xClose method of the virtual table interface.
114366 static int fts3CloseMethod(sqlite3_vtab_cursor *pCursor){
114367 Fts3Cursor *pCsr = (Fts3Cursor *)pCursor;
114368 assert( ((Fts3Table *)pCsr->base.pVtab)->pSegments==0 );
114369 sqlite3_finalize(pCsr->pStmt);
114370 sqlite3Fts3ExprFree(pCsr->pExpr);
114371 sqlite3Fts3FreeDeferredTokens(pCsr);
114372 sqlite3_free(pCsr->aDoclist);
114373 sqlite3_free(pCsr->aMatchinfo);
114374 sqlite3_free(pCsr);
114375 return SQLITE_OK;
114379 ** Position the pCsr->pStmt statement so that it is on the row
114380 ** of the %_content table that contains the last match. Return
114381 ** SQLITE_OK on success.
114383 static int fts3CursorSeek(sqlite3_context *pContext, Fts3Cursor *pCsr){
114384 if( pCsr->isRequireSeek ){
114385 pCsr->isRequireSeek = 0;
114386 sqlite3_bind_int64(pCsr->pStmt, 1, pCsr->iPrevId);
114387 if( SQLITE_ROW==sqlite3_step(pCsr->pStmt) ){
114388 return SQLITE_OK;
114389 }else{
114390 int rc = sqlite3_reset(pCsr->pStmt);
114391 if( rc==SQLITE_OK ){
114392 /* If no row was found and no error has occured, then the %_content
114393 ** table is missing a row that is present in the full-text index.
114394 ** The data structures are corrupt.
114396 rc = SQLITE_CORRUPT;
114398 pCsr->isEof = 1;
114399 if( pContext ){
114400 sqlite3_result_error_code(pContext, rc);
114402 return rc;
114404 }else{
114405 return SQLITE_OK;
114410 ** This function is used to process a single interior node when searching
114411 ** a b-tree for a term or term prefix. The node data is passed to this
114412 ** function via the zNode/nNode parameters. The term to search for is
114413 ** passed in zTerm/nTerm.
114415 ** If piFirst is not NULL, then this function sets *piFirst to the blockid
114416 ** of the child node that heads the sub-tree that may contain the term.
114418 ** If piLast is not NULL, then *piLast is set to the right-most child node
114419 ** that heads a sub-tree that may contain a term for which zTerm/nTerm is
114420 ** a prefix.
114422 ** If an OOM error occurs, SQLITE_NOMEM is returned. Otherwise, SQLITE_OK.
114424 static int fts3ScanInteriorNode(
114425 const char *zTerm, /* Term to select leaves for */
114426 int nTerm, /* Size of term zTerm in bytes */
114427 const char *zNode, /* Buffer containing segment interior node */
114428 int nNode, /* Size of buffer at zNode */
114429 sqlite3_int64 *piFirst, /* OUT: Selected child node */
114430 sqlite3_int64 *piLast /* OUT: Selected child node */
114432 int rc = SQLITE_OK; /* Return code */
114433 const char *zCsr = zNode; /* Cursor to iterate through node */
114434 const char *zEnd = &zCsr[nNode];/* End of interior node buffer */
114435 char *zBuffer = 0; /* Buffer to load terms into */
114436 int nAlloc = 0; /* Size of allocated buffer */
114437 int isFirstTerm = 1; /* True when processing first term on page */
114438 sqlite3_int64 iChild; /* Block id of child node to descend to */
114440 /* Skip over the 'height' varint that occurs at the start of every
114441 ** interior node. Then load the blockid of the left-child of the b-tree
114442 ** node into variable iChild.
114444 ** Even if the data structure on disk is corrupted, this (reading two
114445 ** varints from the buffer) does not risk an overread. If zNode is a
114446 ** root node, then the buffer comes from a SELECT statement. SQLite does
114447 ** not make this guarantee explicitly, but in practice there are always
114448 ** either more than 20 bytes of allocated space following the nNode bytes of
114449 ** contents, or two zero bytes. Or, if the node is read from the %_segments
114450 ** table, then there are always 20 bytes of zeroed padding following the
114451 ** nNode bytes of content (see sqlite3Fts3ReadBlock() for details).
114453 zCsr += sqlite3Fts3GetVarint(zCsr, &iChild);
114454 zCsr += sqlite3Fts3GetVarint(zCsr, &iChild);
114455 if( zCsr>zEnd ){
114456 return SQLITE_CORRUPT;
114459 while( zCsr<zEnd && (piFirst || piLast) ){
114460 int cmp; /* memcmp() result */
114461 int nSuffix; /* Size of term suffix */
114462 int nPrefix = 0; /* Size of term prefix */
114463 int nBuffer; /* Total term size */
114465 /* Load the next term on the node into zBuffer. Use realloc() to expand
114466 ** the size of zBuffer if required. */
114467 if( !isFirstTerm ){
114468 zCsr += sqlite3Fts3GetVarint32(zCsr, &nPrefix);
114470 isFirstTerm = 0;
114471 zCsr += sqlite3Fts3GetVarint32(zCsr, &nSuffix);
114473 /* NOTE(shess): Previous code checked for negative nPrefix and
114474 ** nSuffix and suffix overrunning zEnd. Additionally corrupt if
114475 ** the prefix is longer than the previous term, or if the suffix
114476 ** causes overflow.
114478 if( nPrefix<0 || nSuffix<0 /* || nPrefix>nBuffer */
114479 || &zCsr[nSuffix]<zCsr || &zCsr[nSuffix]>zEnd ){
114480 rc = SQLITE_CORRUPT;
114481 goto finish_scan;
114483 if( nPrefix+nSuffix>nAlloc ){
114484 char *zNew;
114485 nAlloc = (nPrefix+nSuffix) * 2;
114486 zNew = (char *)sqlite3_realloc(zBuffer, nAlloc);
114487 if( !zNew ){
114488 rc = SQLITE_NOMEM;
114489 goto finish_scan;
114491 zBuffer = zNew;
114493 memcpy(&zBuffer[nPrefix], zCsr, nSuffix);
114494 nBuffer = nPrefix + nSuffix;
114495 zCsr += nSuffix;
114497 /* Compare the term we are searching for with the term just loaded from
114498 ** the interior node. If the specified term is greater than or equal
114499 ** to the term from the interior node, then all terms on the sub-tree
114500 ** headed by node iChild are smaller than zTerm. No need to search
114501 ** iChild.
114503 ** If the interior node term is larger than the specified term, then
114504 ** the tree headed by iChild may contain the specified term.
114506 cmp = memcmp(zTerm, zBuffer, (nBuffer>nTerm ? nTerm : nBuffer));
114507 if( piFirst && (cmp<0 || (cmp==0 && nBuffer>nTerm)) ){
114508 *piFirst = iChild;
114509 piFirst = 0;
114512 if( piLast && cmp<0 ){
114513 *piLast = iChild;
114514 piLast = 0;
114517 iChild++;
114520 if( piFirst ) *piFirst = iChild;
114521 if( piLast ) *piLast = iChild;
114523 finish_scan:
114524 sqlite3_free(zBuffer);
114525 return rc;
114530 ** The buffer pointed to by argument zNode (size nNode bytes) contains an
114531 ** interior node of a b-tree segment. The zTerm buffer (size nTerm bytes)
114532 ** contains a term. This function searches the sub-tree headed by the zNode
114533 ** node for the range of leaf nodes that may contain the specified term
114534 ** or terms for which the specified term is a prefix.
114536 ** If piLeaf is not NULL, then *piLeaf is set to the blockid of the
114537 ** left-most leaf node in the tree that may contain the specified term.
114538 ** If piLeaf2 is not NULL, then *piLeaf2 is set to the blockid of the
114539 ** right-most leaf node that may contain a term for which the specified
114540 ** term is a prefix.
114542 ** It is possible that the range of returned leaf nodes does not contain
114543 ** the specified term or any terms for which it is a prefix. However, if the
114544 ** segment does contain any such terms, they are stored within the identified
114545 ** range. Because this function only inspects interior segment nodes (and
114546 ** never loads leaf nodes into memory), it is not possible to be sure.
114548 ** If an error occurs, an error code other than SQLITE_OK is returned.
114550 static int fts3SelectLeaf(
114551 Fts3Table *p, /* Virtual table handle */
114552 const char *zTerm, /* Term to select leaves for */
114553 int nTerm, /* Size of term zTerm in bytes */
114554 const char *zNode, /* Buffer containing segment interior node */
114555 int nNode, /* Size of buffer at zNode */
114556 sqlite3_int64 *piLeaf, /* Selected leaf node */
114557 sqlite3_int64 *piLeaf2 /* Selected leaf node */
114559 int rc; /* Return code */
114560 int iHeight; /* Height of this node in tree */
114562 assert( piLeaf || piLeaf2 );
114564 sqlite3Fts3GetVarint32(zNode, &iHeight);
114565 rc = fts3ScanInteriorNode(zTerm, nTerm, zNode, nNode, piLeaf, piLeaf2);
114566 assert( !piLeaf2 || !piLeaf || rc!=SQLITE_OK || (*piLeaf<=*piLeaf2) );
114568 if( rc==SQLITE_OK && iHeight>1 ){
114569 char *zBlob = 0; /* Blob read from %_segments table */
114570 int nBlob; /* Size of zBlob in bytes */
114572 if( piLeaf && piLeaf2 && (*piLeaf!=*piLeaf2) ){
114573 rc = sqlite3Fts3ReadBlock(p, *piLeaf, &zBlob, &nBlob);
114574 if( rc==SQLITE_OK ){
114575 rc = fts3SelectLeaf(p, zTerm, nTerm, zBlob, nBlob, piLeaf, 0);
114577 sqlite3_free(zBlob);
114578 piLeaf = 0;
114579 zBlob = 0;
114582 if( rc==SQLITE_OK ){
114583 rc = sqlite3Fts3ReadBlock(p, piLeaf ? *piLeaf : *piLeaf2, &zBlob, &nBlob);
114585 if( rc==SQLITE_OK ){
114586 rc = fts3SelectLeaf(p, zTerm, nTerm, zBlob, nBlob, piLeaf, piLeaf2);
114588 sqlite3_free(zBlob);
114591 return rc;
114595 ** This function is used to create delta-encoded serialized lists of FTS3
114596 ** varints. Each call to this function appends a single varint to a list.
114598 static void fts3PutDeltaVarint(
114599 char **pp, /* IN/OUT: Output pointer */
114600 sqlite3_int64 *piPrev, /* IN/OUT: Previous value written to list */
114601 sqlite3_int64 iVal /* Write this value to the list */
114603 assert( iVal-*piPrev > 0 || (*piPrev==0 && iVal==0) );
114604 *pp += sqlite3Fts3PutVarint(*pp, iVal-*piPrev);
114605 *piPrev = iVal;
114609 ** When this function is called, *ppPoslist is assumed to point to the
114610 ** start of a position-list. After it returns, *ppPoslist points to the
114611 ** first byte after the position-list.
114613 ** A position list is list of positions (delta encoded) and columns for
114614 ** a single document record of a doclist. So, in other words, this
114615 ** routine advances *ppPoslist so that it points to the next docid in
114616 ** the doclist, or to the first byte past the end of the doclist.
114618 ** If pp is not NULL, then the contents of the position list are copied
114619 ** to *pp. *pp is set to point to the first byte past the last byte copied
114620 ** before this function returns.
114622 static void fts3PoslistCopy(char **pp, char **ppPoslist){
114623 char *pEnd = *ppPoslist;
114624 char c = 0;
114626 /* The end of a position list is marked by a zero encoded as an FTS3
114627 ** varint. A single POS_END (0) byte. Except, if the 0 byte is preceded by
114628 ** a byte with the 0x80 bit set, then it is not a varint 0, but the tail
114629 ** of some other, multi-byte, value.
114631 ** The following while-loop moves pEnd to point to the first byte that is not
114632 ** immediately preceded by a byte with the 0x80 bit set. Then increments
114633 ** pEnd once more so that it points to the byte immediately following the
114634 ** last byte in the position-list.
114636 while( *pEnd | c ){
114637 c = *pEnd++ & 0x80;
114638 testcase( c!=0 && (*pEnd)==0 );
114640 pEnd++; /* Advance past the POS_END terminator byte */
114642 if( pp ){
114643 int n = (int)(pEnd - *ppPoslist);
114644 char *p = *pp;
114645 memcpy(p, *ppPoslist, n);
114646 p += n;
114647 *pp = p;
114649 *ppPoslist = pEnd;
114653 ** When this function is called, *ppPoslist is assumed to point to the
114654 ** start of a column-list. After it returns, *ppPoslist points to the
114655 ** to the terminator (POS_COLUMN or POS_END) byte of the column-list.
114657 ** A column-list is list of delta-encoded positions for a single column
114658 ** within a single document within a doclist.
114660 ** The column-list is terminated either by a POS_COLUMN varint (1) or
114661 ** a POS_END varint (0). This routine leaves *ppPoslist pointing to
114662 ** the POS_COLUMN or POS_END that terminates the column-list.
114664 ** If pp is not NULL, then the contents of the column-list are copied
114665 ** to *pp. *pp is set to point to the first byte past the last byte copied
114666 ** before this function returns. The POS_COLUMN or POS_END terminator
114667 ** is not copied into *pp.
114669 static void fts3ColumnlistCopy(char **pp, char **ppPoslist){
114670 char *pEnd = *ppPoslist;
114671 char c = 0;
114673 /* A column-list is terminated by either a 0x01 or 0x00 byte that is
114674 ** not part of a multi-byte varint.
114676 while( 0xFE & (*pEnd | c) ){
114677 c = *pEnd++ & 0x80;
114678 testcase( c!=0 && ((*pEnd)&0xfe)==0 );
114680 if( pp ){
114681 int n = (int)(pEnd - *ppPoslist);
114682 char *p = *pp;
114683 memcpy(p, *ppPoslist, n);
114684 p += n;
114685 *pp = p;
114687 *ppPoslist = pEnd;
114691 ** Value used to signify the end of an position-list. This is safe because
114692 ** it is not possible to have a document with 2^31 terms.
114694 #define POSITION_LIST_END 0x7fffffff
114697 ** This function is used to help parse position-lists. When this function is
114698 ** called, *pp may point to the start of the next varint in the position-list
114699 ** being parsed, or it may point to 1 byte past the end of the position-list
114700 ** (in which case **pp will be a terminator bytes POS_END (0) or
114701 ** (1)).
114703 ** If *pp points past the end of the current position-list, set *pi to
114704 ** POSITION_LIST_END and return. Otherwise, read the next varint from *pp,
114705 ** increment the current value of *pi by the value read, and set *pp to
114706 ** point to the next value before returning.
114708 ** Before calling this routine *pi must be initialized to the value of
114709 ** the previous position, or zero if we are reading the first position
114710 ** in the position-list. Because positions are delta-encoded, the value
114711 ** of the previous position is needed in order to compute the value of
114712 ** the next position.
114714 static void fts3ReadNextPos(
114715 char **pp, /* IN/OUT: Pointer into position-list buffer */
114716 sqlite3_int64 *pi /* IN/OUT: Value read from position-list */
114718 if( (**pp)&0xFE ){
114719 fts3GetDeltaVarint(pp, pi);
114720 *pi -= 2;
114721 }else{
114722 *pi = POSITION_LIST_END;
114727 ** If parameter iCol is not 0, write an POS_COLUMN (1) byte followed by
114728 ** the value of iCol encoded as a varint to *pp. This will start a new
114729 ** column list.
114731 ** Set *pp to point to the byte just after the last byte written before
114732 ** returning (do not modify it if iCol==0). Return the total number of bytes
114733 ** written (0 if iCol==0).
114735 static int fts3PutColNumber(char **pp, int iCol){
114736 int n = 0; /* Number of bytes written */
114737 if( iCol ){
114738 char *p = *pp; /* Output pointer */
114739 n = 1 + sqlite3Fts3PutVarint(&p[1], iCol);
114740 *p = 0x01;
114741 *pp = &p[n];
114743 return n;
114747 ** Compute the union of two position lists. The output written
114748 ** into *pp contains all positions of both *pp1 and *pp2 in sorted
114749 ** order and with any duplicates removed. All pointers are
114750 ** updated appropriately. The caller is responsible for insuring
114751 ** that there is enough space in *pp to hold the complete output.
114753 static void fts3PoslistMerge(
114754 char **pp, /* Output buffer */
114755 char **pp1, /* Left input list */
114756 char **pp2 /* Right input list */
114758 char *p = *pp;
114759 char *p1 = *pp1;
114760 char *p2 = *pp2;
114762 while( *p1 || *p2 ){
114763 int iCol1; /* The current column index in pp1 */
114764 int iCol2; /* The current column index in pp2 */
114766 if( *p1==POS_COLUMN ) sqlite3Fts3GetVarint32(&p1[1], &iCol1);
114767 else if( *p1==POS_END ) iCol1 = POSITION_LIST_END;
114768 else iCol1 = 0;
114770 if( *p2==POS_COLUMN ) sqlite3Fts3GetVarint32(&p2[1], &iCol2);
114771 else if( *p2==POS_END ) iCol2 = POSITION_LIST_END;
114772 else iCol2 = 0;
114774 if( iCol1==iCol2 ){
114775 sqlite3_int64 i1 = 0; /* Last position from pp1 */
114776 sqlite3_int64 i2 = 0; /* Last position from pp2 */
114777 sqlite3_int64 iPrev = 0;
114778 int n = fts3PutColNumber(&p, iCol1);
114779 p1 += n;
114780 p2 += n;
114782 /* At this point, both p1 and p2 point to the start of column-lists
114783 ** for the same column (the column with index iCol1 and iCol2).
114784 ** A column-list is a list of non-negative delta-encoded varints, each
114785 ** incremented by 2 before being stored. Each list is terminated by a
114786 ** POS_END (0) or POS_COLUMN (1). The following block merges the two lists
114787 ** and writes the results to buffer p. p is left pointing to the byte
114788 ** after the list written. No terminator (POS_END or POS_COLUMN) is
114789 ** written to the output.
114791 fts3GetDeltaVarint(&p1, &i1);
114792 fts3GetDeltaVarint(&p2, &i2);
114794 fts3PutDeltaVarint(&p, &iPrev, (i1<i2) ? i1 : i2);
114795 iPrev -= 2;
114796 if( i1==i2 ){
114797 fts3ReadNextPos(&p1, &i1);
114798 fts3ReadNextPos(&p2, &i2);
114799 }else if( i1<i2 ){
114800 fts3ReadNextPos(&p1, &i1);
114801 }else{
114802 fts3ReadNextPos(&p2, &i2);
114804 }while( i1!=POSITION_LIST_END || i2!=POSITION_LIST_END );
114805 }else if( iCol1<iCol2 ){
114806 p1 += fts3PutColNumber(&p, iCol1);
114807 fts3ColumnlistCopy(&p, &p1);
114808 }else{
114809 p2 += fts3PutColNumber(&p, iCol2);
114810 fts3ColumnlistCopy(&p, &p2);
114814 *p++ = POS_END;
114815 *pp = p;
114816 *pp1 = p1 + 1;
114817 *pp2 = p2 + 1;
114821 ** nToken==1 searches for adjacent positions.
114823 ** This function is used to merge two position lists into one. When it is
114824 ** called, *pp1 and *pp2 must both point to position lists. A position-list is
114825 ** the part of a doclist that follows each document id. For example, if a row
114826 ** contains:
114828 ** 'a b c'|'x y z'|'a b b a'
114830 ** Then the position list for this row for token 'b' would consist of:
114832 ** 0x02 0x01 0x02 0x03 0x03 0x00
114834 ** When this function returns, both *pp1 and *pp2 are left pointing to the
114835 ** byte following the 0x00 terminator of their respective position lists.
114837 ** If isSaveLeft is 0, an entry is added to the output position list for
114838 ** each position in *pp2 for which there exists one or more positions in
114839 ** *pp1 so that (pos(*pp2)>pos(*pp1) && pos(*pp2)-pos(*pp1)<=nToken). i.e.
114840 ** when the *pp1 token appears before the *pp2 token, but not more than nToken
114841 ** slots before it.
114843 static int fts3PoslistPhraseMerge(
114844 char **pp, /* IN/OUT: Preallocated output buffer */
114845 int nToken, /* Maximum difference in token positions */
114846 int isSaveLeft, /* Save the left position */
114847 int isExact, /* If *pp1 is exactly nTokens before *pp2 */
114848 char **pp1, /* IN/OUT: Left input list */
114849 char **pp2 /* IN/OUT: Right input list */
114851 char *p = (pp ? *pp : 0);
114852 char *p1 = *pp1;
114853 char *p2 = *pp2;
114854 int iCol1 = 0;
114855 int iCol2 = 0;
114857 /* Never set both isSaveLeft and isExact for the same invocation. */
114858 assert( isSaveLeft==0 || isExact==0 );
114860 assert( *p1!=0 && *p2!=0 );
114861 if( *p1==POS_COLUMN ){
114862 p1++;
114863 p1 += sqlite3Fts3GetVarint32(p1, &iCol1);
114865 if( *p2==POS_COLUMN ){
114866 p2++;
114867 p2 += sqlite3Fts3GetVarint32(p2, &iCol2);
114870 while( 1 ){
114871 if( iCol1==iCol2 ){
114872 char *pSave = p;
114873 sqlite3_int64 iPrev = 0;
114874 sqlite3_int64 iPos1 = 0;
114875 sqlite3_int64 iPos2 = 0;
114877 if( pp && iCol1 ){
114878 *p++ = POS_COLUMN;
114879 p += sqlite3Fts3PutVarint(p, iCol1);
114882 assert( *p1!=POS_END && *p1!=POS_COLUMN );
114883 assert( *p2!=POS_END && *p2!=POS_COLUMN );
114884 fts3GetDeltaVarint(&p1, &iPos1); iPos1 -= 2;
114885 fts3GetDeltaVarint(&p2, &iPos2); iPos2 -= 2;
114887 while( 1 ){
114888 if( iPos2==iPos1+nToken
114889 || (isExact==0 && iPos2>iPos1 && iPos2<=iPos1+nToken)
114891 sqlite3_int64 iSave;
114892 if( !pp ){
114893 fts3PoslistCopy(0, &p2);
114894 fts3PoslistCopy(0, &p1);
114895 *pp1 = p1;
114896 *pp2 = p2;
114897 return 1;
114899 iSave = isSaveLeft ? iPos1 : iPos2;
114900 fts3PutDeltaVarint(&p, &iPrev, iSave+2); iPrev -= 2;
114901 pSave = 0;
114903 if( (!isSaveLeft && iPos2<=(iPos1+nToken)) || iPos2<=iPos1 ){
114904 if( (*p2&0xFE)==0 ) break;
114905 fts3GetDeltaVarint(&p2, &iPos2); iPos2 -= 2;
114906 }else{
114907 if( (*p1&0xFE)==0 ) break;
114908 fts3GetDeltaVarint(&p1, &iPos1); iPos1 -= 2;
114912 if( pSave ){
114913 assert( pp && p );
114914 p = pSave;
114917 fts3ColumnlistCopy(0, &p1);
114918 fts3ColumnlistCopy(0, &p2);
114919 assert( (*p1&0xFE)==0 && (*p2&0xFE)==0 );
114920 if( 0==*p1 || 0==*p2 ) break;
114922 p1++;
114923 p1 += sqlite3Fts3GetVarint32(p1, &iCol1);
114924 p2++;
114925 p2 += sqlite3Fts3GetVarint32(p2, &iCol2);
114928 /* Advance pointer p1 or p2 (whichever corresponds to the smaller of
114929 ** iCol1 and iCol2) so that it points to either the 0x00 that marks the
114930 ** end of the position list, or the 0x01 that precedes the next
114931 ** column-number in the position list.
114933 else if( iCol1<iCol2 ){
114934 fts3ColumnlistCopy(0, &p1);
114935 if( 0==*p1 ) break;
114936 p1++;
114937 p1 += sqlite3Fts3GetVarint32(p1, &iCol1);
114938 }else{
114939 fts3ColumnlistCopy(0, &p2);
114940 if( 0==*p2 ) break;
114941 p2++;
114942 p2 += sqlite3Fts3GetVarint32(p2, &iCol2);
114946 fts3PoslistCopy(0, &p2);
114947 fts3PoslistCopy(0, &p1);
114948 *pp1 = p1;
114949 *pp2 = p2;
114950 if( !pp || *pp==p ){
114951 return 0;
114953 *p++ = 0x00;
114954 *pp = p;
114955 return 1;
114959 ** Merge two position-lists as required by the NEAR operator.
114961 static int fts3PoslistNearMerge(
114962 char **pp, /* Output buffer */
114963 char *aTmp, /* Temporary buffer space */
114964 int nRight, /* Maximum difference in token positions */
114965 int nLeft, /* Maximum difference in token positions */
114966 char **pp1, /* IN/OUT: Left input list */
114967 char **pp2 /* IN/OUT: Right input list */
114969 char *p1 = *pp1;
114970 char *p2 = *pp2;
114972 if( !pp ){
114973 if( fts3PoslistPhraseMerge(0, nRight, 0, 0, pp1, pp2) ) return 1;
114974 *pp1 = p1;
114975 *pp2 = p2;
114976 return fts3PoslistPhraseMerge(0, nLeft, 0, 0, pp2, pp1);
114977 }else{
114978 char *pTmp1 = aTmp;
114979 char *pTmp2;
114980 char *aTmp2;
114981 int res = 1;
114983 fts3PoslistPhraseMerge(&pTmp1, nRight, 0, 0, pp1, pp2);
114984 aTmp2 = pTmp2 = pTmp1;
114985 *pp1 = p1;
114986 *pp2 = p2;
114987 fts3PoslistPhraseMerge(&pTmp2, nLeft, 1, 0, pp2, pp1);
114988 if( pTmp1!=aTmp && pTmp2!=aTmp2 ){
114989 fts3PoslistMerge(pp, &aTmp, &aTmp2);
114990 }else if( pTmp1!=aTmp ){
114991 fts3PoslistCopy(pp, &aTmp);
114992 }else if( pTmp2!=aTmp2 ){
114993 fts3PoslistCopy(pp, &aTmp2);
114994 }else{
114995 res = 0;
114998 return res;
115003 ** Values that may be used as the first parameter to fts3DoclistMerge().
115005 #define MERGE_NOT 2 /* D + D -> D */
115006 #define MERGE_AND 3 /* D + D -> D */
115007 #define MERGE_OR 4 /* D + D -> D */
115008 #define MERGE_POS_OR 5 /* P + P -> P */
115009 #define MERGE_PHRASE 6 /* P + P -> D */
115010 #define MERGE_POS_PHRASE 7 /* P + P -> P */
115011 #define MERGE_NEAR 8 /* P + P -> D */
115012 #define MERGE_POS_NEAR 9 /* P + P -> P */
115015 ** Merge the two doclists passed in buffer a1 (size n1 bytes) and a2
115016 ** (size n2 bytes). The output is written to pre-allocated buffer aBuffer,
115017 ** which is guaranteed to be large enough to hold the results. The number
115018 ** of bytes written to aBuffer is stored in *pnBuffer before returning.
115020 ** If successful, SQLITE_OK is returned. Otherwise, if a malloc error
115021 ** occurs while allocating a temporary buffer as part of the merge operation,
115022 ** SQLITE_NOMEM is returned.
115024 static int fts3DoclistMerge(
115025 int mergetype, /* One of the MERGE_XXX constants */
115026 int nParam1, /* Used by MERGE_NEAR and MERGE_POS_NEAR */
115027 int nParam2, /* Used by MERGE_NEAR and MERGE_POS_NEAR */
115028 char *aBuffer, /* Pre-allocated output buffer */
115029 int *pnBuffer, /* OUT: Bytes written to aBuffer */
115030 char *a1, /* Buffer containing first doclist */
115031 int n1, /* Size of buffer a1 */
115032 char *a2, /* Buffer containing second doclist */
115033 int n2, /* Size of buffer a2 */
115034 int *pnDoc /* OUT: Number of docids in output */
115036 sqlite3_int64 i1 = 0;
115037 sqlite3_int64 i2 = 0;
115038 sqlite3_int64 iPrev = 0;
115040 char *p = aBuffer;
115041 char *p1 = a1;
115042 char *p2 = a2;
115043 char *pEnd1 = &a1[n1];
115044 char *pEnd2 = &a2[n2];
115045 int nDoc = 0;
115047 assert( mergetype==MERGE_OR || mergetype==MERGE_POS_OR
115048 || mergetype==MERGE_AND || mergetype==MERGE_NOT
115049 || mergetype==MERGE_PHRASE || mergetype==MERGE_POS_PHRASE
115050 || mergetype==MERGE_NEAR || mergetype==MERGE_POS_NEAR
115053 if( !aBuffer ){
115054 *pnBuffer = 0;
115055 return SQLITE_NOMEM;
115058 /* Read the first docid from each doclist */
115059 fts3GetDeltaVarint2(&p1, pEnd1, &i1);
115060 fts3GetDeltaVarint2(&p2, pEnd2, &i2);
115062 switch( mergetype ){
115063 case MERGE_OR:
115064 case MERGE_POS_OR:
115065 while( p1 || p2 ){
115066 if( p2 && p1 && i1==i2 ){
115067 fts3PutDeltaVarint(&p, &iPrev, i1);
115068 if( mergetype==MERGE_POS_OR ) fts3PoslistMerge(&p, &p1, &p2);
115069 fts3GetDeltaVarint2(&p1, pEnd1, &i1);
115070 fts3GetDeltaVarint2(&p2, pEnd2, &i2);
115071 }else if( !p2 || (p1 && i1<i2) ){
115072 fts3PutDeltaVarint(&p, &iPrev, i1);
115073 if( mergetype==MERGE_POS_OR ) fts3PoslistCopy(&p, &p1);
115074 fts3GetDeltaVarint2(&p1, pEnd1, &i1);
115075 }else{
115076 fts3PutDeltaVarint(&p, &iPrev, i2);
115077 if( mergetype==MERGE_POS_OR ) fts3PoslistCopy(&p, &p2);
115078 fts3GetDeltaVarint2(&p2, pEnd2, &i2);
115081 break;
115083 case MERGE_AND:
115084 while( p1 && p2 ){
115085 if( i1==i2 ){
115086 fts3PutDeltaVarint(&p, &iPrev, i1);
115087 fts3GetDeltaVarint2(&p1, pEnd1, &i1);
115088 fts3GetDeltaVarint2(&p2, pEnd2, &i2);
115089 nDoc++;
115090 }else if( i1<i2 ){
115091 fts3GetDeltaVarint2(&p1, pEnd1, &i1);
115092 }else{
115093 fts3GetDeltaVarint2(&p2, pEnd2, &i2);
115096 break;
115098 case MERGE_NOT:
115099 while( p1 ){
115100 if( p2 && i1==i2 ){
115101 fts3GetDeltaVarint2(&p1, pEnd1, &i1);
115102 fts3GetDeltaVarint2(&p2, pEnd2, &i2);
115103 }else if( !p2 || i1<i2 ){
115104 fts3PutDeltaVarint(&p, &iPrev, i1);
115105 fts3GetDeltaVarint2(&p1, pEnd1, &i1);
115106 }else{
115107 fts3GetDeltaVarint2(&p2, pEnd2, &i2);
115110 break;
115112 case MERGE_POS_PHRASE:
115113 case MERGE_PHRASE: {
115114 char **ppPos = (mergetype==MERGE_PHRASE ? 0 : &p);
115115 while( p1 && p2 ){
115116 if( i1==i2 ){
115117 char *pSave = p;
115118 sqlite3_int64 iPrevSave = iPrev;
115119 fts3PutDeltaVarint(&p, &iPrev, i1);
115120 if( 0==fts3PoslistPhraseMerge(ppPos, nParam1, 0, 1, &p1, &p2) ){
115121 p = pSave;
115122 iPrev = iPrevSave;
115123 }else{
115124 nDoc++;
115126 fts3GetDeltaVarint2(&p1, pEnd1, &i1);
115127 fts3GetDeltaVarint2(&p2, pEnd2, &i2);
115128 }else if( i1<i2 ){
115129 fts3PoslistCopy(0, &p1);
115130 fts3GetDeltaVarint2(&p1, pEnd1, &i1);
115131 }else{
115132 fts3PoslistCopy(0, &p2);
115133 fts3GetDeltaVarint2(&p2, pEnd2, &i2);
115136 break;
115139 default: assert( mergetype==MERGE_POS_NEAR || mergetype==MERGE_NEAR ); {
115140 char *aTmp = 0;
115141 char **ppPos = 0;
115143 if( mergetype==MERGE_POS_NEAR ){
115144 ppPos = &p;
115145 aTmp = sqlite3_malloc(2*(n1+n2+1));
115146 if( !aTmp ){
115147 return SQLITE_NOMEM;
115151 while( p1 && p2 ){
115152 if( i1==i2 ){
115153 char *pSave = p;
115154 sqlite3_int64 iPrevSave = iPrev;
115155 fts3PutDeltaVarint(&p, &iPrev, i1);
115157 if( !fts3PoslistNearMerge(ppPos, aTmp, nParam1, nParam2, &p1, &p2) ){
115158 iPrev = iPrevSave;
115159 p = pSave;
115162 fts3GetDeltaVarint2(&p1, pEnd1, &i1);
115163 fts3GetDeltaVarint2(&p2, pEnd2, &i2);
115164 }else if( i1<i2 ){
115165 fts3PoslistCopy(0, &p1);
115166 fts3GetDeltaVarint2(&p1, pEnd1, &i1);
115167 }else{
115168 fts3PoslistCopy(0, &p2);
115169 fts3GetDeltaVarint2(&p2, pEnd2, &i2);
115172 sqlite3_free(aTmp);
115173 break;
115177 if( pnDoc ) *pnDoc = nDoc;
115178 *pnBuffer = (int)(p-aBuffer);
115179 return SQLITE_OK;
115183 ** A pointer to an instance of this structure is used as the context
115184 ** argument to sqlite3Fts3SegReaderIterate()
115186 typedef struct TermSelect TermSelect;
115187 struct TermSelect {
115188 int isReqPos;
115189 char *aaOutput[16]; /* Malloc'd output buffer */
115190 int anOutput[16]; /* Size of output in bytes */
115194 ** Merge all doclists in the TermSelect.aaOutput[] array into a single
115195 ** doclist stored in TermSelect.aaOutput[0]. If successful, delete all
115196 ** other doclists (except the aaOutput[0] one) and return SQLITE_OK.
115198 ** If an OOM error occurs, return SQLITE_NOMEM. In this case it is
115199 ** the responsibility of the caller to free any doclists left in the
115200 ** TermSelect.aaOutput[] array.
115202 static int fts3TermSelectMerge(TermSelect *pTS){
115203 int mergetype = (pTS->isReqPos ? MERGE_POS_OR : MERGE_OR);
115204 char *aOut = 0;
115205 int nOut = 0;
115206 int i;
115208 /* Loop through the doclists in the aaOutput[] array. Merge them all
115209 ** into a single doclist.
115211 for(i=0; i<SizeofArray(pTS->aaOutput); i++){
115212 if( pTS->aaOutput[i] ){
115213 if( !aOut ){
115214 aOut = pTS->aaOutput[i];
115215 nOut = pTS->anOutput[i];
115216 pTS->aaOutput[i] = 0;
115217 }else{
115218 int nNew = nOut + pTS->anOutput[i];
115219 char *aNew = sqlite3_malloc(nNew);
115220 if( !aNew ){
115221 sqlite3_free(aOut);
115222 return SQLITE_NOMEM;
115224 fts3DoclistMerge(mergetype, 0, 0,
115225 aNew, &nNew, pTS->aaOutput[i], pTS->anOutput[i], aOut, nOut, 0
115227 sqlite3_free(pTS->aaOutput[i]);
115228 sqlite3_free(aOut);
115229 pTS->aaOutput[i] = 0;
115230 aOut = aNew;
115231 nOut = nNew;
115236 pTS->aaOutput[0] = aOut;
115237 pTS->anOutput[0] = nOut;
115238 return SQLITE_OK;
115242 ** This function is used as the sqlite3Fts3SegReaderIterate() callback when
115243 ** querying the full-text index for a doclist associated with a term or
115244 ** term-prefix.
115246 static int fts3TermSelectCb(
115247 Fts3Table *p, /* Virtual table object */
115248 void *pContext, /* Pointer to TermSelect structure */
115249 char *zTerm,
115250 int nTerm,
115251 char *aDoclist,
115252 int nDoclist
115254 TermSelect *pTS = (TermSelect *)pContext;
115256 UNUSED_PARAMETER(p);
115257 UNUSED_PARAMETER(zTerm);
115258 UNUSED_PARAMETER(nTerm);
115260 if( pTS->aaOutput[0]==0 ){
115261 /* If this is the first term selected, copy the doclist to the output
115262 ** buffer using memcpy(). TODO: Add a way to transfer control of the
115263 ** aDoclist buffer from the caller so as to avoid the memcpy().
115265 pTS->aaOutput[0] = sqlite3_malloc(nDoclist);
115266 pTS->anOutput[0] = nDoclist;
115267 if( pTS->aaOutput[0] ){
115268 memcpy(pTS->aaOutput[0], aDoclist, nDoclist);
115269 }else{
115270 return SQLITE_NOMEM;
115272 }else{
115273 int mergetype = (pTS->isReqPos ? MERGE_POS_OR : MERGE_OR);
115274 char *aMerge = aDoclist;
115275 int nMerge = nDoclist;
115276 int iOut;
115278 for(iOut=0; iOut<SizeofArray(pTS->aaOutput); iOut++){
115279 char *aNew;
115280 int nNew;
115281 if( pTS->aaOutput[iOut]==0 ){
115282 assert( iOut>0 );
115283 pTS->aaOutput[iOut] = aMerge;
115284 pTS->anOutput[iOut] = nMerge;
115285 break;
115288 nNew = nMerge + pTS->anOutput[iOut];
115289 aNew = sqlite3_malloc(nNew);
115290 if( !aNew ){
115291 if( aMerge!=aDoclist ){
115292 sqlite3_free(aMerge);
115294 return SQLITE_NOMEM;
115296 fts3DoclistMerge(mergetype, 0, 0, aNew, &nNew,
115297 pTS->aaOutput[iOut], pTS->anOutput[iOut], aMerge, nMerge, 0
115300 if( iOut>0 ) sqlite3_free(aMerge);
115301 sqlite3_free(pTS->aaOutput[iOut]);
115302 pTS->aaOutput[iOut] = 0;
115304 aMerge = aNew;
115305 nMerge = nNew;
115306 if( (iOut+1)==SizeofArray(pTS->aaOutput) ){
115307 pTS->aaOutput[iOut] = aMerge;
115308 pTS->anOutput[iOut] = nMerge;
115312 return SQLITE_OK;
115315 static int fts3DeferredTermSelect(
115316 Fts3DeferredToken *pToken, /* Phrase token */
115317 int isTermPos, /* True to include positions */
115318 int *pnOut, /* OUT: Size of list */
115319 char **ppOut /* OUT: Body of list */
115321 char *aSource;
115322 int nSource;
115324 aSource = sqlite3Fts3DeferredDoclist(pToken, &nSource);
115325 if( !aSource ){
115326 *pnOut = 0;
115327 *ppOut = 0;
115328 }else if( isTermPos ){
115329 *ppOut = sqlite3_malloc(nSource);
115330 if( !*ppOut ) return SQLITE_NOMEM;
115331 memcpy(*ppOut, aSource, nSource);
115332 *pnOut = nSource;
115333 }else{
115334 sqlite3_int64 docid;
115335 *pnOut = sqlite3Fts3GetVarint(aSource, &docid);
115336 *ppOut = sqlite3_malloc(*pnOut);
115337 if( !*ppOut ) return SQLITE_NOMEM;
115338 sqlite3Fts3PutVarint(*ppOut, docid);
115341 return SQLITE_OK;
115344 SQLITE_PRIVATE int sqlite3Fts3SegReaderCursor(
115345 Fts3Table *p, /* FTS3 table handle */
115346 int iLevel, /* Level of segments to scan */
115347 const char *zTerm, /* Term to query for */
115348 int nTerm, /* Size of zTerm in bytes */
115349 int isPrefix, /* True for a prefix search */
115350 int isScan, /* True to scan from zTerm to EOF */
115351 Fts3SegReaderCursor *pCsr /* Cursor object to populate */
115353 int rc = SQLITE_OK;
115354 int rc2;
115355 int iAge = 0;
115356 sqlite3_stmt *pStmt = 0;
115357 Fts3SegReader *pPending = 0;
115359 assert( iLevel==FTS3_SEGCURSOR_ALL
115360 || iLevel==FTS3_SEGCURSOR_PENDING
115361 || iLevel>=0
115363 assert( FTS3_SEGCURSOR_PENDING<0 );
115364 assert( FTS3_SEGCURSOR_ALL<0 );
115365 assert( iLevel==FTS3_SEGCURSOR_ALL || (zTerm==0 && isPrefix==1) );
115366 assert( isPrefix==0 || isScan==0 );
115369 memset(pCsr, 0, sizeof(Fts3SegReaderCursor));
115371 /* If iLevel is less than 0, include a seg-reader for the pending-terms. */
115372 assert( isScan==0 || fts3HashCount(&p->pendingTerms)==0 );
115373 if( iLevel<0 && isScan==0 ){
115374 rc = sqlite3Fts3SegReaderPending(p, zTerm, nTerm, isPrefix, &pPending);
115375 if( rc==SQLITE_OK && pPending ){
115376 int nByte = (sizeof(Fts3SegReader *) * 16);
115377 pCsr->apSegment = (Fts3SegReader **)sqlite3_malloc(nByte);
115378 if( pCsr->apSegment==0 ){
115379 rc = SQLITE_NOMEM;
115380 }else{
115381 pCsr->apSegment[0] = pPending;
115382 pCsr->nSegment = 1;
115383 pPending = 0;
115388 if( iLevel!=FTS3_SEGCURSOR_PENDING ){
115389 if( rc==SQLITE_OK ){
115390 rc = sqlite3Fts3AllSegdirs(p, iLevel, &pStmt);
115392 while( rc==SQLITE_OK && SQLITE_ROW==(rc = sqlite3_step(pStmt)) ){
115394 /* Read the values returned by the SELECT into local variables. */
115395 sqlite3_int64 iStartBlock = sqlite3_column_int64(pStmt, 1);
115396 sqlite3_int64 iLeavesEndBlock = sqlite3_column_int64(pStmt, 2);
115397 sqlite3_int64 iEndBlock = sqlite3_column_int64(pStmt, 3);
115398 int nRoot = sqlite3_column_bytes(pStmt, 4);
115399 char const *zRoot = sqlite3_column_blob(pStmt, 4);
115401 /* If nSegment is a multiple of 16 the array needs to be extended. */
115402 if( (pCsr->nSegment%16)==0 ){
115403 Fts3SegReader **apNew;
115404 int nByte = (pCsr->nSegment + 16)*sizeof(Fts3SegReader*);
115405 apNew = (Fts3SegReader **)sqlite3_realloc(pCsr->apSegment, nByte);
115406 if( !apNew ){
115407 rc = SQLITE_NOMEM;
115408 goto finished;
115410 pCsr->apSegment = apNew;
115413 /* If zTerm is not NULL, and this segment is not stored entirely on its
115414 ** root node, the range of leaves scanned can be reduced. Do this. */
115415 if( iStartBlock && zTerm ){
115416 sqlite3_int64 *pi = (isPrefix ? &iLeavesEndBlock : 0);
115417 rc = fts3SelectLeaf(p, zTerm, nTerm, zRoot, nRoot, &iStartBlock, pi);
115418 if( rc!=SQLITE_OK ) goto finished;
115419 if( isPrefix==0 && isScan==0 ) iLeavesEndBlock = iStartBlock;
115422 rc = sqlite3Fts3SegReaderNew(iAge, iStartBlock, iLeavesEndBlock,
115423 iEndBlock, zRoot, nRoot, &pCsr->apSegment[pCsr->nSegment]
115425 if( rc!=SQLITE_OK ) goto finished;
115426 pCsr->nSegment++;
115427 iAge++;
115431 finished:
115432 rc2 = sqlite3_reset(pStmt);
115433 if( rc==SQLITE_DONE ) rc = rc2;
115434 sqlite3Fts3SegReaderFree(pPending);
115436 return rc;
115440 static int fts3TermSegReaderCursor(
115441 Fts3Cursor *pCsr, /* Virtual table cursor handle */
115442 const char *zTerm, /* Term to query for */
115443 int nTerm, /* Size of zTerm in bytes */
115444 int isPrefix, /* True for a prefix search */
115445 Fts3SegReaderCursor **ppSegcsr /* OUT: Allocated seg-reader cursor */
115447 Fts3SegReaderCursor *pSegcsr; /* Object to allocate and return */
115448 int rc = SQLITE_NOMEM; /* Return code */
115450 pSegcsr = sqlite3_malloc(sizeof(Fts3SegReaderCursor));
115451 if( pSegcsr ){
115452 Fts3Table *p = (Fts3Table *)pCsr->base.pVtab;
115453 int i;
115454 int nCost = 0;
115455 rc = sqlite3Fts3SegReaderCursor(
115456 p, FTS3_SEGCURSOR_ALL, zTerm, nTerm, isPrefix, 0, pSegcsr);
115458 for(i=0; rc==SQLITE_OK && i<pSegcsr->nSegment; i++){
115459 rc = sqlite3Fts3SegReaderCost(pCsr, pSegcsr->apSegment[i], &nCost);
115461 pSegcsr->nCost = nCost;
115464 *ppSegcsr = pSegcsr;
115465 return rc;
115468 static void fts3SegReaderCursorFree(Fts3SegReaderCursor *pSegcsr){
115469 sqlite3Fts3SegReaderFinish(pSegcsr);
115470 sqlite3_free(pSegcsr);
115474 ** This function retreives the doclist for the specified term (or term
115475 ** prefix) from the database.
115477 ** The returned doclist may be in one of two formats, depending on the
115478 ** value of parameter isReqPos. If isReqPos is zero, then the doclist is
115479 ** a sorted list of delta-compressed docids (a bare doclist). If isReqPos
115480 ** is non-zero, then the returned list is in the same format as is stored
115481 ** in the database without the found length specifier at the start of on-disk
115482 ** doclists.
115484 static int fts3TermSelect(
115485 Fts3Table *p, /* Virtual table handle */
115486 Fts3PhraseToken *pTok, /* Token to query for */
115487 int iColumn, /* Column to query (or -ve for all columns) */
115488 int isReqPos, /* True to include position lists in output */
115489 int *pnOut, /* OUT: Size of buffer at *ppOut */
115490 char **ppOut /* OUT: Malloced result buffer */
115492 int rc; /* Return code */
115493 Fts3SegReaderCursor *pSegcsr; /* Seg-reader cursor for this term */
115494 TermSelect tsc; /* Context object for fts3TermSelectCb() */
115495 Fts3SegFilter filter; /* Segment term filter configuration */
115497 pSegcsr = pTok->pSegcsr;
115498 memset(&tsc, 0, sizeof(TermSelect));
115499 tsc.isReqPos = isReqPos;
115501 filter.flags = FTS3_SEGMENT_IGNORE_EMPTY
115502 | (pTok->isPrefix ? FTS3_SEGMENT_PREFIX : 0)
115503 | (isReqPos ? FTS3_SEGMENT_REQUIRE_POS : 0)
115504 | (iColumn<p->nColumn ? FTS3_SEGMENT_COLUMN_FILTER : 0);
115505 filter.iCol = iColumn;
115506 filter.zTerm = pTok->z;
115507 filter.nTerm = pTok->n;
115509 rc = sqlite3Fts3SegReaderStart(p, pSegcsr, &filter);
115510 while( SQLITE_OK==rc
115511 && SQLITE_ROW==(rc = sqlite3Fts3SegReaderStep(p, pSegcsr))
115513 rc = fts3TermSelectCb(p, (void *)&tsc,
115514 pSegcsr->zTerm, pSegcsr->nTerm, pSegcsr->aDoclist, pSegcsr->nDoclist
115518 if( rc==SQLITE_OK ){
115519 rc = fts3TermSelectMerge(&tsc);
115521 if( rc==SQLITE_OK ){
115522 *ppOut = tsc.aaOutput[0];
115523 *pnOut = tsc.anOutput[0];
115524 }else{
115525 int i;
115526 for(i=0; i<SizeofArray(tsc.aaOutput); i++){
115527 sqlite3_free(tsc.aaOutput[i]);
115531 fts3SegReaderCursorFree(pSegcsr);
115532 pTok->pSegcsr = 0;
115533 return rc;
115537 ** This function counts the total number of docids in the doclist stored
115538 ** in buffer aList[], size nList bytes.
115540 ** If the isPoslist argument is true, then it is assumed that the doclist
115541 ** contains a position-list following each docid. Otherwise, it is assumed
115542 ** that the doclist is simply a list of docids stored as delta encoded
115543 ** varints.
115545 static int fts3DoclistCountDocids(int isPoslist, char *aList, int nList){
115546 int nDoc = 0; /* Return value */
115547 if( aList ){
115548 char *aEnd = &aList[nList]; /* Pointer to one byte after EOF */
115549 char *p = aList; /* Cursor */
115550 if( !isPoslist ){
115551 /* The number of docids in the list is the same as the number of
115552 ** varints. In FTS3 a varint consists of a single byte with the 0x80
115553 ** bit cleared and zero or more bytes with the 0x80 bit set. So to
115554 ** count the varints in the buffer, just count the number of bytes
115555 ** with the 0x80 bit clear. */
115556 while( p<aEnd ) nDoc += (((*p++)&0x80)==0);
115557 }else{
115558 while( p<aEnd ){
115559 nDoc++;
115560 while( (*p++)&0x80 ); /* Skip docid varint */
115561 fts3PoslistCopy(0, &p); /* Skip over position list */
115566 return nDoc;
115570 ** Call sqlite3Fts3DeferToken() for each token in the expression pExpr.
115572 static int fts3DeferExpression(Fts3Cursor *pCsr, Fts3Expr *pExpr){
115573 int rc = SQLITE_OK;
115574 if( pExpr ){
115575 rc = fts3DeferExpression(pCsr, pExpr->pLeft);
115576 if( rc==SQLITE_OK ){
115577 rc = fts3DeferExpression(pCsr, pExpr->pRight);
115579 if( pExpr->eType==FTSQUERY_PHRASE ){
115580 int iCol = pExpr->pPhrase->iColumn;
115581 int i;
115582 for(i=0; rc==SQLITE_OK && i<pExpr->pPhrase->nToken; i++){
115583 Fts3PhraseToken *pToken = &pExpr->pPhrase->aToken[i];
115584 if( pToken->pDeferred==0 ){
115585 rc = sqlite3Fts3DeferToken(pCsr, pToken, iCol);
115590 return rc;
115594 ** This function removes the position information from a doclist. When
115595 ** called, buffer aList (size *pnList bytes) contains a doclist that includes
115596 ** position information. This function removes the position information so
115597 ** that aList contains only docids, and adjusts *pnList to reflect the new
115598 ** (possibly reduced) size of the doclist.
115600 static void fts3DoclistStripPositions(
115601 char *aList, /* IN/OUT: Buffer containing doclist */
115602 int *pnList /* IN/OUT: Size of doclist in bytes */
115604 if( aList ){
115605 char *aEnd = &aList[*pnList]; /* Pointer to one byte after EOF */
115606 char *p = aList; /* Input cursor */
115607 char *pOut = aList; /* Output cursor */
115609 while( p<aEnd ){
115610 sqlite3_int64 delta;
115611 p += sqlite3Fts3GetVarint(p, &delta);
115612 fts3PoslistCopy(0, &p);
115613 pOut += sqlite3Fts3PutVarint(pOut, delta);
115616 *pnList = (int)(pOut - aList);
115621 ** Return a DocList corresponding to the phrase *pPhrase.
115623 ** If this function returns SQLITE_OK, but *pnOut is set to a negative value,
115624 ** then no tokens in the phrase were looked up in the full-text index. This
115625 ** is only possible when this function is called from within xFilter(). The
115626 ** caller should assume that all documents match the phrase. The actual
115627 ** filtering will take place in xNext().
115629 static int fts3PhraseSelect(
115630 Fts3Cursor *pCsr, /* Virtual table cursor handle */
115631 Fts3Phrase *pPhrase, /* Phrase to return a doclist for */
115632 int isReqPos, /* True if output should contain positions */
115633 char **paOut, /* OUT: Pointer to malloc'd result buffer */
115634 int *pnOut /* OUT: Size of buffer at *paOut */
115636 char *pOut = 0;
115637 int nOut = 0;
115638 int rc = SQLITE_OK;
115639 int ii;
115640 int iCol = pPhrase->iColumn;
115641 int isTermPos = (pPhrase->nToken>1 || isReqPos);
115642 Fts3Table *p = (Fts3Table *)pCsr->base.pVtab;
115643 int isFirst = 1;
115645 int iPrevTok = 0;
115646 int nDoc = 0;
115648 /* If this is an xFilter() evaluation, create a segment-reader for each
115649 ** phrase token. Or, if this is an xNext() or snippet/offsets/matchinfo
115650 ** evaluation, only create segment-readers if there are no Fts3DeferredToken
115651 ** objects attached to the phrase-tokens.
115653 for(ii=0; ii<pPhrase->nToken; ii++){
115654 Fts3PhraseToken *pTok = &pPhrase->aToken[ii];
115655 if( pTok->pSegcsr==0 ){
115656 if( (pCsr->eEvalmode==FTS3_EVAL_FILTER)
115657 || (pCsr->eEvalmode==FTS3_EVAL_NEXT && pCsr->pDeferred==0)
115658 || (pCsr->eEvalmode==FTS3_EVAL_MATCHINFO && pTok->bFulltext)
115660 rc = fts3TermSegReaderCursor(
115661 pCsr, pTok->z, pTok->n, pTok->isPrefix, &pTok->pSegcsr
115663 if( rc!=SQLITE_OK ) return rc;
115668 for(ii=0; ii<pPhrase->nToken; ii++){
115669 Fts3PhraseToken *pTok; /* Token to find doclist for */
115670 int iTok = 0; /* The token being queried this iteration */
115671 char *pList = 0; /* Pointer to token doclist */
115672 int nList = 0; /* Size of buffer at pList */
115674 /* Select a token to process. If this is an xFilter() call, then tokens
115675 ** are processed in order from least to most costly. Otherwise, tokens
115676 ** are processed in the order in which they occur in the phrase.
115678 if( pCsr->eEvalmode==FTS3_EVAL_MATCHINFO ){
115679 assert( isReqPos );
115680 iTok = ii;
115681 pTok = &pPhrase->aToken[iTok];
115682 if( pTok->bFulltext==0 ) continue;
115683 }else if( pCsr->eEvalmode==FTS3_EVAL_NEXT || isReqPos ){
115684 iTok = ii;
115685 pTok = &pPhrase->aToken[iTok];
115686 }else{
115687 int nMinCost = 0x7FFFFFFF;
115688 int jj;
115690 /* Find the remaining token with the lowest cost. */
115691 for(jj=0; jj<pPhrase->nToken; jj++){
115692 Fts3SegReaderCursor *pSegcsr = pPhrase->aToken[jj].pSegcsr;
115693 if( pSegcsr && pSegcsr->nCost<nMinCost ){
115694 iTok = jj;
115695 nMinCost = pSegcsr->nCost;
115698 pTok = &pPhrase->aToken[iTok];
115700 /* This branch is taken if it is determined that loading the doclist
115701 ** for the next token would require more IO than loading all documents
115702 ** currently identified by doclist pOut/nOut. No further doclists will
115703 ** be loaded from the full-text index for this phrase.
115705 if( nMinCost>nDoc && ii>0 ){
115706 rc = fts3DeferExpression(pCsr, pCsr->pExpr);
115707 break;
115711 if( pCsr->eEvalmode==FTS3_EVAL_NEXT && pTok->pDeferred ){
115712 rc = fts3DeferredTermSelect(pTok->pDeferred, isTermPos, &nList, &pList);
115713 }else{
115714 if( pTok->pSegcsr ){
115715 rc = fts3TermSelect(p, pTok, iCol, isTermPos, &nList, &pList);
115717 pTok->bFulltext = 1;
115719 assert( rc!=SQLITE_OK || pCsr->eEvalmode || pTok->pSegcsr==0 );
115720 if( rc!=SQLITE_OK ) break;
115722 if( isFirst ){
115723 pOut = pList;
115724 nOut = nList;
115725 if( pCsr->eEvalmode==FTS3_EVAL_FILTER && pPhrase->nToken>1 ){
115726 nDoc = fts3DoclistCountDocids(1, pOut, nOut);
115728 isFirst = 0;
115729 iPrevTok = iTok;
115730 }else{
115731 /* Merge the new term list and the current output. */
115732 char *aLeft, *aRight;
115733 int nLeft, nRight;
115734 int nDist;
115735 int mt;
115737 /* If this is the final token of the phrase, and positions were not
115738 ** requested by the caller, use MERGE_PHRASE instead of POS_PHRASE.
115739 ** This drops the position information from the output list.
115741 mt = MERGE_POS_PHRASE;
115742 if( ii==pPhrase->nToken-1 && !isReqPos ) mt = MERGE_PHRASE;
115744 assert( iPrevTok!=iTok );
115745 if( iPrevTok<iTok ){
115746 aLeft = pOut;
115747 nLeft = nOut;
115748 aRight = pList;
115749 nRight = nList;
115750 nDist = iTok-iPrevTok;
115751 iPrevTok = iTok;
115752 }else{
115753 aRight = pOut;
115754 nRight = nOut;
115755 aLeft = pList;
115756 nLeft = nList;
115757 nDist = iPrevTok-iTok;
115759 pOut = aRight;
115760 fts3DoclistMerge(
115761 mt, nDist, 0, pOut, &nOut, aLeft, nLeft, aRight, nRight, &nDoc
115763 sqlite3_free(aLeft);
115765 assert( nOut==0 || pOut!=0 );
115768 if( rc==SQLITE_OK ){
115769 if( ii!=pPhrase->nToken ){
115770 assert( pCsr->eEvalmode==FTS3_EVAL_FILTER && isReqPos==0 );
115771 fts3DoclistStripPositions(pOut, &nOut);
115773 *paOut = pOut;
115774 *pnOut = nOut;
115775 }else{
115776 sqlite3_free(pOut);
115778 return rc;
115782 ** This function merges two doclists according to the requirements of a
115783 ** NEAR operator.
115785 ** Both input doclists must include position information. The output doclist
115786 ** includes position information if the first argument to this function
115787 ** is MERGE_POS_NEAR, or does not if it is MERGE_NEAR.
115789 static int fts3NearMerge(
115790 int mergetype, /* MERGE_POS_NEAR or MERGE_NEAR */
115791 int nNear, /* Parameter to NEAR operator */
115792 int nTokenLeft, /* Number of tokens in LHS phrase arg */
115793 char *aLeft, /* Doclist for LHS (incl. positions) */
115794 int nLeft, /* Size of LHS doclist in bytes */
115795 int nTokenRight, /* As nTokenLeft */
115796 char *aRight, /* As aLeft */
115797 int nRight, /* As nRight */
115798 char **paOut, /* OUT: Results of merge (malloced) */
115799 int *pnOut /* OUT: Sized of output buffer */
115801 char *aOut; /* Buffer to write output doclist to */
115802 int rc; /* Return code */
115804 assert( mergetype==MERGE_POS_NEAR || MERGE_NEAR );
115806 aOut = sqlite3_malloc(nLeft+nRight+1);
115807 if( aOut==0 ){
115808 rc = SQLITE_NOMEM;
115809 }else{
115810 rc = fts3DoclistMerge(mergetype, nNear+nTokenRight, nNear+nTokenLeft,
115811 aOut, pnOut, aLeft, nLeft, aRight, nRight, 0
115813 if( rc!=SQLITE_OK ){
115814 sqlite3_free(aOut);
115815 aOut = 0;
115819 *paOut = aOut;
115820 return rc;
115824 ** This function is used as part of the processing for the snippet() and
115825 ** offsets() functions.
115827 ** Both pLeft and pRight are expression nodes of type FTSQUERY_PHRASE. Both
115828 ** have their respective doclists (including position information) loaded
115829 ** in Fts3Expr.aDoclist/nDoclist. This function removes all entries from
115830 ** each doclist that are not within nNear tokens of a corresponding entry
115831 ** in the other doclist.
115833 SQLITE_PRIVATE int sqlite3Fts3ExprNearTrim(Fts3Expr *pLeft, Fts3Expr *pRight, int nNear){
115834 int rc; /* Return code */
115836 assert( pLeft->eType==FTSQUERY_PHRASE );
115837 assert( pRight->eType==FTSQUERY_PHRASE );
115838 assert( pLeft->isLoaded && pRight->isLoaded );
115840 if( pLeft->aDoclist==0 || pRight->aDoclist==0 ){
115841 sqlite3_free(pLeft->aDoclist);
115842 sqlite3_free(pRight->aDoclist);
115843 pRight->aDoclist = 0;
115844 pLeft->aDoclist = 0;
115845 rc = SQLITE_OK;
115846 }else{
115847 char *aOut; /* Buffer in which to assemble new doclist */
115848 int nOut; /* Size of buffer aOut in bytes */
115850 rc = fts3NearMerge(MERGE_POS_NEAR, nNear,
115851 pLeft->pPhrase->nToken, pLeft->aDoclist, pLeft->nDoclist,
115852 pRight->pPhrase->nToken, pRight->aDoclist, pRight->nDoclist,
115853 &aOut, &nOut
115855 if( rc!=SQLITE_OK ) return rc;
115856 sqlite3_free(pRight->aDoclist);
115857 pRight->aDoclist = aOut;
115858 pRight->nDoclist = nOut;
115860 rc = fts3NearMerge(MERGE_POS_NEAR, nNear,
115861 pRight->pPhrase->nToken, pRight->aDoclist, pRight->nDoclist,
115862 pLeft->pPhrase->nToken, pLeft->aDoclist, pLeft->nDoclist,
115863 &aOut, &nOut
115865 sqlite3_free(pLeft->aDoclist);
115866 pLeft->aDoclist = aOut;
115867 pLeft->nDoclist = nOut;
115869 return rc;
115874 ** Allocate an Fts3SegReaderArray for each token in the expression pExpr.
115875 ** The allocated objects are stored in the Fts3PhraseToken.pArray member
115876 ** variables of each token structure.
115878 static int fts3ExprAllocateSegReaders(
115879 Fts3Cursor *pCsr, /* FTS3 table */
115880 Fts3Expr *pExpr, /* Expression to create seg-readers for */
115881 int *pnExpr /* OUT: Number of AND'd expressions */
115883 int rc = SQLITE_OK; /* Return code */
115885 assert( pCsr->eEvalmode==FTS3_EVAL_FILTER );
115886 if( pnExpr && pExpr->eType!=FTSQUERY_AND ){
115887 (*pnExpr)++;
115888 pnExpr = 0;
115891 if( pExpr->eType==FTSQUERY_PHRASE ){
115892 Fts3Phrase *pPhrase = pExpr->pPhrase;
115893 int ii;
115895 for(ii=0; rc==SQLITE_OK && ii<pPhrase->nToken; ii++){
115896 Fts3PhraseToken *pTok = &pPhrase->aToken[ii];
115897 if( pTok->pSegcsr==0 ){
115898 rc = fts3TermSegReaderCursor(
115899 pCsr, pTok->z, pTok->n, pTok->isPrefix, &pTok->pSegcsr
115903 }else{
115904 rc = fts3ExprAllocateSegReaders(pCsr, pExpr->pLeft, pnExpr);
115905 if( rc==SQLITE_OK ){
115906 rc = fts3ExprAllocateSegReaders(pCsr, pExpr->pRight, pnExpr);
115909 return rc;
115913 ** Free the Fts3SegReaderArray objects associated with each token in the
115914 ** expression pExpr. In other words, this function frees the resources
115915 ** allocated by fts3ExprAllocateSegReaders().
115917 static void fts3ExprFreeSegReaders(Fts3Expr *pExpr){
115918 if( pExpr ){
115919 Fts3Phrase *pPhrase = pExpr->pPhrase;
115920 if( pPhrase ){
115921 int kk;
115922 for(kk=0; kk<pPhrase->nToken; kk++){
115923 fts3SegReaderCursorFree(pPhrase->aToken[kk].pSegcsr);
115924 pPhrase->aToken[kk].pSegcsr = 0;
115927 fts3ExprFreeSegReaders(pExpr->pLeft);
115928 fts3ExprFreeSegReaders(pExpr->pRight);
115933 ** Return the sum of the costs of all tokens in the expression pExpr. This
115934 ** function must be called after Fts3SegReaderArrays have been allocated
115935 ** for all tokens using fts3ExprAllocateSegReaders().
115937 static int fts3ExprCost(Fts3Expr *pExpr){
115938 int nCost; /* Return value */
115939 if( pExpr->eType==FTSQUERY_PHRASE ){
115940 Fts3Phrase *pPhrase = pExpr->pPhrase;
115941 int ii;
115942 nCost = 0;
115943 for(ii=0; ii<pPhrase->nToken; ii++){
115944 Fts3SegReaderCursor *pSegcsr = pPhrase->aToken[ii].pSegcsr;
115945 if( pSegcsr ) nCost += pSegcsr->nCost;
115947 }else{
115948 nCost = fts3ExprCost(pExpr->pLeft) + fts3ExprCost(pExpr->pRight);
115950 return nCost;
115954 ** The following is a helper function (and type) for fts3EvalExpr(). It
115955 ** must be called after Fts3SegReaders have been allocated for every token
115956 ** in the expression. See the context it is called from in fts3EvalExpr()
115957 ** for further explanation.
115959 typedef struct ExprAndCost ExprAndCost;
115960 struct ExprAndCost {
115961 Fts3Expr *pExpr;
115962 int nCost;
115964 static void fts3ExprAssignCosts(
115965 Fts3Expr *pExpr, /* Expression to create seg-readers for */
115966 ExprAndCost **ppExprCost /* OUT: Write to *ppExprCost */
115968 if( pExpr->eType==FTSQUERY_AND ){
115969 fts3ExprAssignCosts(pExpr->pLeft, ppExprCost);
115970 fts3ExprAssignCosts(pExpr->pRight, ppExprCost);
115971 }else{
115972 (*ppExprCost)->pExpr = pExpr;
115973 (*ppExprCost)->nCost = fts3ExprCost(pExpr);
115974 (*ppExprCost)++;
115979 ** Evaluate the full-text expression pExpr against FTS3 table pTab. Store
115980 ** the resulting doclist in *paOut and *pnOut. This routine mallocs for
115981 ** the space needed to store the output. The caller is responsible for
115982 ** freeing the space when it has finished.
115984 ** This function is called in two distinct contexts:
115986 ** * From within the virtual table xFilter() method. In this case, the
115987 ** output doclist contains entries for all rows in the table, based on
115988 ** data read from the full-text index.
115990 ** In this case, if the query expression contains one or more tokens that
115991 ** are very common, then the returned doclist may contain a superset of
115992 ** the documents that actually match the expression.
115994 ** * From within the virtual table xNext() method. This call is only made
115995 ** if the call from within xFilter() found that there were very common
115996 ** tokens in the query expression and did return a superset of the
115997 ** matching documents. In this case the returned doclist contains only
115998 ** entries that correspond to the current row of the table. Instead of
115999 ** reading the data for each token from the full-text index, the data is
116000 ** already available in-memory in the Fts3PhraseToken.pDeferred structures.
116001 ** See fts3EvalDeferred() for how it gets there.
116003 ** In the first case above, Fts3Cursor.doDeferred==0. In the second (if it is
116004 ** required) Fts3Cursor.doDeferred==1.
116006 ** If the SQLite invokes the snippet(), offsets() or matchinfo() function
116007 ** as part of a SELECT on an FTS3 table, this function is called on each
116008 ** individual phrase expression in the query. If there were very common tokens
116009 ** found in the xFilter() call, then this function is called once for phrase
116010 ** for each row visited, and the returned doclist contains entries for the
116011 ** current row only. Otherwise, if there were no very common tokens, then this
116012 ** function is called once only for each phrase in the query and the returned
116013 ** doclist contains entries for all rows of the table.
116015 ** Fts3Cursor.doDeferred==1 when this function is called on phrases as a
116016 ** result of a snippet(), offsets() or matchinfo() invocation.
116018 static int fts3EvalExpr(
116019 Fts3Cursor *p, /* Virtual table cursor handle */
116020 Fts3Expr *pExpr, /* Parsed fts3 expression */
116021 char **paOut, /* OUT: Pointer to malloc'd result buffer */
116022 int *pnOut, /* OUT: Size of buffer at *paOut */
116023 int isReqPos /* Require positions in output buffer */
116025 int rc = SQLITE_OK; /* Return code */
116027 /* Zero the output parameters. */
116028 *paOut = 0;
116029 *pnOut = 0;
116031 if( pExpr ){
116032 assert( pExpr->eType==FTSQUERY_NEAR || pExpr->eType==FTSQUERY_OR
116033 || pExpr->eType==FTSQUERY_AND || pExpr->eType==FTSQUERY_NOT
116034 || pExpr->eType==FTSQUERY_PHRASE
116036 assert( pExpr->eType==FTSQUERY_PHRASE || isReqPos==0 );
116038 if( pExpr->eType==FTSQUERY_PHRASE ){
116039 rc = fts3PhraseSelect(p, pExpr->pPhrase,
116040 isReqPos || (pExpr->pParent && pExpr->pParent->eType==FTSQUERY_NEAR),
116041 paOut, pnOut
116043 fts3ExprFreeSegReaders(pExpr);
116044 }else if( p->eEvalmode==FTS3_EVAL_FILTER && pExpr->eType==FTSQUERY_AND ){
116045 ExprAndCost *aExpr = 0; /* Array of AND'd expressions and costs */
116046 int nExpr = 0; /* Size of aExpr[] */
116047 char *aRet = 0; /* Doclist to return to caller */
116048 int nRet = 0; /* Length of aRet[] in bytes */
116049 int nDoc = 0x7FFFFFFF;
116051 assert( !isReqPos );
116053 rc = fts3ExprAllocateSegReaders(p, pExpr, &nExpr);
116054 if( rc==SQLITE_OK ){
116055 assert( nExpr>1 );
116056 aExpr = sqlite3_malloc(sizeof(ExprAndCost) * nExpr);
116057 if( !aExpr ) rc = SQLITE_NOMEM;
116059 if( rc==SQLITE_OK ){
116060 int ii; /* Used to iterate through expressions */
116062 fts3ExprAssignCosts(pExpr, &aExpr);
116063 aExpr -= nExpr;
116064 for(ii=0; ii<nExpr; ii++){
116065 char *aNew;
116066 int nNew;
116067 int jj;
116068 ExprAndCost *pBest = 0;
116070 for(jj=0; jj<nExpr; jj++){
116071 ExprAndCost *pCand = &aExpr[jj];
116072 if( pCand->pExpr && (pBest==0 || pCand->nCost<pBest->nCost) ){
116073 pBest = pCand;
116077 if( pBest->nCost>nDoc ){
116078 rc = fts3DeferExpression(p, p->pExpr);
116079 break;
116080 }else{
116081 rc = fts3EvalExpr(p, pBest->pExpr, &aNew, &nNew, 0);
116082 if( rc!=SQLITE_OK ) break;
116083 pBest->pExpr = 0;
116084 if( ii==0 ){
116085 aRet = aNew;
116086 nRet = nNew;
116087 nDoc = fts3DoclistCountDocids(0, aRet, nRet);
116088 }else{
116089 fts3DoclistMerge(
116090 MERGE_AND, 0, 0, aRet, &nRet, aRet, nRet, aNew, nNew, &nDoc
116092 sqlite3_free(aNew);
116098 if( rc==SQLITE_OK ){
116099 *paOut = aRet;
116100 *pnOut = nRet;
116101 }else{
116102 assert( *paOut==0 );
116103 sqlite3_free(aRet);
116105 sqlite3_free(aExpr);
116106 fts3ExprFreeSegReaders(pExpr);
116108 }else{
116109 char *aLeft;
116110 char *aRight;
116111 int nLeft;
116112 int nRight;
116114 assert( pExpr->eType==FTSQUERY_NEAR
116115 || pExpr->eType==FTSQUERY_OR
116116 || pExpr->eType==FTSQUERY_NOT
116117 || (pExpr->eType==FTSQUERY_AND && p->eEvalmode==FTS3_EVAL_NEXT)
116120 if( 0==(rc = fts3EvalExpr(p, pExpr->pRight, &aRight, &nRight, isReqPos))
116121 && 0==(rc = fts3EvalExpr(p, pExpr->pLeft, &aLeft, &nLeft, isReqPos))
116123 switch( pExpr->eType ){
116124 case FTSQUERY_NEAR: {
116125 Fts3Expr *pLeft;
116126 Fts3Expr *pRight;
116127 int mergetype = MERGE_NEAR;
116128 if( pExpr->pParent && pExpr->pParent->eType==FTSQUERY_NEAR ){
116129 mergetype = MERGE_POS_NEAR;
116131 pLeft = pExpr->pLeft;
116132 while( pLeft->eType==FTSQUERY_NEAR ){
116133 pLeft=pLeft->pRight;
116135 pRight = pExpr->pRight;
116136 assert( pRight->eType==FTSQUERY_PHRASE );
116137 assert( pLeft->eType==FTSQUERY_PHRASE );
116139 rc = fts3NearMerge(mergetype, pExpr->nNear,
116140 pLeft->pPhrase->nToken, aLeft, nLeft,
116141 pRight->pPhrase->nToken, aRight, nRight,
116142 paOut, pnOut
116144 sqlite3_free(aLeft);
116145 break;
116148 case FTSQUERY_OR: {
116149 /* Allocate a buffer for the output. The maximum size is the
116150 ** sum of the sizes of the two input buffers. The +1 term is
116151 ** so that a buffer of zero bytes is never allocated - this can
116152 ** cause fts3DoclistMerge() to incorrectly return SQLITE_NOMEM.
116154 char *aBuffer = sqlite3_malloc(nRight+nLeft+1);
116155 rc = fts3DoclistMerge(MERGE_OR, 0, 0, aBuffer, pnOut,
116156 aLeft, nLeft, aRight, nRight, 0
116158 *paOut = aBuffer;
116159 sqlite3_free(aLeft);
116160 break;
116163 default: {
116164 assert( FTSQUERY_NOT==MERGE_NOT && FTSQUERY_AND==MERGE_AND );
116165 fts3DoclistMerge(pExpr->eType, 0, 0, aLeft, pnOut,
116166 aLeft, nLeft, aRight, nRight, 0
116168 *paOut = aLeft;
116169 break;
116173 sqlite3_free(aRight);
116177 assert( rc==SQLITE_OK || *paOut==0 );
116178 return rc;
116182 ** This function is called from within xNext() for each row visited by
116183 ** an FTS3 query. If evaluating the FTS3 query expression within xFilter()
116184 ** was able to determine the exact set of matching rows, this function sets
116185 ** *pbRes to true and returns SQLITE_IO immediately.
116187 ** Otherwise, if evaluating the query expression within xFilter() returned a
116188 ** superset of the matching documents instead of an exact set (this happens
116189 ** when the query includes very common tokens and it is deemed too expensive to
116190 ** load their doclists from disk), this function tests if the current row
116191 ** really does match the FTS3 query.
116193 ** If an error occurs, an SQLite error code is returned. Otherwise, SQLITE_OK
116194 ** is returned and *pbRes is set to true if the current row matches the
116195 ** FTS3 query (and should be included in the results returned to SQLite), or
116196 ** false otherwise.
116198 static int fts3EvalDeferred(
116199 Fts3Cursor *pCsr, /* FTS3 cursor pointing at row to test */
116200 int *pbRes /* OUT: Set to true if row is a match */
116202 int rc = SQLITE_OK;
116203 if( pCsr->pDeferred==0 ){
116204 *pbRes = 1;
116205 }else{
116206 rc = fts3CursorSeek(0, pCsr);
116207 if( rc==SQLITE_OK ){
116208 sqlite3Fts3FreeDeferredDoclists(pCsr);
116209 rc = sqlite3Fts3CacheDeferredDoclists(pCsr);
116211 if( rc==SQLITE_OK ){
116212 char *a = 0;
116213 int n = 0;
116214 rc = fts3EvalExpr(pCsr, pCsr->pExpr, &a, &n, 0);
116215 assert( n>=0 );
116216 *pbRes = (n>0);
116217 sqlite3_free(a);
116220 return rc;
116224 ** Advance the cursor to the next row in the %_content table that
116225 ** matches the search criteria. For a MATCH search, this will be
116226 ** the next row that matches. For a full-table scan, this will be
116227 ** simply the next row in the %_content table. For a docid lookup,
116228 ** this routine simply sets the EOF flag.
116230 ** Return SQLITE_OK if nothing goes wrong. SQLITE_OK is returned
116231 ** even if we reach end-of-file. The fts3EofMethod() will be called
116232 ** subsequently to determine whether or not an EOF was hit.
116234 static int fts3NextMethod(sqlite3_vtab_cursor *pCursor){
116235 int res;
116236 int rc = SQLITE_OK; /* Return code */
116237 Fts3Cursor *pCsr = (Fts3Cursor *)pCursor;
116239 pCsr->eEvalmode = FTS3_EVAL_NEXT;
116241 if( pCsr->aDoclist==0 ){
116242 if( SQLITE_ROW!=sqlite3_step(pCsr->pStmt) ){
116243 pCsr->isEof = 1;
116244 rc = sqlite3_reset(pCsr->pStmt);
116245 break;
116247 pCsr->iPrevId = sqlite3_column_int64(pCsr->pStmt, 0);
116248 }else{
116249 if( pCsr->pNextId>=&pCsr->aDoclist[pCsr->nDoclist] ){
116250 pCsr->isEof = 1;
116251 break;
116253 sqlite3_reset(pCsr->pStmt);
116254 fts3GetDeltaVarint(&pCsr->pNextId, &pCsr->iPrevId);
116255 pCsr->isRequireSeek = 1;
116256 pCsr->isMatchinfoNeeded = 1;
116258 }while( SQLITE_OK==(rc = fts3EvalDeferred(pCsr, &res)) && res==0 );
116260 return rc;
116264 ** This is the xFilter interface for the virtual table. See
116265 ** the virtual table xFilter method documentation for additional
116266 ** information.
116268 ** If idxNum==FTS3_FULLSCAN_SEARCH then do a full table scan against
116269 ** the %_content table.
116271 ** If idxNum==FTS3_DOCID_SEARCH then do a docid lookup for a single entry
116272 ** in the %_content table.
116274 ** If idxNum>=FTS3_FULLTEXT_SEARCH then use the full text index. The
116275 ** column on the left-hand side of the MATCH operator is column
116276 ** number idxNum-FTS3_FULLTEXT_SEARCH, 0 indexed. argv[0] is the right-hand
116277 ** side of the MATCH operator.
116279 static int fts3FilterMethod(
116280 sqlite3_vtab_cursor *pCursor, /* The cursor used for this query */
116281 int idxNum, /* Strategy index */
116282 const char *idxStr, /* Unused */
116283 int nVal, /* Number of elements in apVal */
116284 sqlite3_value **apVal /* Arguments for the indexing scheme */
116286 const char *azSql[] = {
116287 "SELECT %s FROM %Q.'%q_content' AS x WHERE docid = ?", /* non-full-scan */
116288 "SELECT %s FROM %Q.'%q_content' AS x ", /* full-scan */
116290 int rc; /* Return code */
116291 char *zSql; /* SQL statement used to access %_content */
116292 Fts3Table *p = (Fts3Table *)pCursor->pVtab;
116293 Fts3Cursor *pCsr = (Fts3Cursor *)pCursor;
116295 UNUSED_PARAMETER(idxStr);
116296 UNUSED_PARAMETER(nVal);
116298 assert( idxNum>=0 && idxNum<=(FTS3_FULLTEXT_SEARCH+p->nColumn) );
116299 assert( nVal==0 || nVal==1 );
116300 assert( (nVal==0)==(idxNum==FTS3_FULLSCAN_SEARCH) );
116301 assert( p->pSegments==0 );
116303 /* In case the cursor has been used before, clear it now. */
116304 sqlite3_finalize(pCsr->pStmt);
116305 sqlite3_free(pCsr->aDoclist);
116306 sqlite3Fts3ExprFree(pCsr->pExpr);
116307 memset(&pCursor[1], 0, sizeof(Fts3Cursor)-sizeof(sqlite3_vtab_cursor));
116309 if( idxNum!=FTS3_DOCID_SEARCH && idxNum!=FTS3_FULLSCAN_SEARCH ){
116310 int iCol = idxNum-FTS3_FULLTEXT_SEARCH;
116311 const char *zQuery = (const char *)sqlite3_value_text(apVal[0]);
116313 if( zQuery==0 && sqlite3_value_type(apVal[0])!=SQLITE_NULL ){
116314 return SQLITE_NOMEM;
116317 rc = sqlite3Fts3ExprParse(p->pTokenizer, p->azColumn, p->nColumn,
116318 iCol, zQuery, -1, &pCsr->pExpr
116320 if( rc!=SQLITE_OK ){
116321 if( rc==SQLITE_ERROR ){
116322 p->base.zErrMsg = sqlite3_mprintf("malformed MATCH expression: [%s]",
116323 zQuery);
116325 return rc;
116328 rc = sqlite3Fts3ReadLock(p);
116329 if( rc!=SQLITE_OK ) return rc;
116331 rc = fts3EvalExpr(pCsr, pCsr->pExpr, &pCsr->aDoclist, &pCsr->nDoclist, 0);
116332 sqlite3Fts3SegmentsClose(p);
116333 if( rc!=SQLITE_OK ) return rc;
116334 pCsr->pNextId = pCsr->aDoclist;
116335 pCsr->iPrevId = 0;
116338 /* Compile a SELECT statement for this cursor. For a full-table-scan, the
116339 ** statement loops through all rows of the %_content table. For a
116340 ** full-text query or docid lookup, the statement retrieves a single
116341 ** row by docid.
116343 zSql = (char *)azSql[idxNum==FTS3_FULLSCAN_SEARCH];
116344 zSql = sqlite3_mprintf(zSql, p->zReadExprlist, p->zDb, p->zName);
116345 if( !zSql ){
116346 rc = SQLITE_NOMEM;
116347 }else{
116348 rc = sqlite3_prepare_v2(p->db, zSql, -1, &pCsr->pStmt, 0);
116349 sqlite3_free(zSql);
116351 if( rc==SQLITE_OK && idxNum==FTS3_DOCID_SEARCH ){
116352 rc = sqlite3_bind_value(pCsr->pStmt, 1, apVal[0]);
116354 pCsr->eSearch = (i16)idxNum;
116356 if( rc!=SQLITE_OK ) return rc;
116357 return fts3NextMethod(pCursor);
116361 ** This is the xEof method of the virtual table. SQLite calls this
116362 ** routine to find out if it has reached the end of a result set.
116364 static int fts3EofMethod(sqlite3_vtab_cursor *pCursor){
116365 return ((Fts3Cursor *)pCursor)->isEof;
116369 ** This is the xRowid method. The SQLite core calls this routine to
116370 ** retrieve the rowid for the current row of the result set. fts3
116371 ** exposes %_content.docid as the rowid for the virtual table. The
116372 ** rowid should be written to *pRowid.
116374 static int fts3RowidMethod(sqlite3_vtab_cursor *pCursor, sqlite_int64 *pRowid){
116375 Fts3Cursor *pCsr = (Fts3Cursor *) pCursor;
116376 if( pCsr->aDoclist ){
116377 *pRowid = pCsr->iPrevId;
116378 }else{
116379 /* This branch runs if the query is implemented using a full-table scan
116380 ** (not using the full-text index). In this case grab the rowid from the
116381 ** SELECT statement.
116383 assert( pCsr->isRequireSeek==0 );
116384 *pRowid = sqlite3_column_int64(pCsr->pStmt, 0);
116386 return SQLITE_OK;
116390 ** This is the xColumn method, called by SQLite to request a value from
116391 ** the row that the supplied cursor currently points to.
116393 static int fts3ColumnMethod(
116394 sqlite3_vtab_cursor *pCursor, /* Cursor to retrieve value from */
116395 sqlite3_context *pContext, /* Context for sqlite3_result_xxx() calls */
116396 int iCol /* Index of column to read value from */
116398 int rc; /* Return Code */
116399 Fts3Cursor *pCsr = (Fts3Cursor *) pCursor;
116400 Fts3Table *p = (Fts3Table *)pCursor->pVtab;
116402 /* The column value supplied by SQLite must be in range. */
116403 assert( iCol>=0 && iCol<=p->nColumn+1 );
116405 if( iCol==p->nColumn+1 ){
116406 /* This call is a request for the "docid" column. Since "docid" is an
116407 ** alias for "rowid", use the xRowid() method to obtain the value.
116409 sqlite3_int64 iRowid;
116410 rc = fts3RowidMethod(pCursor, &iRowid);
116411 sqlite3_result_int64(pContext, iRowid);
116412 }else if( iCol==p->nColumn ){
116413 /* The extra column whose name is the same as the table.
116414 ** Return a blob which is a pointer to the cursor.
116416 sqlite3_result_blob(pContext, &pCsr, sizeof(pCsr), SQLITE_TRANSIENT);
116417 rc = SQLITE_OK;
116418 }else{
116419 rc = fts3CursorSeek(0, pCsr);
116420 if( rc==SQLITE_OK ){
116421 sqlite3_result_value(pContext, sqlite3_column_value(pCsr->pStmt, iCol+1));
116424 return rc;
116428 ** This function is the implementation of the xUpdate callback used by
116429 ** FTS3 virtual tables. It is invoked by SQLite each time a row is to be
116430 ** inserted, updated or deleted.
116432 static int fts3UpdateMethod(
116433 sqlite3_vtab *pVtab, /* Virtual table handle */
116434 int nArg, /* Size of argument array */
116435 sqlite3_value **apVal, /* Array of arguments */
116436 sqlite_int64 *pRowid /* OUT: The affected (or effected) rowid */
116438 return sqlite3Fts3UpdateMethod(pVtab, nArg, apVal, pRowid);
116442 ** Implementation of xSync() method. Flush the contents of the pending-terms
116443 ** hash-table to the database.
116445 static int fts3SyncMethod(sqlite3_vtab *pVtab){
116446 int rc = sqlite3Fts3PendingTermsFlush((Fts3Table *)pVtab);
116447 sqlite3Fts3SegmentsClose((Fts3Table *)pVtab);
116448 return rc;
116452 ** Implementation of xBegin() method. This is a no-op.
116454 static int fts3BeginMethod(sqlite3_vtab *pVtab){
116455 UNUSED_PARAMETER(pVtab);
116456 assert( ((Fts3Table *)pVtab)->nPendingData==0 );
116457 return SQLITE_OK;
116461 ** Implementation of xCommit() method. This is a no-op. The contents of
116462 ** the pending-terms hash-table have already been flushed into the database
116463 ** by fts3SyncMethod().
116465 static int fts3CommitMethod(sqlite3_vtab *pVtab){
116466 UNUSED_PARAMETER(pVtab);
116467 assert( ((Fts3Table *)pVtab)->nPendingData==0 );
116468 return SQLITE_OK;
116472 ** Implementation of xRollback(). Discard the contents of the pending-terms
116473 ** hash-table. Any changes made to the database are reverted by SQLite.
116475 static int fts3RollbackMethod(sqlite3_vtab *pVtab){
116476 sqlite3Fts3PendingTermsClear((Fts3Table *)pVtab);
116477 return SQLITE_OK;
116481 ** Load the doclist associated with expression pExpr to pExpr->aDoclist.
116482 ** The loaded doclist contains positions as well as the document ids.
116483 ** This is used by the matchinfo(), snippet() and offsets() auxillary
116484 ** functions.
116486 SQLITE_PRIVATE int sqlite3Fts3ExprLoadDoclist(Fts3Cursor *pCsr, Fts3Expr *pExpr){
116487 int rc;
116488 assert( pExpr->eType==FTSQUERY_PHRASE && pExpr->pPhrase );
116489 assert( pCsr->eEvalmode==FTS3_EVAL_NEXT );
116490 rc = fts3EvalExpr(pCsr, pExpr, &pExpr->aDoclist, &pExpr->nDoclist, 1);
116491 return rc;
116494 SQLITE_PRIVATE int sqlite3Fts3ExprLoadFtDoclist(
116495 Fts3Cursor *pCsr,
116496 Fts3Expr *pExpr,
116497 char **paDoclist,
116498 int *pnDoclist
116500 int rc;
116501 assert( pCsr->eEvalmode==FTS3_EVAL_NEXT );
116502 assert( pExpr->eType==FTSQUERY_PHRASE && pExpr->pPhrase );
116503 pCsr->eEvalmode = FTS3_EVAL_MATCHINFO;
116504 rc = fts3EvalExpr(pCsr, pExpr, paDoclist, pnDoclist, 1);
116505 pCsr->eEvalmode = FTS3_EVAL_NEXT;
116506 return rc;
116510 ** After ExprLoadDoclist() (see above) has been called, this function is
116511 ** used to iterate/search through the position lists that make up the doclist
116512 ** stored in pExpr->aDoclist.
116514 SQLITE_PRIVATE char *sqlite3Fts3FindPositions(
116515 Fts3Expr *pExpr, /* Access this expressions doclist */
116516 sqlite3_int64 iDocid, /* Docid associated with requested pos-list */
116517 int iCol /* Column of requested pos-list */
116519 assert( pExpr->isLoaded );
116520 if( pExpr->aDoclist ){
116521 char *pEnd = &pExpr->aDoclist[pExpr->nDoclist];
116522 char *pCsr;
116524 if( pExpr->pCurrent==0 ){
116525 pExpr->pCurrent = pExpr->aDoclist;
116526 pExpr->iCurrent = 0;
116527 pExpr->pCurrent += sqlite3Fts3GetVarint(pExpr->pCurrent,&pExpr->iCurrent);
116529 pCsr = pExpr->pCurrent;
116530 assert( pCsr );
116532 while( pCsr<pEnd ){
116533 if( pExpr->iCurrent<iDocid ){
116534 fts3PoslistCopy(0, &pCsr);
116535 if( pCsr<pEnd ){
116536 fts3GetDeltaVarint(&pCsr, &pExpr->iCurrent);
116538 pExpr->pCurrent = pCsr;
116539 }else{
116540 if( pExpr->iCurrent==iDocid ){
116541 int iThis = 0;
116542 if( iCol<0 ){
116543 /* If iCol is negative, return a pointer to the start of the
116544 ** position-list (instead of a pointer to the start of a list
116545 ** of offsets associated with a specific column).
116547 return pCsr;
116549 while( iThis<iCol ){
116550 fts3ColumnlistCopy(0, &pCsr);
116551 if( *pCsr==0x00 ) return 0;
116552 pCsr++;
116553 pCsr += sqlite3Fts3GetVarint32(pCsr, &iThis);
116555 if( iCol==iThis && (*pCsr&0xFE) ) return pCsr;
116557 return 0;
116562 return 0;
116566 ** Helper function used by the implementation of the overloaded snippet(),
116567 ** offsets() and optimize() SQL functions.
116569 ** If the value passed as the third argument is a blob of size
116570 ** sizeof(Fts3Cursor*), then the blob contents are copied to the
116571 ** output variable *ppCsr and SQLITE_OK is returned. Otherwise, an error
116572 ** message is written to context pContext and SQLITE_ERROR returned. The
116573 ** string passed via zFunc is used as part of the error message.
116575 static int fts3FunctionArg(
116576 sqlite3_context *pContext, /* SQL function call context */
116577 const char *zFunc, /* Function name */
116578 sqlite3_value *pVal, /* argv[0] passed to function */
116579 Fts3Cursor **ppCsr /* OUT: Store cursor handle here */
116581 Fts3Cursor *pRet;
116582 if( sqlite3_value_type(pVal)!=SQLITE_BLOB
116583 || sqlite3_value_bytes(pVal)!=sizeof(Fts3Cursor *)
116585 char *zErr = sqlite3_mprintf("illegal first argument to %s", zFunc);
116586 sqlite3_result_error(pContext, zErr, -1);
116587 sqlite3_free(zErr);
116588 return SQLITE_ERROR;
116590 memcpy(&pRet, sqlite3_value_blob(pVal), sizeof(Fts3Cursor *));
116591 *ppCsr = pRet;
116592 return SQLITE_OK;
116596 ** Implementation of the snippet() function for FTS3
116598 static void fts3SnippetFunc(
116599 sqlite3_context *pContext, /* SQLite function call context */
116600 int nVal, /* Size of apVal[] array */
116601 sqlite3_value **apVal /* Array of arguments */
116603 Fts3Cursor *pCsr; /* Cursor handle passed through apVal[0] */
116604 const char *zStart = "<b>";
116605 const char *zEnd = "</b>";
116606 const char *zEllipsis = "<b>...</b>";
116607 int iCol = -1;
116608 int nToken = 15; /* Default number of tokens in snippet */
116610 /* There must be at least one argument passed to this function (otherwise
116611 ** the non-overloaded version would have been called instead of this one).
116613 assert( nVal>=1 );
116615 if( nVal>6 ){
116616 sqlite3_result_error(pContext,
116617 "wrong number of arguments to function snippet()", -1);
116618 return;
116620 if( fts3FunctionArg(pContext, "snippet", apVal[0], &pCsr) ) return;
116622 switch( nVal ){
116623 case 6: nToken = sqlite3_value_int(apVal[5]);
116624 case 5: iCol = sqlite3_value_int(apVal[4]);
116625 case 4: zEllipsis = (const char*)sqlite3_value_text(apVal[3]);
116626 case 3: zEnd = (const char*)sqlite3_value_text(apVal[2]);
116627 case 2: zStart = (const char*)sqlite3_value_text(apVal[1]);
116629 if( !zEllipsis || !zEnd || !zStart ){
116630 sqlite3_result_error_nomem(pContext);
116631 }else if( SQLITE_OK==fts3CursorSeek(pContext, pCsr) ){
116632 sqlite3Fts3Snippet(pContext, pCsr, zStart, zEnd, zEllipsis, iCol, nToken);
116637 ** Implementation of the offsets() function for FTS3
116639 static void fts3OffsetsFunc(
116640 sqlite3_context *pContext, /* SQLite function call context */
116641 int nVal, /* Size of argument array */
116642 sqlite3_value **apVal /* Array of arguments */
116644 Fts3Cursor *pCsr; /* Cursor handle passed through apVal[0] */
116646 UNUSED_PARAMETER(nVal);
116648 assert( nVal==1 );
116649 if( fts3FunctionArg(pContext, "offsets", apVal[0], &pCsr) ) return;
116650 assert( pCsr );
116651 if( SQLITE_OK==fts3CursorSeek(pContext, pCsr) ){
116652 sqlite3Fts3Offsets(pContext, pCsr);
116657 ** Implementation of the special optimize() function for FTS3. This
116658 ** function merges all segments in the database to a single segment.
116659 ** Example usage is:
116661 ** SELECT optimize(t) FROM t LIMIT 1;
116663 ** where 't' is the name of an FTS3 table.
116665 static void fts3OptimizeFunc(
116666 sqlite3_context *pContext, /* SQLite function call context */
116667 int nVal, /* Size of argument array */
116668 sqlite3_value **apVal /* Array of arguments */
116670 int rc; /* Return code */
116671 Fts3Table *p; /* Virtual table handle */
116672 Fts3Cursor *pCursor; /* Cursor handle passed through apVal[0] */
116674 UNUSED_PARAMETER(nVal);
116676 assert( nVal==1 );
116677 if( fts3FunctionArg(pContext, "optimize", apVal[0], &pCursor) ) return;
116678 p = (Fts3Table *)pCursor->base.pVtab;
116679 assert( p );
116681 rc = sqlite3Fts3Optimize(p);
116683 switch( rc ){
116684 case SQLITE_OK:
116685 sqlite3_result_text(pContext, "Index optimized", -1, SQLITE_STATIC);
116686 break;
116687 case SQLITE_DONE:
116688 sqlite3_result_text(pContext, "Index already optimal", -1, SQLITE_STATIC);
116689 break;
116690 default:
116691 sqlite3_result_error_code(pContext, rc);
116692 break;
116697 ** Implementation of the matchinfo() function for FTS3
116699 static void fts3MatchinfoFunc(
116700 sqlite3_context *pContext, /* SQLite function call context */
116701 int nVal, /* Size of argument array */
116702 sqlite3_value **apVal /* Array of arguments */
116704 Fts3Cursor *pCsr; /* Cursor handle passed through apVal[0] */
116705 assert( nVal==1 || nVal==2 );
116706 if( SQLITE_OK==fts3FunctionArg(pContext, "matchinfo", apVal[0], &pCsr) ){
116707 const char *zArg = 0;
116708 if( nVal>1 ){
116709 zArg = (const char *)sqlite3_value_text(apVal[1]);
116711 sqlite3Fts3Matchinfo(pContext, pCsr, zArg);
116716 ** This routine implements the xFindFunction method for the FTS3
116717 ** virtual table.
116719 static int fts3FindFunctionMethod(
116720 sqlite3_vtab *pVtab, /* Virtual table handle */
116721 int nArg, /* Number of SQL function arguments */
116722 const char *zName, /* Name of SQL function */
116723 void (**pxFunc)(sqlite3_context*,int,sqlite3_value**), /* OUT: Result */
116724 void **ppArg /* Unused */
116726 struct Overloaded {
116727 const char *zName;
116728 void (*xFunc)(sqlite3_context*,int,sqlite3_value**);
116729 } aOverload[] = {
116730 { "snippet", fts3SnippetFunc },
116731 { "offsets", fts3OffsetsFunc },
116732 { "optimize", fts3OptimizeFunc },
116733 { "matchinfo", fts3MatchinfoFunc },
116735 int i; /* Iterator variable */
116737 UNUSED_PARAMETER(pVtab);
116738 UNUSED_PARAMETER(nArg);
116739 UNUSED_PARAMETER(ppArg);
116741 for(i=0; i<SizeofArray(aOverload); i++){
116742 if( strcmp(zName, aOverload[i].zName)==0 ){
116743 *pxFunc = aOverload[i].xFunc;
116744 return 1;
116748 /* No function of the specified name was found. Return 0. */
116749 return 0;
116753 ** Implementation of FTS3 xRename method. Rename an fts3 table.
116755 static int fts3RenameMethod(
116756 sqlite3_vtab *pVtab, /* Virtual table handle */
116757 const char *zName /* New name of table */
116759 Fts3Table *p = (Fts3Table *)pVtab;
116760 sqlite3 *db = p->db; /* Database connection */
116761 int rc; /* Return Code */
116763 rc = sqlite3Fts3PendingTermsFlush(p);
116764 if( rc!=SQLITE_OK ){
116765 return rc;
116768 fts3DbExec(&rc, db,
116769 "ALTER TABLE %Q.'%q_content' RENAME TO '%q_content';",
116770 p->zDb, p->zName, zName
116772 if( p->bHasDocsize ){
116773 fts3DbExec(&rc, db,
116774 "ALTER TABLE %Q.'%q_docsize' RENAME TO '%q_docsize';",
116775 p->zDb, p->zName, zName
116778 if( p->bHasStat ){
116779 fts3DbExec(&rc, db,
116780 "ALTER TABLE %Q.'%q_stat' RENAME TO '%q_stat';",
116781 p->zDb, p->zName, zName
116784 fts3DbExec(&rc, db,
116785 "ALTER TABLE %Q.'%q_segments' RENAME TO '%q_segments';",
116786 p->zDb, p->zName, zName
116788 fts3DbExec(&rc, db,
116789 "ALTER TABLE %Q.'%q_segdir' RENAME TO '%q_segdir';",
116790 p->zDb, p->zName, zName
116792 return rc;
116795 static const sqlite3_module fts3Module = {
116796 /* iVersion */ 0,
116797 /* xCreate */ fts3CreateMethod,
116798 /* xConnect */ fts3ConnectMethod,
116799 /* xBestIndex */ fts3BestIndexMethod,
116800 /* xDisconnect */ fts3DisconnectMethod,
116801 /* xDestroy */ fts3DestroyMethod,
116802 /* xOpen */ fts3OpenMethod,
116803 /* xClose */ fts3CloseMethod,
116804 /* xFilter */ fts3FilterMethod,
116805 /* xNext */ fts3NextMethod,
116806 /* xEof */ fts3EofMethod,
116807 /* xColumn */ fts3ColumnMethod,
116808 /* xRowid */ fts3RowidMethod,
116809 /* xUpdate */ fts3UpdateMethod,
116810 /* xBegin */ fts3BeginMethod,
116811 /* xSync */ fts3SyncMethod,
116812 /* xCommit */ fts3CommitMethod,
116813 /* xRollback */ fts3RollbackMethod,
116814 /* xFindFunction */ fts3FindFunctionMethod,
116815 /* xRename */ fts3RenameMethod,
116819 ** This function is registered as the module destructor (called when an
116820 ** FTS3 enabled database connection is closed). It frees the memory
116821 ** allocated for the tokenizer hash table.
116823 static void hashDestroy(void *p){
116824 Fts3Hash *pHash = (Fts3Hash *)p;
116825 sqlite3Fts3HashClear(pHash);
116826 sqlite3_free(pHash);
116830 ** The fts3 built-in tokenizers - "simple", "porter" and "icu"- are
116831 ** implemented in files fts3_tokenizer1.c, fts3_porter.c and fts3_icu.c
116832 ** respectively. The following three forward declarations are for functions
116833 ** declared in these files used to retrieve the respective implementations.
116835 ** Calling sqlite3Fts3SimpleTokenizerModule() sets the value pointed
116836 ** to by the argument to point to the "simple" tokenizer implementation.
116837 ** And so on.
116839 SQLITE_PRIVATE void sqlite3Fts3SimpleTokenizerModule(sqlite3_tokenizer_module const**ppModule);
116840 SQLITE_PRIVATE void sqlite3Fts3PorterTokenizerModule(sqlite3_tokenizer_module const**ppModule);
116841 #ifdef SQLITE_ENABLE_ICU
116842 SQLITE_PRIVATE void sqlite3Fts3IcuTokenizerModule(sqlite3_tokenizer_module const**ppModule);
116843 #endif
116846 ** Initialise the fts3 extension. If this extension is built as part
116847 ** of the sqlite library, then this function is called directly by
116848 ** SQLite. If fts3 is built as a dynamically loadable extension, this
116849 ** function is called by the sqlite3_extension_init() entry point.
116851 SQLITE_PRIVATE int sqlite3Fts3Init(sqlite3 *db){
116852 int rc = SQLITE_OK;
116853 Fts3Hash *pHash = 0;
116854 const sqlite3_tokenizer_module *pSimple = 0;
116855 const sqlite3_tokenizer_module *pPorter = 0;
116857 #ifdef SQLITE_ENABLE_ICU
116858 const sqlite3_tokenizer_module *pIcu = 0;
116859 sqlite3Fts3IcuTokenizerModule(&pIcu);
116860 #endif
116862 rc = sqlite3Fts3InitAux(db);
116863 if( rc!=SQLITE_OK ) return rc;
116865 sqlite3Fts3SimpleTokenizerModule(&pSimple);
116866 sqlite3Fts3PorterTokenizerModule(&pPorter);
116868 /* Allocate and initialise the hash-table used to store tokenizers. */
116869 pHash = sqlite3_malloc(sizeof(Fts3Hash));
116870 if( !pHash ){
116871 rc = SQLITE_NOMEM;
116872 }else{
116873 sqlite3Fts3HashInit(pHash, FTS3_HASH_STRING, 1);
116876 /* Load the built-in tokenizers into the hash table */
116877 if( rc==SQLITE_OK ){
116878 if( sqlite3Fts3HashInsert(pHash, "simple", 7, (void *)pSimple)
116879 || sqlite3Fts3HashInsert(pHash, "porter", 7, (void *)pPorter)
116880 #ifdef SQLITE_ENABLE_ICU
116881 || (pIcu && sqlite3Fts3HashInsert(pHash, "icu", 4, (void *)pIcu))
116882 #endif
116884 rc = SQLITE_NOMEM;
116888 #ifdef SQLITE_TEST
116889 if( rc==SQLITE_OK ){
116890 rc = sqlite3Fts3ExprInitTestInterface(db);
116892 #endif
116894 /* Create the virtual table wrapper around the hash-table and overload
116895 ** the two scalar functions. If this is successful, register the
116896 ** module with sqlite.
116898 if( SQLITE_OK==rc
116899 #if CHROMIUM_FTS3_CHANGES && !SQLITE_TEST
116900 /* fts3_tokenizer() disabled for security reasons. */
116901 #else
116902 && SQLITE_OK==(rc = sqlite3Fts3InitHashTable(db, pHash, "fts3_tokenizer"))
116903 #endif
116904 && SQLITE_OK==(rc = sqlite3_overload_function(db, "snippet", -1))
116905 && SQLITE_OK==(rc = sqlite3_overload_function(db, "offsets", 1))
116906 && SQLITE_OK==(rc = sqlite3_overload_function(db, "matchinfo", 1))
116907 && SQLITE_OK==(rc = sqlite3_overload_function(db, "matchinfo", 2))
116908 && SQLITE_OK==(rc = sqlite3_overload_function(db, "optimize", 1))
116910 rc = sqlite3_create_module_v2(
116911 db, "fts3", &fts3Module, (void *)pHash, hashDestroy
116913 #if CHROMIUM_FTS3_CHANGES && !SQLITE_TEST
116914 /* Disable fts4 pending review. */
116915 #else
116916 if( rc==SQLITE_OK ){
116917 rc = sqlite3_create_module_v2(
116918 db, "fts4", &fts3Module, (void *)pHash, 0
116921 #endif
116922 return rc;
116925 /* An error has occurred. Delete the hash table and return the error code. */
116926 assert( rc!=SQLITE_OK );
116927 if( pHash ){
116928 sqlite3Fts3HashClear(pHash);
116929 sqlite3_free(pHash);
116931 return rc;
116934 #if !SQLITE_CORE
116935 SQLITE_API int sqlite3_extension_init(
116936 sqlite3 *db,
116937 char **pzErrMsg,
116938 const sqlite3_api_routines *pApi
116940 SQLITE_EXTENSION_INIT2(pApi)
116941 return sqlite3Fts3Init(db);
116943 #endif
116945 #endif
116947 /************** End of fts3.c ************************************************/
116948 /************** Begin file fts3_aux.c ****************************************/
116950 ** 2011 Jan 27
116952 ** The author disclaims copyright to this source code. In place of
116953 ** a legal notice, here is a blessing:
116955 ** May you do good and not evil.
116956 ** May you find forgiveness for yourself and forgive others.
116957 ** May you share freely, never taking more than you give.
116959 ******************************************************************************
116963 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
116966 typedef struct Fts3auxTable Fts3auxTable;
116967 typedef struct Fts3auxCursor Fts3auxCursor;
116969 struct Fts3auxTable {
116970 sqlite3_vtab base; /* Base class used by SQLite core */
116971 Fts3Table *pFts3Tab;
116974 struct Fts3auxCursor {
116975 sqlite3_vtab_cursor base; /* Base class used by SQLite core */
116976 Fts3SegReaderCursor csr; /* Must be right after "base" */
116977 Fts3SegFilter filter;
116978 char *zStop;
116979 int nStop; /* Byte-length of string zStop */
116980 int isEof; /* True if cursor is at EOF */
116981 sqlite3_int64 iRowid; /* Current rowid */
116983 int iCol; /* Current value of 'col' column */
116984 int nStat; /* Size of aStat[] array */
116985 struct Fts3auxColstats {
116986 sqlite3_int64 nDoc; /* 'documents' values for current csr row */
116987 sqlite3_int64 nOcc; /* 'occurrences' values for current csr row */
116988 } *aStat;
116992 ** Schema of the terms table.
116994 #define FTS3_TERMS_SCHEMA "CREATE TABLE x(term, col, documents, occurrences)"
116997 ** This function does all the work for both the xConnect and xCreate methods.
116998 ** These tables have no persistent representation of their own, so xConnect
116999 ** and xCreate are identical operations.
117001 static int fts3auxConnectMethod(
117002 sqlite3 *db, /* Database connection */
117003 void *pUnused, /* Unused */
117004 int argc, /* Number of elements in argv array */
117005 const char * const *argv, /* xCreate/xConnect argument array */
117006 sqlite3_vtab **ppVtab, /* OUT: New sqlite3_vtab object */
117007 char **pzErr /* OUT: sqlite3_malloc'd error message */
117009 char const *zDb; /* Name of database (e.g. "main") */
117010 char const *zFts3; /* Name of fts3 table */
117011 int nDb; /* Result of strlen(zDb) */
117012 int nFts3; /* Result of strlen(zFts3) */
117013 int nByte; /* Bytes of space to allocate here */
117014 int rc; /* value returned by declare_vtab() */
117015 Fts3auxTable *p; /* Virtual table object to return */
117017 UNUSED_PARAMETER(pUnused);
117019 /* The user should specify a single argument - the name of an fts3 table. */
117020 if( argc!=4 ){
117021 *pzErr = sqlite3_mprintf(
117022 "wrong number of arguments to fts4aux constructor"
117024 return SQLITE_ERROR;
117027 zDb = argv[1];
117028 nDb = strlen(zDb);
117029 zFts3 = argv[3];
117030 nFts3 = strlen(zFts3);
117032 rc = sqlite3_declare_vtab(db, FTS3_TERMS_SCHEMA);
117033 if( rc!=SQLITE_OK ) return rc;
117035 nByte = sizeof(Fts3auxTable) + sizeof(Fts3Table) + nDb + nFts3 + 2;
117036 p = (Fts3auxTable *)sqlite3_malloc(nByte);
117037 if( !p ) return SQLITE_NOMEM;
117038 memset(p, 0, nByte);
117040 p->pFts3Tab = (Fts3Table *)&p[1];
117041 p->pFts3Tab->zDb = (char *)&p->pFts3Tab[1];
117042 p->pFts3Tab->zName = &p->pFts3Tab->zDb[nDb+1];
117043 p->pFts3Tab->db = db;
117045 memcpy((char *)p->pFts3Tab->zDb, zDb, nDb);
117046 memcpy((char *)p->pFts3Tab->zName, zFts3, nFts3);
117047 sqlite3Fts3Dequote((char *)p->pFts3Tab->zName);
117049 *ppVtab = (sqlite3_vtab *)p;
117050 return SQLITE_OK;
117054 ** This function does the work for both the xDisconnect and xDestroy methods.
117055 ** These tables have no persistent representation of their own, so xDisconnect
117056 ** and xDestroy are identical operations.
117058 static int fts3auxDisconnectMethod(sqlite3_vtab *pVtab){
117059 Fts3auxTable *p = (Fts3auxTable *)pVtab;
117060 Fts3Table *pFts3 = p->pFts3Tab;
117061 int i;
117063 /* Free any prepared statements held */
117064 for(i=0; i<SizeofArray(pFts3->aStmt); i++){
117065 sqlite3_finalize(pFts3->aStmt[i]);
117067 sqlite3_free(pFts3->zSegmentsTbl);
117068 sqlite3_free(p);
117069 return SQLITE_OK;
117072 #define FTS4AUX_EQ_CONSTRAINT 1
117073 #define FTS4AUX_GE_CONSTRAINT 2
117074 #define FTS4AUX_LE_CONSTRAINT 4
117077 ** xBestIndex - Analyze a WHERE and ORDER BY clause.
117079 static int fts3auxBestIndexMethod(
117080 sqlite3_vtab *pVTab,
117081 sqlite3_index_info *pInfo
117083 int i;
117084 int iEq = -1;
117085 int iGe = -1;
117086 int iLe = -1;
117088 UNUSED_PARAMETER(pVTab);
117090 /* This vtab delivers always results in "ORDER BY term ASC" order. */
117091 if( pInfo->nOrderBy==1
117092 && pInfo->aOrderBy[0].iColumn==0
117093 && pInfo->aOrderBy[0].desc==0
117095 pInfo->orderByConsumed = 1;
117098 /* Search for equality and range constraints on the "term" column. */
117099 for(i=0; i<pInfo->nConstraint; i++){
117100 if( pInfo->aConstraint[i].usable && pInfo->aConstraint[i].iColumn==0 ){
117101 int op = pInfo->aConstraint[i].op;
117102 if( op==SQLITE_INDEX_CONSTRAINT_EQ ) iEq = i;
117103 if( op==SQLITE_INDEX_CONSTRAINT_LT ) iLe = i;
117104 if( op==SQLITE_INDEX_CONSTRAINT_LE ) iLe = i;
117105 if( op==SQLITE_INDEX_CONSTRAINT_GT ) iGe = i;
117106 if( op==SQLITE_INDEX_CONSTRAINT_GE ) iGe = i;
117110 if( iEq>=0 ){
117111 pInfo->idxNum = FTS4AUX_EQ_CONSTRAINT;
117112 pInfo->aConstraintUsage[iEq].argvIndex = 1;
117113 pInfo->estimatedCost = 5;
117114 }else{
117115 pInfo->idxNum = 0;
117116 pInfo->estimatedCost = 20000;
117117 if( iGe>=0 ){
117118 pInfo->idxNum += FTS4AUX_GE_CONSTRAINT;
117119 pInfo->aConstraintUsage[iGe].argvIndex = 1;
117120 pInfo->estimatedCost /= 2;
117122 if( iLe>=0 ){
117123 pInfo->idxNum += FTS4AUX_LE_CONSTRAINT;
117124 pInfo->aConstraintUsage[iLe].argvIndex = 1 + (iGe>=0);
117125 pInfo->estimatedCost /= 2;
117129 return SQLITE_OK;
117133 ** xOpen - Open a cursor.
117135 static int fts3auxOpenMethod(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCsr){
117136 Fts3auxCursor *pCsr; /* Pointer to cursor object to return */
117138 UNUSED_PARAMETER(pVTab);
117140 pCsr = (Fts3auxCursor *)sqlite3_malloc(sizeof(Fts3auxCursor));
117141 if( !pCsr ) return SQLITE_NOMEM;
117142 memset(pCsr, 0, sizeof(Fts3auxCursor));
117144 *ppCsr = (sqlite3_vtab_cursor *)pCsr;
117145 return SQLITE_OK;
117149 ** xClose - Close a cursor.
117151 static int fts3auxCloseMethod(sqlite3_vtab_cursor *pCursor){
117152 Fts3Table *pFts3 = ((Fts3auxTable *)pCursor->pVtab)->pFts3Tab;
117153 Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
117155 sqlite3Fts3SegmentsClose(pFts3);
117156 sqlite3Fts3SegReaderFinish(&pCsr->csr);
117157 sqlite3_free((void *)pCsr->filter.zTerm);
117158 sqlite3_free(pCsr->zStop);
117159 sqlite3_free(pCsr->aStat);
117160 sqlite3_free(pCsr);
117161 return SQLITE_OK;
117164 static int fts3auxGrowStatArray(Fts3auxCursor *pCsr, int nSize){
117165 if( nSize>pCsr->nStat ){
117166 struct Fts3auxColstats *aNew;
117167 aNew = (struct Fts3auxColstats *)sqlite3_realloc(pCsr->aStat,
117168 sizeof(struct Fts3auxColstats) * nSize
117170 if( aNew==0 ) return SQLITE_NOMEM;
117171 memset(&aNew[pCsr->nStat], 0,
117172 sizeof(struct Fts3auxColstats) * (nSize - pCsr->nStat)
117174 pCsr->aStat = aNew;
117175 pCsr->nStat = nSize;
117177 return SQLITE_OK;
117181 ** xNext - Advance the cursor to the next row, if any.
117183 static int fts3auxNextMethod(sqlite3_vtab_cursor *pCursor){
117184 Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
117185 Fts3Table *pFts3 = ((Fts3auxTable *)pCursor->pVtab)->pFts3Tab;
117186 int rc;
117188 /* Increment our pretend rowid value. */
117189 pCsr->iRowid++;
117191 for(pCsr->iCol++; pCsr->iCol<pCsr->nStat; pCsr->iCol++){
117192 if( pCsr->aStat[pCsr->iCol].nDoc>0 ) return SQLITE_OK;
117195 rc = sqlite3Fts3SegReaderStep(pFts3, &pCsr->csr);
117196 if( rc==SQLITE_ROW ){
117197 int i = 0;
117198 int nDoclist = pCsr->csr.nDoclist;
117199 char *aDoclist = pCsr->csr.aDoclist;
117200 int iCol;
117202 int eState = 0;
117204 if( pCsr->zStop ){
117205 int n = (pCsr->nStop<pCsr->csr.nTerm) ? pCsr->nStop : pCsr->csr.nTerm;
117206 int mc = memcmp(pCsr->zStop, pCsr->csr.zTerm, n);
117207 if( mc<0 || (mc==0 && pCsr->csr.nTerm>pCsr->nStop) ){
117208 pCsr->isEof = 1;
117209 return SQLITE_OK;
117213 if( fts3auxGrowStatArray(pCsr, 2) ) return SQLITE_NOMEM;
117214 memset(pCsr->aStat, 0, sizeof(struct Fts3auxColstats) * pCsr->nStat);
117215 iCol = 0;
117217 while( i<nDoclist ){
117218 sqlite3_int64 v = 0;
117220 i += sqlite3Fts3GetVarint(&aDoclist[i], &v);
117221 switch( eState ){
117222 /* State 0. In this state the integer just read was a docid. */
117223 case 0:
117224 pCsr->aStat[0].nDoc++;
117225 eState = 1;
117226 iCol = 0;
117227 break;
117229 /* State 1. In this state we are expecting either a 1, indicating
117230 ** that the following integer will be a column number, or the
117231 ** start of a position list for column 0.
117233 ** The only difference between state 1 and state 2 is that if the
117234 ** integer encountered in state 1 is not 0 or 1, then we need to
117235 ** increment the column 0 "nDoc" count for this term.
117237 case 1:
117238 assert( iCol==0 );
117239 if( v>1 ){
117240 pCsr->aStat[1].nDoc++;
117242 eState = 2;
117243 /* fall through */
117245 case 2:
117246 if( v==0 ){ /* 0x00. Next integer will be a docid. */
117247 eState = 0;
117248 }else if( v==1 ){ /* 0x01. Next integer will be a column number. */
117249 eState = 3;
117250 }else{ /* 2 or greater. A position. */
117251 pCsr->aStat[iCol+1].nOcc++;
117252 pCsr->aStat[0].nOcc++;
117254 break;
117256 /* State 3. The integer just read is a column number. */
117257 default: assert( eState==3 );
117258 iCol = (int)v;
117259 if( fts3auxGrowStatArray(pCsr, iCol+2) ) return SQLITE_NOMEM;
117260 pCsr->aStat[iCol+1].nDoc++;
117261 eState = 2;
117262 break;
117266 pCsr->iCol = 0;
117267 rc = SQLITE_OK;
117268 }else{
117269 pCsr->isEof = 1;
117271 return rc;
117275 ** xFilter - Initialize a cursor to point at the start of its data.
117277 static int fts3auxFilterMethod(
117278 sqlite3_vtab_cursor *pCursor, /* The cursor used for this query */
117279 int idxNum, /* Strategy index */
117280 const char *idxStr, /* Unused */
117281 int nVal, /* Number of elements in apVal */
117282 sqlite3_value **apVal /* Arguments for the indexing scheme */
117284 Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
117285 Fts3Table *pFts3 = ((Fts3auxTable *)pCursor->pVtab)->pFts3Tab;
117286 int rc;
117287 int isScan;
117289 UNUSED_PARAMETER(nVal);
117291 assert( idxStr==0 );
117292 assert( idxNum==FTS4AUX_EQ_CONSTRAINT || idxNum==0
117293 || idxNum==FTS4AUX_LE_CONSTRAINT || idxNum==FTS4AUX_GE_CONSTRAINT
117294 || idxNum==(FTS4AUX_LE_CONSTRAINT|FTS4AUX_GE_CONSTRAINT)
117296 isScan = (idxNum!=FTS4AUX_EQ_CONSTRAINT);
117298 /* In case this cursor is being reused, close and zero it. */
117299 testcase(pCsr->filter.zTerm);
117300 sqlite3Fts3SegReaderFinish(&pCsr->csr);
117301 sqlite3_free((void *)pCsr->filter.zTerm);
117302 sqlite3_free(pCsr->aStat);
117303 memset(&pCsr->csr, 0, ((u8*)&pCsr[1]) - (u8*)&pCsr->csr);
117305 pCsr->filter.flags = FTS3_SEGMENT_REQUIRE_POS|FTS3_SEGMENT_IGNORE_EMPTY;
117306 if( isScan ) pCsr->filter.flags |= FTS3_SEGMENT_SCAN;
117308 if( idxNum&(FTS4AUX_EQ_CONSTRAINT|FTS4AUX_GE_CONSTRAINT) ){
117309 const unsigned char *zStr = sqlite3_value_text(apVal[0]);
117310 if( zStr ){
117311 pCsr->filter.zTerm = sqlite3_mprintf("%s", zStr);
117312 pCsr->filter.nTerm = sqlite3_value_bytes(apVal[0]);
117313 if( pCsr->filter.zTerm==0 ) return SQLITE_NOMEM;
117316 if( idxNum&FTS4AUX_LE_CONSTRAINT ){
117317 int iIdx = (idxNum&FTS4AUX_GE_CONSTRAINT) ? 1 : 0;
117318 pCsr->zStop = sqlite3_mprintf("%s", sqlite3_value_text(apVal[iIdx]));
117319 pCsr->nStop = sqlite3_value_bytes(apVal[iIdx]);
117320 if( pCsr->zStop==0 ) return SQLITE_NOMEM;
117323 rc = sqlite3Fts3SegReaderCursor(pFts3, FTS3_SEGCURSOR_ALL,
117324 pCsr->filter.zTerm, pCsr->filter.nTerm, 0, isScan, &pCsr->csr
117326 if( rc==SQLITE_OK ){
117327 rc = sqlite3Fts3SegReaderStart(pFts3, &pCsr->csr, &pCsr->filter);
117330 if( rc==SQLITE_OK ) rc = fts3auxNextMethod(pCursor);
117331 return rc;
117335 ** xEof - Return true if the cursor is at EOF, or false otherwise.
117337 static int fts3auxEofMethod(sqlite3_vtab_cursor *pCursor){
117338 Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
117339 return pCsr->isEof;
117343 ** xColumn - Return a column value.
117345 static int fts3auxColumnMethod(
117346 sqlite3_vtab_cursor *pCursor, /* Cursor to retrieve value from */
117347 sqlite3_context *pContext, /* Context for sqlite3_result_xxx() calls */
117348 int iCol /* Index of column to read value from */
117350 Fts3auxCursor *p = (Fts3auxCursor *)pCursor;
117352 assert( p->isEof==0 );
117353 if( iCol==0 ){ /* Column "term" */
117354 sqlite3_result_text(pContext, p->csr.zTerm, p->csr.nTerm, SQLITE_TRANSIENT);
117355 }else if( iCol==1 ){ /* Column "col" */
117356 if( p->iCol ){
117357 sqlite3_result_int(pContext, p->iCol-1);
117358 }else{
117359 sqlite3_result_text(pContext, "*", -1, SQLITE_STATIC);
117361 }else if( iCol==2 ){ /* Column "documents" */
117362 sqlite3_result_int64(pContext, p->aStat[p->iCol].nDoc);
117363 }else{ /* Column "occurrences" */
117364 sqlite3_result_int64(pContext, p->aStat[p->iCol].nOcc);
117367 return SQLITE_OK;
117371 ** xRowid - Return the current rowid for the cursor.
117373 static int fts3auxRowidMethod(
117374 sqlite3_vtab_cursor *pCursor, /* Cursor to retrieve value from */
117375 sqlite_int64 *pRowid /* OUT: Rowid value */
117377 Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
117378 *pRowid = pCsr->iRowid;
117379 return SQLITE_OK;
117383 ** Register the fts3aux module with database connection db. Return SQLITE_OK
117384 ** if successful or an error code if sqlite3_create_module() fails.
117386 SQLITE_PRIVATE int sqlite3Fts3InitAux(sqlite3 *db){
117387 static const sqlite3_module fts3aux_module = {
117388 0, /* iVersion */
117389 fts3auxConnectMethod, /* xCreate */
117390 fts3auxConnectMethod, /* xConnect */
117391 fts3auxBestIndexMethod, /* xBestIndex */
117392 fts3auxDisconnectMethod, /* xDisconnect */
117393 fts3auxDisconnectMethod, /* xDestroy */
117394 fts3auxOpenMethod, /* xOpen */
117395 fts3auxCloseMethod, /* xClose */
117396 fts3auxFilterMethod, /* xFilter */
117397 fts3auxNextMethod, /* xNext */
117398 fts3auxEofMethod, /* xEof */
117399 fts3auxColumnMethod, /* xColumn */
117400 fts3auxRowidMethod, /* xRowid */
117401 0, /* xUpdate */
117402 0, /* xBegin */
117403 0, /* xSync */
117404 0, /* xCommit */
117405 0, /* xRollback */
117406 0, /* xFindFunction */
117407 0 /* xRename */
117409 int rc; /* Return code */
117411 rc = sqlite3_create_module(db, "fts4aux", &fts3aux_module, 0);
117412 return rc;
117415 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
117417 /************** End of fts3_aux.c ********************************************/
117418 /************** Begin file fts3_expr.c ***************************************/
117420 ** 2008 Nov 28
117422 ** The author disclaims copyright to this source code. In place of
117423 ** a legal notice, here is a blessing:
117425 ** May you do good and not evil.
117426 ** May you find forgiveness for yourself and forgive others.
117427 ** May you share freely, never taking more than you give.
117429 ******************************************************************************
117431 ** This module contains code that implements a parser for fts3 query strings
117432 ** (the right-hand argument to the MATCH operator). Because the supported
117433 ** syntax is relatively simple, the whole tokenizer/parser system is
117434 ** hand-coded.
117436 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
117439 ** By default, this module parses the legacy syntax that has been
117440 ** traditionally used by fts3. Or, if SQLITE_ENABLE_FTS3_PARENTHESIS
117441 ** is defined, then it uses the new syntax. The differences between
117442 ** the new and the old syntaxes are:
117444 ** a) The new syntax supports parenthesis. The old does not.
117446 ** b) The new syntax supports the AND and NOT operators. The old does not.
117448 ** c) The old syntax supports the "-" token qualifier. This is not
117449 ** supported by the new syntax (it is replaced by the NOT operator).
117451 ** d) When using the old syntax, the OR operator has a greater precedence
117452 ** than an implicit AND. When using the new, both implicity and explicit
117453 ** AND operators have a higher precedence than OR.
117455 ** If compiled with SQLITE_TEST defined, then this module exports the
117456 ** symbol "int sqlite3_fts3_enable_parentheses". Setting this variable
117457 ** to zero causes the module to use the old syntax. If it is set to
117458 ** non-zero the new syntax is activated. This is so both syntaxes can
117459 ** be tested using a single build of testfixture.
117461 ** The following describes the syntax supported by the fts3 MATCH
117462 ** operator in a similar format to that used by the lemon parser
117463 ** generator. This module does not use actually lemon, it uses a
117464 ** custom parser.
117466 ** query ::= andexpr (OR andexpr)*.
117468 ** andexpr ::= notexpr (AND? notexpr)*.
117470 ** notexpr ::= nearexpr (NOT nearexpr|-TOKEN)*.
117471 ** notexpr ::= LP query RP.
117473 ** nearexpr ::= phrase (NEAR distance_opt nearexpr)*.
117475 ** distance_opt ::= .
117476 ** distance_opt ::= / INTEGER.
117478 ** phrase ::= TOKEN.
117479 ** phrase ::= COLUMN:TOKEN.
117480 ** phrase ::= "TOKEN TOKEN TOKEN...".
117483 #ifdef SQLITE_TEST
117484 SQLITE_API int sqlite3_fts3_enable_parentheses = 0;
117485 #else
117486 # ifdef SQLITE_ENABLE_FTS3_PARENTHESIS
117487 # define sqlite3_fts3_enable_parentheses 1
117488 # else
117489 # define sqlite3_fts3_enable_parentheses 0
117490 # endif
117491 #endif
117494 ** Default span for NEAR operators.
117496 #define SQLITE_FTS3_DEFAULT_NEAR_PARAM 10
117499 typedef struct ParseContext ParseContext;
117500 struct ParseContext {
117501 sqlite3_tokenizer *pTokenizer; /* Tokenizer module */
117502 const char **azCol; /* Array of column names for fts3 table */
117503 int nCol; /* Number of entries in azCol[] */
117504 int iDefaultCol; /* Default column to query */
117505 sqlite3_context *pCtx; /* Write error message here */
117506 int nNest; /* Number of nested brackets */
117510 ** This function is equivalent to the standard isspace() function.
117512 ** The standard isspace() can be awkward to use safely, because although it
117513 ** is defined to accept an argument of type int, its behaviour when passed
117514 ** an integer that falls outside of the range of the unsigned char type
117515 ** is undefined (and sometimes, "undefined" means segfault). This wrapper
117516 ** is defined to accept an argument of type char, and always returns 0 for
117517 ** any values that fall outside of the range of the unsigned char type (i.e.
117518 ** negative values).
117520 static int fts3isspace(char c){
117521 return c==' ' || c=='\t' || c=='\n' || c=='\r' || c=='\v' || c=='\f';
117525 ** Allocate nByte bytes of memory using sqlite3_malloc(). If successful,
117526 ** zero the memory before returning a pointer to it. If unsuccessful,
117527 ** return NULL.
117529 static void *fts3MallocZero(int nByte){
117530 void *pRet = sqlite3_malloc(nByte);
117531 if( pRet ) memset(pRet, 0, nByte);
117532 return pRet;
117537 ** Extract the next token from buffer z (length n) using the tokenizer
117538 ** and other information (column names etc.) in pParse. Create an Fts3Expr
117539 ** structure of type FTSQUERY_PHRASE containing a phrase consisting of this
117540 ** single token and set *ppExpr to point to it. If the end of the buffer is
117541 ** reached before a token is found, set *ppExpr to zero. It is the
117542 ** responsibility of the caller to eventually deallocate the allocated
117543 ** Fts3Expr structure (if any) by passing it to sqlite3_free().
117545 ** Return SQLITE_OK if successful, or SQLITE_NOMEM if a memory allocation
117546 ** fails.
117548 static int getNextToken(
117549 ParseContext *pParse, /* fts3 query parse context */
117550 int iCol, /* Value for Fts3Phrase.iColumn */
117551 const char *z, int n, /* Input string */
117552 Fts3Expr **ppExpr, /* OUT: expression */
117553 int *pnConsumed /* OUT: Number of bytes consumed */
117555 sqlite3_tokenizer *pTokenizer = pParse->pTokenizer;
117556 sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
117557 int rc;
117558 sqlite3_tokenizer_cursor *pCursor;
117559 Fts3Expr *pRet = 0;
117560 int nConsumed = 0;
117562 rc = pModule->xOpen(pTokenizer, z, n, &pCursor);
117563 if( rc==SQLITE_OK ){
117564 const char *zToken;
117565 int nToken, iStart, iEnd, iPosition;
117566 int nByte; /* total space to allocate */
117568 pCursor->pTokenizer = pTokenizer;
117569 rc = pModule->xNext(pCursor, &zToken, &nToken, &iStart, &iEnd, &iPosition);
117571 if( rc==SQLITE_OK ){
117572 nByte = sizeof(Fts3Expr) + sizeof(Fts3Phrase) + nToken;
117573 pRet = (Fts3Expr *)fts3MallocZero(nByte);
117574 if( !pRet ){
117575 rc = SQLITE_NOMEM;
117576 }else{
117577 pRet->eType = FTSQUERY_PHRASE;
117578 pRet->pPhrase = (Fts3Phrase *)&pRet[1];
117579 pRet->pPhrase->nToken = 1;
117580 pRet->pPhrase->iColumn = iCol;
117581 pRet->pPhrase->aToken[0].n = nToken;
117582 pRet->pPhrase->aToken[0].z = (char *)&pRet->pPhrase[1];
117583 memcpy(pRet->pPhrase->aToken[0].z, zToken, nToken);
117585 if( iEnd<n && z[iEnd]=='*' ){
117586 pRet->pPhrase->aToken[0].isPrefix = 1;
117587 iEnd++;
117589 if( !sqlite3_fts3_enable_parentheses && iStart>0 && z[iStart-1]=='-' ){
117590 pRet->pPhrase->isNot = 1;
117593 nConsumed = iEnd;
117596 pModule->xClose(pCursor);
117599 *pnConsumed = nConsumed;
117600 *ppExpr = pRet;
117601 return rc;
117606 ** Enlarge a memory allocation. If an out-of-memory allocation occurs,
117607 ** then free the old allocation.
117609 static void *fts3ReallocOrFree(void *pOrig, int nNew){
117610 void *pRet = sqlite3_realloc(pOrig, nNew);
117611 if( !pRet ){
117612 sqlite3_free(pOrig);
117614 return pRet;
117618 ** Buffer zInput, length nInput, contains the contents of a quoted string
117619 ** that appeared as part of an fts3 query expression. Neither quote character
117620 ** is included in the buffer. This function attempts to tokenize the entire
117621 ** input buffer and create an Fts3Expr structure of type FTSQUERY_PHRASE
117622 ** containing the results.
117624 ** If successful, SQLITE_OK is returned and *ppExpr set to point at the
117625 ** allocated Fts3Expr structure. Otherwise, either SQLITE_NOMEM (out of memory
117626 ** error) or SQLITE_ERROR (tokenization error) is returned and *ppExpr set
117627 ** to 0.
117629 static int getNextString(
117630 ParseContext *pParse, /* fts3 query parse context */
117631 const char *zInput, int nInput, /* Input string */
117632 Fts3Expr **ppExpr /* OUT: expression */
117634 sqlite3_tokenizer *pTokenizer = pParse->pTokenizer;
117635 sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
117636 int rc;
117637 Fts3Expr *p = 0;
117638 sqlite3_tokenizer_cursor *pCursor = 0;
117639 char *zTemp = 0;
117640 int nTemp = 0;
117642 rc = pModule->xOpen(pTokenizer, zInput, nInput, &pCursor);
117643 if( rc==SQLITE_OK ){
117644 int ii;
117645 pCursor->pTokenizer = pTokenizer;
117646 for(ii=0; rc==SQLITE_OK; ii++){
117647 const char *zToken;
117648 int nToken, iBegin, iEnd, iPos;
117649 rc = pModule->xNext(pCursor, &zToken, &nToken, &iBegin, &iEnd, &iPos);
117650 if( rc==SQLITE_OK ){
117651 int nByte = sizeof(Fts3Expr) + sizeof(Fts3Phrase);
117652 p = fts3ReallocOrFree(p, nByte+ii*sizeof(Fts3PhraseToken));
117653 zTemp = fts3ReallocOrFree(zTemp, nTemp + nToken);
117654 if( !p || !zTemp ){
117655 goto no_mem;
117657 if( ii==0 ){
117658 memset(p, 0, nByte);
117659 p->pPhrase = (Fts3Phrase *)&p[1];
117661 p->pPhrase = (Fts3Phrase *)&p[1];
117662 memset(&p->pPhrase->aToken[ii], 0, sizeof(Fts3PhraseToken));
117663 p->pPhrase->nToken = ii+1;
117664 p->pPhrase->aToken[ii].n = nToken;
117665 memcpy(&zTemp[nTemp], zToken, nToken);
117666 nTemp += nToken;
117667 if( iEnd<nInput && zInput[iEnd]=='*' ){
117668 p->pPhrase->aToken[ii].isPrefix = 1;
117669 }else{
117670 p->pPhrase->aToken[ii].isPrefix = 0;
117675 pModule->xClose(pCursor);
117676 pCursor = 0;
117679 if( rc==SQLITE_DONE ){
117680 int jj;
117681 char *zNew = NULL;
117682 int nNew = 0;
117683 int nByte = sizeof(Fts3Expr) + sizeof(Fts3Phrase);
117684 nByte += (p?(p->pPhrase->nToken-1):0) * sizeof(Fts3PhraseToken);
117685 p = fts3ReallocOrFree(p, nByte + nTemp);
117686 if( !p ){
117687 goto no_mem;
117689 if( zTemp ){
117690 zNew = &(((char *)p)[nByte]);
117691 memcpy(zNew, zTemp, nTemp);
117692 }else{
117693 memset(p, 0, nByte+nTemp);
117695 p->pPhrase = (Fts3Phrase *)&p[1];
117696 for(jj=0; jj<p->pPhrase->nToken; jj++){
117697 p->pPhrase->aToken[jj].z = &zNew[nNew];
117698 nNew += p->pPhrase->aToken[jj].n;
117700 sqlite3_free(zTemp);
117701 p->eType = FTSQUERY_PHRASE;
117702 p->pPhrase->iColumn = pParse->iDefaultCol;
117703 rc = SQLITE_OK;
117706 *ppExpr = p;
117707 return rc;
117708 no_mem:
117710 if( pCursor ){
117711 pModule->xClose(pCursor);
117713 sqlite3_free(zTemp);
117714 sqlite3_free(p);
117715 *ppExpr = 0;
117716 return SQLITE_NOMEM;
117720 ** Function getNextNode(), which is called by fts3ExprParse(), may itself
117721 ** call fts3ExprParse(). So this forward declaration is required.
117723 static int fts3ExprParse(ParseContext *, const char *, int, Fts3Expr **, int *);
117726 ** The output variable *ppExpr is populated with an allocated Fts3Expr
117727 ** structure, or set to 0 if the end of the input buffer is reached.
117729 ** Returns an SQLite error code. SQLITE_OK if everything works, SQLITE_NOMEM
117730 ** if a malloc failure occurs, or SQLITE_ERROR if a parse error is encountered.
117731 ** If SQLITE_ERROR is returned, pContext is populated with an error message.
117733 static int getNextNode(
117734 ParseContext *pParse, /* fts3 query parse context */
117735 const char *z, int n, /* Input string */
117736 Fts3Expr **ppExpr, /* OUT: expression */
117737 int *pnConsumed /* OUT: Number of bytes consumed */
117739 static const struct Fts3Keyword {
117740 char *z; /* Keyword text */
117741 unsigned char n; /* Length of the keyword */
117742 unsigned char parenOnly; /* Only valid in paren mode */
117743 unsigned char eType; /* Keyword code */
117744 } aKeyword[] = {
117745 { "OR" , 2, 0, FTSQUERY_OR },
117746 { "AND", 3, 1, FTSQUERY_AND },
117747 { "NOT", 3, 1, FTSQUERY_NOT },
117748 { "NEAR", 4, 0, FTSQUERY_NEAR }
117750 int ii;
117751 int iCol;
117752 int iColLen;
117753 int rc;
117754 Fts3Expr *pRet = 0;
117756 const char *zInput = z;
117757 int nInput = n;
117759 /* Skip over any whitespace before checking for a keyword, an open or
117760 ** close bracket, or a quoted string.
117762 while( nInput>0 && fts3isspace(*zInput) ){
117763 nInput--;
117764 zInput++;
117766 if( nInput==0 ){
117767 return SQLITE_DONE;
117770 /* See if we are dealing with a keyword. */
117771 for(ii=0; ii<(int)(sizeof(aKeyword)/sizeof(struct Fts3Keyword)); ii++){
117772 const struct Fts3Keyword *pKey = &aKeyword[ii];
117774 if( (pKey->parenOnly & ~sqlite3_fts3_enable_parentheses)!=0 ){
117775 continue;
117778 if( nInput>=pKey->n && 0==memcmp(zInput, pKey->z, pKey->n) ){
117779 int nNear = SQLITE_FTS3_DEFAULT_NEAR_PARAM;
117780 int nKey = pKey->n;
117781 char cNext;
117783 /* If this is a "NEAR" keyword, check for an explicit nearness. */
117784 if( pKey->eType==FTSQUERY_NEAR ){
117785 assert( nKey==4 );
117786 if( zInput[4]=='/' && zInput[5]>='0' && zInput[5]<='9' ){
117787 nNear = 0;
117788 for(nKey=5; zInput[nKey]>='0' && zInput[nKey]<='9'; nKey++){
117789 nNear = nNear * 10 + (zInput[nKey] - '0');
117794 /* At this point this is probably a keyword. But for that to be true,
117795 ** the next byte must contain either whitespace, an open or close
117796 ** parenthesis, a quote character, or EOF.
117798 cNext = zInput[nKey];
117799 if( fts3isspace(cNext)
117800 || cNext=='"' || cNext=='(' || cNext==')' || cNext==0
117802 pRet = (Fts3Expr *)fts3MallocZero(sizeof(Fts3Expr));
117803 if( !pRet ){
117804 return SQLITE_NOMEM;
117806 pRet->eType = pKey->eType;
117807 pRet->nNear = nNear;
117808 *ppExpr = pRet;
117809 *pnConsumed = (int)((zInput - z) + nKey);
117810 return SQLITE_OK;
117813 /* Turns out that wasn't a keyword after all. This happens if the
117814 ** user has supplied a token such as "ORacle". Continue.
117819 /* Check for an open bracket. */
117820 if( sqlite3_fts3_enable_parentheses ){
117821 if( *zInput=='(' ){
117822 int nConsumed;
117823 pParse->nNest++;
117824 rc = fts3ExprParse(pParse, &zInput[1], nInput-1, ppExpr, &nConsumed);
117825 if( rc==SQLITE_OK && !*ppExpr ){
117826 rc = SQLITE_DONE;
117828 *pnConsumed = (int)((zInput - z) + 1 + nConsumed);
117829 return rc;
117832 /* Check for a close bracket. */
117833 if( *zInput==')' ){
117834 pParse->nNest--;
117835 *pnConsumed = (int)((zInput - z) + 1);
117836 return SQLITE_DONE;
117840 /* See if we are dealing with a quoted phrase. If this is the case, then
117841 ** search for the closing quote and pass the whole string to getNextString()
117842 ** for processing. This is easy to do, as fts3 has no syntax for escaping
117843 ** a quote character embedded in a string.
117845 if( *zInput=='"' ){
117846 for(ii=1; ii<nInput && zInput[ii]!='"'; ii++);
117847 *pnConsumed = (int)((zInput - z) + ii + 1);
117848 if( ii==nInput ){
117849 return SQLITE_ERROR;
117851 return getNextString(pParse, &zInput[1], ii-1, ppExpr);
117855 /* If control flows to this point, this must be a regular token, or
117856 ** the end of the input. Read a regular token using the sqlite3_tokenizer
117857 ** interface. Before doing so, figure out if there is an explicit
117858 ** column specifier for the token.
117860 ** TODO: Strangely, it is not possible to associate a column specifier
117861 ** with a quoted phrase, only with a single token. Not sure if this was
117862 ** an implementation artifact or an intentional decision when fts3 was
117863 ** first implemented. Whichever it was, this module duplicates the
117864 ** limitation.
117866 iCol = pParse->iDefaultCol;
117867 iColLen = 0;
117868 for(ii=0; ii<pParse->nCol; ii++){
117869 const char *zStr = pParse->azCol[ii];
117870 int nStr = (int)strlen(zStr);
117871 if( nInput>nStr && zInput[nStr]==':'
117872 && sqlite3_strnicmp(zStr, zInput, nStr)==0
117874 iCol = ii;
117875 iColLen = (int)((zInput - z) + nStr + 1);
117876 break;
117879 rc = getNextToken(pParse, iCol, &z[iColLen], n-iColLen, ppExpr, pnConsumed);
117880 *pnConsumed += iColLen;
117881 return rc;
117885 ** The argument is an Fts3Expr structure for a binary operator (any type
117886 ** except an FTSQUERY_PHRASE). Return an integer value representing the
117887 ** precedence of the operator. Lower values have a higher precedence (i.e.
117888 ** group more tightly). For example, in the C language, the == operator
117889 ** groups more tightly than ||, and would therefore have a higher precedence.
117891 ** When using the new fts3 query syntax (when SQLITE_ENABLE_FTS3_PARENTHESIS
117892 ** is defined), the order of the operators in precedence from highest to
117893 ** lowest is:
117895 ** NEAR
117896 ** NOT
117897 ** AND (including implicit ANDs)
117898 ** OR
117900 ** Note that when using the old query syntax, the OR operator has a higher
117901 ** precedence than the AND operator.
117903 static int opPrecedence(Fts3Expr *p){
117904 assert( p->eType!=FTSQUERY_PHRASE );
117905 if( sqlite3_fts3_enable_parentheses ){
117906 return p->eType;
117907 }else if( p->eType==FTSQUERY_NEAR ){
117908 return 1;
117909 }else if( p->eType==FTSQUERY_OR ){
117910 return 2;
117912 assert( p->eType==FTSQUERY_AND );
117913 return 3;
117917 ** Argument ppHead contains a pointer to the current head of a query
117918 ** expression tree being parsed. pPrev is the expression node most recently
117919 ** inserted into the tree. This function adds pNew, which is always a binary
117920 ** operator node, into the expression tree based on the relative precedence
117921 ** of pNew and the existing nodes of the tree. This may result in the head
117922 ** of the tree changing, in which case *ppHead is set to the new root node.
117924 static void insertBinaryOperator(
117925 Fts3Expr **ppHead, /* Pointer to the root node of a tree */
117926 Fts3Expr *pPrev, /* Node most recently inserted into the tree */
117927 Fts3Expr *pNew /* New binary node to insert into expression tree */
117929 Fts3Expr *pSplit = pPrev;
117930 while( pSplit->pParent && opPrecedence(pSplit->pParent)<=opPrecedence(pNew) ){
117931 pSplit = pSplit->pParent;
117934 if( pSplit->pParent ){
117935 assert( pSplit->pParent->pRight==pSplit );
117936 pSplit->pParent->pRight = pNew;
117937 pNew->pParent = pSplit->pParent;
117938 }else{
117939 *ppHead = pNew;
117941 pNew->pLeft = pSplit;
117942 pSplit->pParent = pNew;
117946 ** Parse the fts3 query expression found in buffer z, length n. This function
117947 ** returns either when the end of the buffer is reached or an unmatched
117948 ** closing bracket - ')' - is encountered.
117950 ** If successful, SQLITE_OK is returned, *ppExpr is set to point to the
117951 ** parsed form of the expression and *pnConsumed is set to the number of
117952 ** bytes read from buffer z. Otherwise, *ppExpr is set to 0 and SQLITE_NOMEM
117953 ** (out of memory error) or SQLITE_ERROR (parse error) is returned.
117955 static int fts3ExprParse(
117956 ParseContext *pParse, /* fts3 query parse context */
117957 const char *z, int n, /* Text of MATCH query */
117958 Fts3Expr **ppExpr, /* OUT: Parsed query structure */
117959 int *pnConsumed /* OUT: Number of bytes consumed */
117961 Fts3Expr *pRet = 0;
117962 Fts3Expr *pPrev = 0;
117963 Fts3Expr *pNotBranch = 0; /* Only used in legacy parse mode */
117964 int nIn = n;
117965 const char *zIn = z;
117966 int rc = SQLITE_OK;
117967 int isRequirePhrase = 1;
117969 while( rc==SQLITE_OK ){
117970 Fts3Expr *p = 0;
117971 int nByte = 0;
117972 rc = getNextNode(pParse, zIn, nIn, &p, &nByte);
117973 if( rc==SQLITE_OK ){
117974 int isPhrase;
117976 if( !sqlite3_fts3_enable_parentheses
117977 && p->eType==FTSQUERY_PHRASE && p->pPhrase->isNot
117979 /* Create an implicit NOT operator. */
117980 Fts3Expr *pNot = fts3MallocZero(sizeof(Fts3Expr));
117981 if( !pNot ){
117982 sqlite3Fts3ExprFree(p);
117983 rc = SQLITE_NOMEM;
117984 goto exprparse_out;
117986 pNot->eType = FTSQUERY_NOT;
117987 pNot->pRight = p;
117988 if( pNotBranch ){
117989 pNot->pLeft = pNotBranch;
117991 pNotBranch = pNot;
117992 p = pPrev;
117993 }else{
117994 int eType = p->eType;
117995 assert( eType!=FTSQUERY_PHRASE || !p->pPhrase->isNot );
117996 isPhrase = (eType==FTSQUERY_PHRASE || p->pLeft);
117998 /* The isRequirePhrase variable is set to true if a phrase or
117999 ** an expression contained in parenthesis is required. If a
118000 ** binary operator (AND, OR, NOT or NEAR) is encounted when
118001 ** isRequirePhrase is set, this is a syntax error.
118003 if( !isPhrase && isRequirePhrase ){
118004 sqlite3Fts3ExprFree(p);
118005 rc = SQLITE_ERROR;
118006 goto exprparse_out;
118009 if( isPhrase && !isRequirePhrase ){
118010 /* Insert an implicit AND operator. */
118011 Fts3Expr *pAnd;
118012 assert( pRet && pPrev );
118013 pAnd = fts3MallocZero(sizeof(Fts3Expr));
118014 if( !pAnd ){
118015 sqlite3Fts3ExprFree(p);
118016 rc = SQLITE_NOMEM;
118017 goto exprparse_out;
118019 pAnd->eType = FTSQUERY_AND;
118020 insertBinaryOperator(&pRet, pPrev, pAnd);
118021 pPrev = pAnd;
118024 /* This test catches attempts to make either operand of a NEAR
118025 ** operator something other than a phrase. For example, either of
118026 ** the following:
118028 ** (bracketed expression) NEAR phrase
118029 ** phrase NEAR (bracketed expression)
118031 ** Return an error in either case.
118033 if( pPrev && (
118034 (eType==FTSQUERY_NEAR && !isPhrase && pPrev->eType!=FTSQUERY_PHRASE)
118035 || (eType!=FTSQUERY_PHRASE && isPhrase && pPrev->eType==FTSQUERY_NEAR)
118037 sqlite3Fts3ExprFree(p);
118038 rc = SQLITE_ERROR;
118039 goto exprparse_out;
118042 if( isPhrase ){
118043 if( pRet ){
118044 assert( pPrev && pPrev->pLeft && pPrev->pRight==0 );
118045 pPrev->pRight = p;
118046 p->pParent = pPrev;
118047 }else{
118048 pRet = p;
118050 }else{
118051 insertBinaryOperator(&pRet, pPrev, p);
118053 isRequirePhrase = !isPhrase;
118055 assert( nByte>0 );
118057 assert( rc!=SQLITE_OK || (nByte>0 && nByte<=nIn) );
118058 nIn -= nByte;
118059 zIn += nByte;
118060 pPrev = p;
118063 if( rc==SQLITE_DONE && pRet && isRequirePhrase ){
118064 rc = SQLITE_ERROR;
118067 if( rc==SQLITE_DONE ){
118068 rc = SQLITE_OK;
118069 if( !sqlite3_fts3_enable_parentheses && pNotBranch ){
118070 if( !pRet ){
118071 rc = SQLITE_ERROR;
118072 }else{
118073 Fts3Expr *pIter = pNotBranch;
118074 while( pIter->pLeft ){
118075 pIter = pIter->pLeft;
118077 pIter->pLeft = pRet;
118078 pRet = pNotBranch;
118082 *pnConsumed = n - nIn;
118084 exprparse_out:
118085 if( rc!=SQLITE_OK ){
118086 sqlite3Fts3ExprFree(pRet);
118087 sqlite3Fts3ExprFree(pNotBranch);
118088 pRet = 0;
118090 *ppExpr = pRet;
118091 return rc;
118095 ** Parameters z and n contain a pointer to and length of a buffer containing
118096 ** an fts3 query expression, respectively. This function attempts to parse the
118097 ** query expression and create a tree of Fts3Expr structures representing the
118098 ** parsed expression. If successful, *ppExpr is set to point to the head
118099 ** of the parsed expression tree and SQLITE_OK is returned. If an error
118100 ** occurs, either SQLITE_NOMEM (out-of-memory error) or SQLITE_ERROR (parse
118101 ** error) is returned and *ppExpr is set to 0.
118103 ** If parameter n is a negative number, then z is assumed to point to a
118104 ** nul-terminated string and the length is determined using strlen().
118106 ** The first parameter, pTokenizer, is passed the fts3 tokenizer module to
118107 ** use to normalize query tokens while parsing the expression. The azCol[]
118108 ** array, which is assumed to contain nCol entries, should contain the names
118109 ** of each column in the target fts3 table, in order from left to right.
118110 ** Column names must be nul-terminated strings.
118112 ** The iDefaultCol parameter should be passed the index of the table column
118113 ** that appears on the left-hand-side of the MATCH operator (the default
118114 ** column to match against for tokens for which a column name is not explicitly
118115 ** specified as part of the query string), or -1 if tokens may by default
118116 ** match any table column.
118118 SQLITE_PRIVATE int sqlite3Fts3ExprParse(
118119 sqlite3_tokenizer *pTokenizer, /* Tokenizer module */
118120 char **azCol, /* Array of column names for fts3 table */
118121 int nCol, /* Number of entries in azCol[] */
118122 int iDefaultCol, /* Default column to query */
118123 const char *z, int n, /* Text of MATCH query */
118124 Fts3Expr **ppExpr /* OUT: Parsed query structure */
118126 int nParsed;
118127 int rc;
118128 ParseContext sParse;
118129 sParse.pTokenizer = pTokenizer;
118130 sParse.azCol = (const char **)azCol;
118131 sParse.nCol = nCol;
118132 sParse.iDefaultCol = iDefaultCol;
118133 sParse.nNest = 0;
118134 if( z==0 ){
118135 *ppExpr = 0;
118136 return SQLITE_OK;
118138 if( n<0 ){
118139 n = (int)strlen(z);
118141 rc = fts3ExprParse(&sParse, z, n, ppExpr, &nParsed);
118143 /* Check for mismatched parenthesis */
118144 if( rc==SQLITE_OK && sParse.nNest ){
118145 rc = SQLITE_ERROR;
118146 sqlite3Fts3ExprFree(*ppExpr);
118147 *ppExpr = 0;
118150 return rc;
118154 ** Free a parsed fts3 query expression allocated by sqlite3Fts3ExprParse().
118156 SQLITE_PRIVATE void sqlite3Fts3ExprFree(Fts3Expr *p){
118157 if( p ){
118158 sqlite3Fts3ExprFree(p->pLeft);
118159 sqlite3Fts3ExprFree(p->pRight);
118160 sqlite3_free(p->aDoclist);
118161 sqlite3_free(p);
118165 /****************************************************************************
118166 *****************************************************************************
118167 ** Everything after this point is just test code.
118170 #ifdef SQLITE_TEST
118174 ** Function to query the hash-table of tokenizers (see README.tokenizers).
118176 static int queryTestTokenizer(
118177 sqlite3 *db,
118178 const char *zName,
118179 const sqlite3_tokenizer_module **pp
118181 int rc;
118182 sqlite3_stmt *pStmt;
118183 const char zSql[] = "SELECT fts3_tokenizer(?)";
118185 *pp = 0;
118186 rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
118187 if( rc!=SQLITE_OK ){
118188 return rc;
118191 sqlite3_bind_text(pStmt, 1, zName, -1, SQLITE_STATIC);
118192 if( SQLITE_ROW==sqlite3_step(pStmt) ){
118193 if( sqlite3_column_type(pStmt, 0)==SQLITE_BLOB ){
118194 memcpy((void *)pp, sqlite3_column_blob(pStmt, 0), sizeof(*pp));
118198 return sqlite3_finalize(pStmt);
118202 ** Return a pointer to a buffer containing a text representation of the
118203 ** expression passed as the first argument. The buffer is obtained from
118204 ** sqlite3_malloc(). It is the responsibility of the caller to use
118205 ** sqlite3_free() to release the memory. If an OOM condition is encountered,
118206 ** NULL is returned.
118208 ** If the second argument is not NULL, then its contents are prepended to
118209 ** the returned expression text and then freed using sqlite3_free().
118211 static char *exprToString(Fts3Expr *pExpr, char *zBuf){
118212 switch( pExpr->eType ){
118213 case FTSQUERY_PHRASE: {
118214 Fts3Phrase *pPhrase = pExpr->pPhrase;
118215 int i;
118216 zBuf = sqlite3_mprintf(
118217 "%zPHRASE %d %d", zBuf, pPhrase->iColumn, pPhrase->isNot);
118218 for(i=0; zBuf && i<pPhrase->nToken; i++){
118219 zBuf = sqlite3_mprintf("%z %.*s%s", zBuf,
118220 pPhrase->aToken[i].n, pPhrase->aToken[i].z,
118221 (pPhrase->aToken[i].isPrefix?"+":"")
118224 return zBuf;
118227 case FTSQUERY_NEAR:
118228 zBuf = sqlite3_mprintf("%zNEAR/%d ", zBuf, pExpr->nNear);
118229 break;
118230 case FTSQUERY_NOT:
118231 zBuf = sqlite3_mprintf("%zNOT ", zBuf);
118232 break;
118233 case FTSQUERY_AND:
118234 zBuf = sqlite3_mprintf("%zAND ", zBuf);
118235 break;
118236 case FTSQUERY_OR:
118237 zBuf = sqlite3_mprintf("%zOR ", zBuf);
118238 break;
118241 if( zBuf ) zBuf = sqlite3_mprintf("%z{", zBuf);
118242 if( zBuf ) zBuf = exprToString(pExpr->pLeft, zBuf);
118243 if( zBuf ) zBuf = sqlite3_mprintf("%z} {", zBuf);
118245 if( zBuf ) zBuf = exprToString(pExpr->pRight, zBuf);
118246 if( zBuf ) zBuf = sqlite3_mprintf("%z}", zBuf);
118248 return zBuf;
118252 ** This is the implementation of a scalar SQL function used to test the
118253 ** expression parser. It should be called as follows:
118255 ** fts3_exprtest(<tokenizer>, <expr>, <column 1>, ...);
118257 ** The first argument, <tokenizer>, is the name of the fts3 tokenizer used
118258 ** to parse the query expression (see README.tokenizers). The second argument
118259 ** is the query expression to parse. Each subsequent argument is the name
118260 ** of a column of the fts3 table that the query expression may refer to.
118261 ** For example:
118263 ** SELECT fts3_exprtest('simple', 'Bill col2:Bloggs', 'col1', 'col2');
118265 static void fts3ExprTest(
118266 sqlite3_context *context,
118267 int argc,
118268 sqlite3_value **argv
118270 sqlite3_tokenizer_module const *pModule = 0;
118271 sqlite3_tokenizer *pTokenizer = 0;
118272 int rc;
118273 char **azCol = 0;
118274 const char *zExpr;
118275 int nExpr;
118276 int nCol;
118277 int ii;
118278 Fts3Expr *pExpr;
118279 char *zBuf = 0;
118280 sqlite3 *db = sqlite3_context_db_handle(context);
118282 if( argc<3 ){
118283 sqlite3_result_error(context,
118284 "Usage: fts3_exprtest(tokenizer, expr, col1, ...", -1
118286 return;
118289 rc = queryTestTokenizer(db,
118290 (const char *)sqlite3_value_text(argv[0]), &pModule);
118291 if( rc==SQLITE_NOMEM ){
118292 sqlite3_result_error_nomem(context);
118293 goto exprtest_out;
118294 }else if( !pModule ){
118295 sqlite3_result_error(context, "No such tokenizer module", -1);
118296 goto exprtest_out;
118299 rc = pModule->xCreate(0, 0, &pTokenizer);
118300 assert( rc==SQLITE_NOMEM || rc==SQLITE_OK );
118301 if( rc==SQLITE_NOMEM ){
118302 sqlite3_result_error_nomem(context);
118303 goto exprtest_out;
118305 pTokenizer->pModule = pModule;
118307 zExpr = (const char *)sqlite3_value_text(argv[1]);
118308 nExpr = sqlite3_value_bytes(argv[1]);
118309 nCol = argc-2;
118310 azCol = (char **)sqlite3_malloc(nCol*sizeof(char *));
118311 if( !azCol ){
118312 sqlite3_result_error_nomem(context);
118313 goto exprtest_out;
118315 for(ii=0; ii<nCol; ii++){
118316 azCol[ii] = (char *)sqlite3_value_text(argv[ii+2]);
118319 rc = sqlite3Fts3ExprParse(
118320 pTokenizer, azCol, nCol, nCol, zExpr, nExpr, &pExpr
118322 if( rc!=SQLITE_OK && rc!=SQLITE_NOMEM ){
118323 sqlite3_result_error(context, "Error parsing expression", -1);
118324 }else if( rc==SQLITE_NOMEM || !(zBuf = exprToString(pExpr, 0)) ){
118325 sqlite3_result_error_nomem(context);
118326 }else{
118327 sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
118328 sqlite3_free(zBuf);
118331 sqlite3Fts3ExprFree(pExpr);
118333 exprtest_out:
118334 if( pModule && pTokenizer ){
118335 rc = pModule->xDestroy(pTokenizer);
118337 sqlite3_free(azCol);
118341 ** Register the query expression parser test function fts3_exprtest()
118342 ** with database connection db.
118344 SQLITE_PRIVATE int sqlite3Fts3ExprInitTestInterface(sqlite3* db){
118345 return sqlite3_create_function(
118346 db, "fts3_exprtest", -1, SQLITE_UTF8, 0, fts3ExprTest, 0, 0
118350 #endif
118351 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
118353 /************** End of fts3_expr.c *******************************************/
118354 /************** Begin file fts3_hash.c ***************************************/
118356 ** 2001 September 22
118358 ** The author disclaims copyright to this source code. In place of
118359 ** a legal notice, here is a blessing:
118361 ** May you do good and not evil.
118362 ** May you find forgiveness for yourself and forgive others.
118363 ** May you share freely, never taking more than you give.
118365 *************************************************************************
118366 ** This is the implementation of generic hash-tables used in SQLite.
118367 ** We've modified it slightly to serve as a standalone hash table
118368 ** implementation for the full-text indexing module.
118372 ** The code in this file is only compiled if:
118374 ** * The FTS3 module is being built as an extension
118375 ** (in which case SQLITE_CORE is not defined), or
118377 ** * The FTS3 module is being built into the core of
118378 ** SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
118380 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
118385 ** Malloc and Free functions
118387 static void *fts3HashMalloc(int n){
118388 void *p = sqlite3_malloc(n);
118389 if( p ){
118390 memset(p, 0, n);
118392 return p;
118394 static void fts3HashFree(void *p){
118395 sqlite3_free(p);
118398 /* Turn bulk memory into a hash table object by initializing the
118399 ** fields of the Hash structure.
118401 ** "pNew" is a pointer to the hash table that is to be initialized.
118402 ** keyClass is one of the constants
118403 ** FTS3_HASH_BINARY or FTS3_HASH_STRING. The value of keyClass
118404 ** determines what kind of key the hash table will use. "copyKey" is
118405 ** true if the hash table should make its own private copy of keys and
118406 ** false if it should just use the supplied pointer.
118408 SQLITE_PRIVATE void sqlite3Fts3HashInit(Fts3Hash *pNew, char keyClass, char copyKey){
118409 assert( pNew!=0 );
118410 assert( keyClass>=FTS3_HASH_STRING && keyClass<=FTS3_HASH_BINARY );
118411 pNew->keyClass = keyClass;
118412 pNew->copyKey = copyKey;
118413 pNew->first = 0;
118414 pNew->count = 0;
118415 pNew->htsize = 0;
118416 pNew->ht = 0;
118419 /* Remove all entries from a hash table. Reclaim all memory.
118420 ** Call this routine to delete a hash table or to reset a hash table
118421 ** to the empty state.
118423 SQLITE_PRIVATE void sqlite3Fts3HashClear(Fts3Hash *pH){
118424 Fts3HashElem *elem; /* For looping over all elements of the table */
118426 assert( pH!=0 );
118427 elem = pH->first;
118428 pH->first = 0;
118429 fts3HashFree(pH->ht);
118430 pH->ht = 0;
118431 pH->htsize = 0;
118432 while( elem ){
118433 Fts3HashElem *next_elem = elem->next;
118434 if( pH->copyKey && elem->pKey ){
118435 fts3HashFree(elem->pKey);
118437 fts3HashFree(elem);
118438 elem = next_elem;
118440 pH->count = 0;
118444 ** Hash and comparison functions when the mode is FTS3_HASH_STRING
118446 static int fts3StrHash(const void *pKey, int nKey){
118447 const char *z = (const char *)pKey;
118448 int h = 0;
118449 if( nKey<=0 ) nKey = (int) strlen(z);
118450 while( nKey > 0 ){
118451 h = (h<<3) ^ h ^ *z++;
118452 nKey--;
118454 return h & 0x7fffffff;
118456 static int fts3StrCompare(const void *pKey1, int n1, const void *pKey2, int n2){
118457 if( n1!=n2 ) return 1;
118458 return strncmp((const char*)pKey1,(const char*)pKey2,n1);
118462 ** Hash and comparison functions when the mode is FTS3_HASH_BINARY
118464 static int fts3BinHash(const void *pKey, int nKey){
118465 int h = 0;
118466 const char *z = (const char *)pKey;
118467 while( nKey-- > 0 ){
118468 h = (h<<3) ^ h ^ *(z++);
118470 return h & 0x7fffffff;
118472 static int fts3BinCompare(const void *pKey1, int n1, const void *pKey2, int n2){
118473 if( n1!=n2 ) return 1;
118474 return memcmp(pKey1,pKey2,n1);
118478 ** Return a pointer to the appropriate hash function given the key class.
118480 ** The C syntax in this function definition may be unfamilar to some
118481 ** programmers, so we provide the following additional explanation:
118483 ** The name of the function is "ftsHashFunction". The function takes a
118484 ** single parameter "keyClass". The return value of ftsHashFunction()
118485 ** is a pointer to another function. Specifically, the return value
118486 ** of ftsHashFunction() is a pointer to a function that takes two parameters
118487 ** with types "const void*" and "int" and returns an "int".
118489 static int (*ftsHashFunction(int keyClass))(const void*,int){
118490 if( keyClass==FTS3_HASH_STRING ){
118491 return &fts3StrHash;
118492 }else{
118493 assert( keyClass==FTS3_HASH_BINARY );
118494 return &fts3BinHash;
118499 ** Return a pointer to the appropriate hash function given the key class.
118501 ** For help in interpreted the obscure C code in the function definition,
118502 ** see the header comment on the previous function.
118504 static int (*ftsCompareFunction(int keyClass))(const void*,int,const void*,int){
118505 if( keyClass==FTS3_HASH_STRING ){
118506 return &fts3StrCompare;
118507 }else{
118508 assert( keyClass==FTS3_HASH_BINARY );
118509 return &fts3BinCompare;
118513 /* Link an element into the hash table
118515 static void fts3HashInsertElement(
118516 Fts3Hash *pH, /* The complete hash table */
118517 struct _fts3ht *pEntry, /* The entry into which pNew is inserted */
118518 Fts3HashElem *pNew /* The element to be inserted */
118520 Fts3HashElem *pHead; /* First element already in pEntry */
118521 pHead = pEntry->chain;
118522 if( pHead ){
118523 pNew->next = pHead;
118524 pNew->prev = pHead->prev;
118525 if( pHead->prev ){ pHead->prev->next = pNew; }
118526 else { pH->first = pNew; }
118527 pHead->prev = pNew;
118528 }else{
118529 pNew->next = pH->first;
118530 if( pH->first ){ pH->first->prev = pNew; }
118531 pNew->prev = 0;
118532 pH->first = pNew;
118534 pEntry->count++;
118535 pEntry->chain = pNew;
118539 /* Resize the hash table so that it cantains "new_size" buckets.
118540 ** "new_size" must be a power of 2. The hash table might fail
118541 ** to resize if sqliteMalloc() fails.
118543 ** Return non-zero if a memory allocation error occurs.
118545 static int fts3Rehash(Fts3Hash *pH, int new_size){
118546 struct _fts3ht *new_ht; /* The new hash table */
118547 Fts3HashElem *elem, *next_elem; /* For looping over existing elements */
118548 int (*xHash)(const void*,int); /* The hash function */
118550 assert( (new_size & (new_size-1))==0 );
118551 new_ht = (struct _fts3ht *)fts3HashMalloc( new_size*sizeof(struct _fts3ht) );
118552 if( new_ht==0 ) return 1;
118553 fts3HashFree(pH->ht);
118554 pH->ht = new_ht;
118555 pH->htsize = new_size;
118556 xHash = ftsHashFunction(pH->keyClass);
118557 for(elem=pH->first, pH->first=0; elem; elem = next_elem){
118558 int h = (*xHash)(elem->pKey, elem->nKey) & (new_size-1);
118559 next_elem = elem->next;
118560 fts3HashInsertElement(pH, &new_ht[h], elem);
118562 return 0;
118565 /* This function (for internal use only) locates an element in an
118566 ** hash table that matches the given key. The hash for this key has
118567 ** already been computed and is passed as the 4th parameter.
118569 static Fts3HashElem *fts3FindElementByHash(
118570 const Fts3Hash *pH, /* The pH to be searched */
118571 const void *pKey, /* The key we are searching for */
118572 int nKey,
118573 int h /* The hash for this key. */
118575 Fts3HashElem *elem; /* Used to loop thru the element list */
118576 int count; /* Number of elements left to test */
118577 int (*xCompare)(const void*,int,const void*,int); /* comparison function */
118579 if( pH->ht ){
118580 struct _fts3ht *pEntry = &pH->ht[h];
118581 elem = pEntry->chain;
118582 count = pEntry->count;
118583 xCompare = ftsCompareFunction(pH->keyClass);
118584 while( count-- && elem ){
118585 if( (*xCompare)(elem->pKey,elem->nKey,pKey,nKey)==0 ){
118586 return elem;
118588 elem = elem->next;
118591 return 0;
118594 /* Remove a single entry from the hash table given a pointer to that
118595 ** element and a hash on the element's key.
118597 static void fts3RemoveElementByHash(
118598 Fts3Hash *pH, /* The pH containing "elem" */
118599 Fts3HashElem* elem, /* The element to be removed from the pH */
118600 int h /* Hash value for the element */
118602 struct _fts3ht *pEntry;
118603 if( elem->prev ){
118604 elem->prev->next = elem->next;
118605 }else{
118606 pH->first = elem->next;
118608 if( elem->next ){
118609 elem->next->prev = elem->prev;
118611 pEntry = &pH->ht[h];
118612 if( pEntry->chain==elem ){
118613 pEntry->chain = elem->next;
118615 pEntry->count--;
118616 if( pEntry->count<=0 ){
118617 pEntry->chain = 0;
118619 if( pH->copyKey && elem->pKey ){
118620 fts3HashFree(elem->pKey);
118622 fts3HashFree( elem );
118623 pH->count--;
118624 if( pH->count<=0 ){
118625 assert( pH->first==0 );
118626 assert( pH->count==0 );
118627 fts3HashClear(pH);
118631 SQLITE_PRIVATE Fts3HashElem *sqlite3Fts3HashFindElem(
118632 const Fts3Hash *pH,
118633 const void *pKey,
118634 int nKey
118636 int h; /* A hash on key */
118637 int (*xHash)(const void*,int); /* The hash function */
118639 if( pH==0 || pH->ht==0 ) return 0;
118640 xHash = ftsHashFunction(pH->keyClass);
118641 assert( xHash!=0 );
118642 h = (*xHash)(pKey,nKey);
118643 assert( (pH->htsize & (pH->htsize-1))==0 );
118644 return fts3FindElementByHash(pH,pKey,nKey, h & (pH->htsize-1));
118648 ** Attempt to locate an element of the hash table pH with a key
118649 ** that matches pKey,nKey. Return the data for this element if it is
118650 ** found, or NULL if there is no match.
118652 SQLITE_PRIVATE void *sqlite3Fts3HashFind(const Fts3Hash *pH, const void *pKey, int nKey){
118653 Fts3HashElem *pElem; /* The element that matches key (if any) */
118655 pElem = sqlite3Fts3HashFindElem(pH, pKey, nKey);
118656 return pElem ? pElem->data : 0;
118659 /* Insert an element into the hash table pH. The key is pKey,nKey
118660 ** and the data is "data".
118662 ** If no element exists with a matching key, then a new
118663 ** element is created. A copy of the key is made if the copyKey
118664 ** flag is set. NULL is returned.
118666 ** If another element already exists with the same key, then the
118667 ** new data replaces the old data and the old data is returned.
118668 ** The key is not copied in this instance. If a malloc fails, then
118669 ** the new data is returned and the hash table is unchanged.
118671 ** If the "data" parameter to this function is NULL, then the
118672 ** element corresponding to "key" is removed from the hash table.
118674 SQLITE_PRIVATE void *sqlite3Fts3HashInsert(
118675 Fts3Hash *pH, /* The hash table to insert into */
118676 const void *pKey, /* The key */
118677 int nKey, /* Number of bytes in the key */
118678 void *data /* The data */
118680 int hraw; /* Raw hash value of the key */
118681 int h; /* the hash of the key modulo hash table size */
118682 Fts3HashElem *elem; /* Used to loop thru the element list */
118683 Fts3HashElem *new_elem; /* New element added to the pH */
118684 int (*xHash)(const void*,int); /* The hash function */
118686 assert( pH!=0 );
118687 xHash = ftsHashFunction(pH->keyClass);
118688 assert( xHash!=0 );
118689 hraw = (*xHash)(pKey, nKey);
118690 assert( (pH->htsize & (pH->htsize-1))==0 );
118691 h = hraw & (pH->htsize-1);
118692 elem = fts3FindElementByHash(pH,pKey,nKey,h);
118693 if( elem ){
118694 void *old_data = elem->data;
118695 if( data==0 ){
118696 fts3RemoveElementByHash(pH,elem,h);
118697 }else{
118698 elem->data = data;
118700 return old_data;
118702 if( data==0 ) return 0;
118703 if( (pH->htsize==0 && fts3Rehash(pH,8))
118704 || (pH->count>=pH->htsize && fts3Rehash(pH, pH->htsize*2))
118706 pH->count = 0;
118707 return data;
118709 assert( pH->htsize>0 );
118710 new_elem = (Fts3HashElem*)fts3HashMalloc( sizeof(Fts3HashElem) );
118711 if( new_elem==0 ) return data;
118712 if( pH->copyKey && pKey!=0 ){
118713 new_elem->pKey = fts3HashMalloc( nKey );
118714 if( new_elem->pKey==0 ){
118715 fts3HashFree(new_elem);
118716 return data;
118718 memcpy((void*)new_elem->pKey, pKey, nKey);
118719 }else{
118720 new_elem->pKey = (void*)pKey;
118722 new_elem->nKey = nKey;
118723 pH->count++;
118724 assert( pH->htsize>0 );
118725 assert( (pH->htsize & (pH->htsize-1))==0 );
118726 h = hraw & (pH->htsize-1);
118727 fts3HashInsertElement(pH, &pH->ht[h], new_elem);
118728 new_elem->data = data;
118729 return 0;
118732 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
118734 /************** End of fts3_hash.c *******************************************/
118735 /************** Begin file fts3_porter.c *************************************/
118737 ** 2006 September 30
118739 ** The author disclaims copyright to this source code. In place of
118740 ** a legal notice, here is a blessing:
118742 ** May you do good and not evil.
118743 ** May you find forgiveness for yourself and forgive others.
118744 ** May you share freely, never taking more than you give.
118746 *************************************************************************
118747 ** Implementation of the full-text-search tokenizer that implements
118748 ** a Porter stemmer.
118752 ** The code in this file is only compiled if:
118754 ** * The FTS3 module is being built as an extension
118755 ** (in which case SQLITE_CORE is not defined), or
118757 ** * The FTS3 module is being built into the core of
118758 ** SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
118760 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
118766 ** Class derived from sqlite3_tokenizer
118768 typedef struct porter_tokenizer {
118769 sqlite3_tokenizer base; /* Base class */
118770 } porter_tokenizer;
118773 ** Class derived from sqlit3_tokenizer_cursor
118775 typedef struct porter_tokenizer_cursor {
118776 sqlite3_tokenizer_cursor base;
118777 const char *zInput; /* input we are tokenizing */
118778 int nInput; /* size of the input */
118779 int iOffset; /* current position in zInput */
118780 int iToken; /* index of next token to be returned */
118781 char *zToken; /* storage for current token */
118782 int nAllocated; /* space allocated to zToken buffer */
118783 } porter_tokenizer_cursor;
118787 ** Create a new tokenizer instance.
118789 static int porterCreate(
118790 int argc, const char * const *argv,
118791 sqlite3_tokenizer **ppTokenizer
118793 porter_tokenizer *t;
118795 UNUSED_PARAMETER(argc);
118796 UNUSED_PARAMETER(argv);
118798 t = (porter_tokenizer *) sqlite3_malloc(sizeof(*t));
118799 if( t==NULL ) return SQLITE_NOMEM;
118800 memset(t, 0, sizeof(*t));
118801 *ppTokenizer = &t->base;
118802 return SQLITE_OK;
118806 ** Destroy a tokenizer
118808 static int porterDestroy(sqlite3_tokenizer *pTokenizer){
118809 sqlite3_free(pTokenizer);
118810 return SQLITE_OK;
118814 ** Prepare to begin tokenizing a particular string. The input
118815 ** string to be tokenized is zInput[0..nInput-1]. A cursor
118816 ** used to incrementally tokenize this string is returned in
118817 ** *ppCursor.
118819 static int porterOpen(
118820 sqlite3_tokenizer *pTokenizer, /* The tokenizer */
118821 const char *zInput, int nInput, /* String to be tokenized */
118822 sqlite3_tokenizer_cursor **ppCursor /* OUT: Tokenization cursor */
118824 porter_tokenizer_cursor *c;
118826 UNUSED_PARAMETER(pTokenizer);
118828 c = (porter_tokenizer_cursor *) sqlite3_malloc(sizeof(*c));
118829 if( c==NULL ) return SQLITE_NOMEM;
118831 c->zInput = zInput;
118832 if( zInput==0 ){
118833 c->nInput = 0;
118834 }else if( nInput<0 ){
118835 c->nInput = (int)strlen(zInput);
118836 }else{
118837 c->nInput = nInput;
118839 c->iOffset = 0; /* start tokenizing at the beginning */
118840 c->iToken = 0;
118841 c->zToken = NULL; /* no space allocated, yet. */
118842 c->nAllocated = 0;
118844 *ppCursor = &c->base;
118845 return SQLITE_OK;
118849 ** Close a tokenization cursor previously opened by a call to
118850 ** porterOpen() above.
118852 static int porterClose(sqlite3_tokenizer_cursor *pCursor){
118853 porter_tokenizer_cursor *c = (porter_tokenizer_cursor *) pCursor;
118854 sqlite3_free(c->zToken);
118855 sqlite3_free(c);
118856 return SQLITE_OK;
118859 ** Vowel or consonant
118861 static const char vOrCType[] = {
118862 0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0,
118863 1, 1, 1, 2, 1
118867 ** isConsonant() and isVowel() determine if their first character in
118868 ** the string they point to is a consonant or a vowel, according
118869 ** to Porter ruls.
118871 ** A consonate is any letter other than 'a', 'e', 'i', 'o', or 'u'.
118872 ** 'Y' is a consonant unless it follows another consonant,
118873 ** in which case it is a vowel.
118875 ** In these routine, the letters are in reverse order. So the 'y' rule
118876 ** is that 'y' is a consonant unless it is followed by another
118877 ** consonent.
118879 static int isVowel(const char*);
118880 static int isConsonant(const char *z){
118881 int j;
118882 char x = *z;
118883 if( x==0 ) return 0;
118884 assert( x>='a' && x<='z' );
118885 j = vOrCType[x-'a'];
118886 if( j<2 ) return j;
118887 return z[1]==0 || isVowel(z + 1);
118889 static int isVowel(const char *z){
118890 int j;
118891 char x = *z;
118892 if( x==0 ) return 0;
118893 assert( x>='a' && x<='z' );
118894 j = vOrCType[x-'a'];
118895 if( j<2 ) return 1-j;
118896 return isConsonant(z + 1);
118900 ** Let any sequence of one or more vowels be represented by V and let
118901 ** C be sequence of one or more consonants. Then every word can be
118902 ** represented as:
118904 ** [C] (VC){m} [V]
118906 ** In prose: A word is an optional consonant followed by zero or
118907 ** vowel-consonant pairs followed by an optional vowel. "m" is the
118908 ** number of vowel consonant pairs. This routine computes the value
118909 ** of m for the first i bytes of a word.
118911 ** Return true if the m-value for z is 1 or more. In other words,
118912 ** return true if z contains at least one vowel that is followed
118913 ** by a consonant.
118915 ** In this routine z[] is in reverse order. So we are really looking
118916 ** for an instance of of a consonant followed by a vowel.
118918 static int m_gt_0(const char *z){
118919 while( isVowel(z) ){ z++; }
118920 if( *z==0 ) return 0;
118921 while( isConsonant(z) ){ z++; }
118922 return *z!=0;
118925 /* Like mgt0 above except we are looking for a value of m which is
118926 ** exactly 1
118928 static int m_eq_1(const char *z){
118929 while( isVowel(z) ){ z++; }
118930 if( *z==0 ) return 0;
118931 while( isConsonant(z) ){ z++; }
118932 if( *z==0 ) return 0;
118933 while( isVowel(z) ){ z++; }
118934 if( *z==0 ) return 1;
118935 while( isConsonant(z) ){ z++; }
118936 return *z==0;
118939 /* Like mgt0 above except we are looking for a value of m>1 instead
118940 ** or m>0
118942 static int m_gt_1(const char *z){
118943 while( isVowel(z) ){ z++; }
118944 if( *z==0 ) return 0;
118945 while( isConsonant(z) ){ z++; }
118946 if( *z==0 ) return 0;
118947 while( isVowel(z) ){ z++; }
118948 if( *z==0 ) return 0;
118949 while( isConsonant(z) ){ z++; }
118950 return *z!=0;
118954 ** Return TRUE if there is a vowel anywhere within z[0..n-1]
118956 static int hasVowel(const char *z){
118957 while( isConsonant(z) ){ z++; }
118958 return *z!=0;
118962 ** Return TRUE if the word ends in a double consonant.
118964 ** The text is reversed here. So we are really looking at
118965 ** the first two characters of z[].
118967 static int doubleConsonant(const char *z){
118968 return isConsonant(z) && z[0]==z[1];
118972 ** Return TRUE if the word ends with three letters which
118973 ** are consonant-vowel-consonent and where the final consonant
118974 ** is not 'w', 'x', or 'y'.
118976 ** The word is reversed here. So we are really checking the
118977 ** first three letters and the first one cannot be in [wxy].
118979 static int star_oh(const char *z){
118980 return
118981 isConsonant(z) &&
118982 z[0]!='w' && z[0]!='x' && z[0]!='y' &&
118983 isVowel(z+1) &&
118984 isConsonant(z+2);
118988 ** If the word ends with zFrom and xCond() is true for the stem
118989 ** of the word that preceeds the zFrom ending, then change the
118990 ** ending to zTo.
118992 ** The input word *pz and zFrom are both in reverse order. zTo
118993 ** is in normal order.
118995 ** Return TRUE if zFrom matches. Return FALSE if zFrom does not
118996 ** match. Not that TRUE is returned even if xCond() fails and
118997 ** no substitution occurs.
118999 static int stem(
119000 char **pz, /* The word being stemmed (Reversed) */
119001 const char *zFrom, /* If the ending matches this... (Reversed) */
119002 const char *zTo, /* ... change the ending to this (not reversed) */
119003 int (*xCond)(const char*) /* Condition that must be true */
119005 char *z = *pz;
119006 while( *zFrom && *zFrom==*z ){ z++; zFrom++; }
119007 if( *zFrom!=0 ) return 0;
119008 if( xCond && !xCond(z) ) return 1;
119009 while( *zTo ){
119010 *(--z) = *(zTo++);
119012 *pz = z;
119013 return 1;
119017 ** This is the fallback stemmer used when the porter stemmer is
119018 ** inappropriate. The input word is copied into the output with
119019 ** US-ASCII case folding. If the input word is too long (more
119020 ** than 20 bytes if it contains no digits or more than 6 bytes if
119021 ** it contains digits) then word is truncated to 20 or 6 bytes
119022 ** by taking 10 or 3 bytes from the beginning and end.
119024 static void copy_stemmer(const char *zIn, int nIn, char *zOut, int *pnOut){
119025 int i, mx, j;
119026 int hasDigit = 0;
119027 for(i=0; i<nIn; i++){
119028 char c = zIn[i];
119029 if( c>='A' && c<='Z' ){
119030 zOut[i] = c - 'A' + 'a';
119031 }else{
119032 if( c>='0' && c<='9' ) hasDigit = 1;
119033 zOut[i] = c;
119036 mx = hasDigit ? 3 : 10;
119037 if( nIn>mx*2 ){
119038 for(j=mx, i=nIn-mx; i<nIn; i++, j++){
119039 zOut[j] = zOut[i];
119041 i = j;
119043 zOut[i] = 0;
119044 *pnOut = i;
119049 ** Stem the input word zIn[0..nIn-1]. Store the output in zOut.
119050 ** zOut is at least big enough to hold nIn bytes. Write the actual
119051 ** size of the output word (exclusive of the '\0' terminator) into *pnOut.
119053 ** Any upper-case characters in the US-ASCII character set ([A-Z])
119054 ** are converted to lower case. Upper-case UTF characters are
119055 ** unchanged.
119057 ** Words that are longer than about 20 bytes are stemmed by retaining
119058 ** a few bytes from the beginning and the end of the word. If the
119059 ** word contains digits, 3 bytes are taken from the beginning and
119060 ** 3 bytes from the end. For long words without digits, 10 bytes
119061 ** are taken from each end. US-ASCII case folding still applies.
119063 ** If the input word contains not digits but does characters not
119064 ** in [a-zA-Z] then no stemming is attempted and this routine just
119065 ** copies the input into the input into the output with US-ASCII
119066 ** case folding.
119068 ** Stemming never increases the length of the word. So there is
119069 ** no chance of overflowing the zOut buffer.
119071 static void porter_stemmer(const char *zIn, int nIn, char *zOut, int *pnOut){
119072 int i, j;
119073 char zReverse[28];
119074 char *z, *z2;
119075 if( nIn<3 || nIn>=(int)sizeof(zReverse)-7 ){
119076 /* The word is too big or too small for the porter stemmer.
119077 ** Fallback to the copy stemmer */
119078 copy_stemmer(zIn, nIn, zOut, pnOut);
119079 return;
119081 for(i=0, j=sizeof(zReverse)-6; i<nIn; i++, j--){
119082 char c = zIn[i];
119083 if( c>='A' && c<='Z' ){
119084 zReverse[j] = c + 'a' - 'A';
119085 }else if( c>='a' && c<='z' ){
119086 zReverse[j] = c;
119087 }else{
119088 /* The use of a character not in [a-zA-Z] means that we fallback
119089 ** to the copy stemmer */
119090 copy_stemmer(zIn, nIn, zOut, pnOut);
119091 return;
119094 memset(&zReverse[sizeof(zReverse)-5], 0, 5);
119095 z = &zReverse[j+1];
119098 /* Step 1a */
119099 if( z[0]=='s' ){
119101 !stem(&z, "sess", "ss", 0) &&
119102 !stem(&z, "sei", "i", 0) &&
119103 !stem(&z, "ss", "ss", 0)
119109 /* Step 1b */
119110 z2 = z;
119111 if( stem(&z, "dee", "ee", m_gt_0) ){
119112 /* Do nothing. The work was all in the test */
119113 }else if(
119114 (stem(&z, "gni", "", hasVowel) || stem(&z, "de", "", hasVowel))
119115 && z!=z2
119117 if( stem(&z, "ta", "ate", 0) ||
119118 stem(&z, "lb", "ble", 0) ||
119119 stem(&z, "zi", "ize", 0) ){
119120 /* Do nothing. The work was all in the test */
119121 }else if( doubleConsonant(z) && (*z!='l' && *z!='s' && *z!='z') ){
119123 }else if( m_eq_1(z) && star_oh(z) ){
119124 *(--z) = 'e';
119128 /* Step 1c */
119129 if( z[0]=='y' && hasVowel(z+1) ){
119130 z[0] = 'i';
119133 /* Step 2 */
119134 switch( z[1] ){
119135 case 'a':
119136 stem(&z, "lanoita", "ate", m_gt_0) ||
119137 stem(&z, "lanoit", "tion", m_gt_0);
119138 break;
119139 case 'c':
119140 stem(&z, "icne", "ence", m_gt_0) ||
119141 stem(&z, "icna", "ance", m_gt_0);
119142 break;
119143 case 'e':
119144 stem(&z, "rezi", "ize", m_gt_0);
119145 break;
119146 case 'g':
119147 stem(&z, "igol", "log", m_gt_0);
119148 break;
119149 case 'l':
119150 stem(&z, "ilb", "ble", m_gt_0) ||
119151 stem(&z, "illa", "al", m_gt_0) ||
119152 stem(&z, "iltne", "ent", m_gt_0) ||
119153 stem(&z, "ile", "e", m_gt_0) ||
119154 stem(&z, "ilsuo", "ous", m_gt_0);
119155 break;
119156 case 'o':
119157 stem(&z, "noitazi", "ize", m_gt_0) ||
119158 stem(&z, "noita", "ate", m_gt_0) ||
119159 stem(&z, "rota", "ate", m_gt_0);
119160 break;
119161 case 's':
119162 stem(&z, "msila", "al", m_gt_0) ||
119163 stem(&z, "ssenevi", "ive", m_gt_0) ||
119164 stem(&z, "ssenluf", "ful", m_gt_0) ||
119165 stem(&z, "ssensuo", "ous", m_gt_0);
119166 break;
119167 case 't':
119168 stem(&z, "itila", "al", m_gt_0) ||
119169 stem(&z, "itivi", "ive", m_gt_0) ||
119170 stem(&z, "itilib", "ble", m_gt_0);
119171 break;
119174 /* Step 3 */
119175 switch( z[0] ){
119176 case 'e':
119177 stem(&z, "etaci", "ic", m_gt_0) ||
119178 stem(&z, "evita", "", m_gt_0) ||
119179 stem(&z, "ezila", "al", m_gt_0);
119180 break;
119181 case 'i':
119182 stem(&z, "itici", "ic", m_gt_0);
119183 break;
119184 case 'l':
119185 stem(&z, "laci", "ic", m_gt_0) ||
119186 stem(&z, "luf", "", m_gt_0);
119187 break;
119188 case 's':
119189 stem(&z, "ssen", "", m_gt_0);
119190 break;
119193 /* Step 4 */
119194 switch( z[1] ){
119195 case 'a':
119196 if( z[0]=='l' && m_gt_1(z+2) ){
119197 z += 2;
119199 break;
119200 case 'c':
119201 if( z[0]=='e' && z[2]=='n' && (z[3]=='a' || z[3]=='e') && m_gt_1(z+4) ){
119202 z += 4;
119204 break;
119205 case 'e':
119206 if( z[0]=='r' && m_gt_1(z+2) ){
119207 z += 2;
119209 break;
119210 case 'i':
119211 if( z[0]=='c' && m_gt_1(z+2) ){
119212 z += 2;
119214 break;
119215 case 'l':
119216 if( z[0]=='e' && z[2]=='b' && (z[3]=='a' || z[3]=='i') && m_gt_1(z+4) ){
119217 z += 4;
119219 break;
119220 case 'n':
119221 if( z[0]=='t' ){
119222 if( z[2]=='a' ){
119223 if( m_gt_1(z+3) ){
119224 z += 3;
119226 }else if( z[2]=='e' ){
119227 stem(&z, "tneme", "", m_gt_1) ||
119228 stem(&z, "tnem", "", m_gt_1) ||
119229 stem(&z, "tne", "", m_gt_1);
119232 break;
119233 case 'o':
119234 if( z[0]=='u' ){
119235 if( m_gt_1(z+2) ){
119236 z += 2;
119238 }else if( z[3]=='s' || z[3]=='t' ){
119239 stem(&z, "noi", "", m_gt_1);
119241 break;
119242 case 's':
119243 if( z[0]=='m' && z[2]=='i' && m_gt_1(z+3) ){
119244 z += 3;
119246 break;
119247 case 't':
119248 stem(&z, "eta", "", m_gt_1) ||
119249 stem(&z, "iti", "", m_gt_1);
119250 break;
119251 case 'u':
119252 if( z[0]=='s' && z[2]=='o' && m_gt_1(z+3) ){
119253 z += 3;
119255 break;
119256 case 'v':
119257 case 'z':
119258 if( z[0]=='e' && z[2]=='i' && m_gt_1(z+3) ){
119259 z += 3;
119261 break;
119264 /* Step 5a */
119265 if( z[0]=='e' ){
119266 if( m_gt_1(z+1) ){
119268 }else if( m_eq_1(z+1) && !star_oh(z+1) ){
119273 /* Step 5b */
119274 if( m_gt_1(z) && z[0]=='l' && z[1]=='l' ){
119278 /* z[] is now the stemmed word in reverse order. Flip it back
119279 ** around into forward order and return.
119281 *pnOut = i = (int)strlen(z);
119282 zOut[i] = 0;
119283 while( *z ){
119284 zOut[--i] = *(z++);
119289 ** Characters that can be part of a token. We assume any character
119290 ** whose value is greater than 0x80 (any UTF character) can be
119291 ** part of a token. In other words, delimiters all must have
119292 ** values of 0x7f or lower.
119294 static const char porterIdChar[] = {
119295 /* x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 xA xB xC xD xE xF */
119296 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, /* 3x */
119297 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 4x */
119298 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, /* 5x */
119299 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 6x */
119300 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, /* 7x */
119302 #define isDelim(C) (((ch=C)&0x80)==0 && (ch<0x30 || !porterIdChar[ch-0x30]))
119305 ** Extract the next token from a tokenization cursor. The cursor must
119306 ** have been opened by a prior call to porterOpen().
119308 static int porterNext(
119309 sqlite3_tokenizer_cursor *pCursor, /* Cursor returned by porterOpen */
119310 const char **pzToken, /* OUT: *pzToken is the token text */
119311 int *pnBytes, /* OUT: Number of bytes in token */
119312 int *piStartOffset, /* OUT: Starting offset of token */
119313 int *piEndOffset, /* OUT: Ending offset of token */
119314 int *piPosition /* OUT: Position integer of token */
119316 porter_tokenizer_cursor *c = (porter_tokenizer_cursor *) pCursor;
119317 const char *z = c->zInput;
119319 while( c->iOffset<c->nInput ){
119320 int iStartOffset, ch;
119322 /* Scan past delimiter characters */
119323 while( c->iOffset<c->nInput && isDelim(z[c->iOffset]) ){
119324 c->iOffset++;
119327 /* Count non-delimiter characters. */
119328 iStartOffset = c->iOffset;
119329 while( c->iOffset<c->nInput && !isDelim(z[c->iOffset]) ){
119330 c->iOffset++;
119333 if( c->iOffset>iStartOffset ){
119334 int n = c->iOffset-iStartOffset;
119335 if( n>c->nAllocated ){
119336 char *pNew;
119337 c->nAllocated = n+20;
119338 pNew = sqlite3_realloc(c->zToken, c->nAllocated);
119339 if( !pNew ) return SQLITE_NOMEM;
119340 c->zToken = pNew;
119342 porter_stemmer(&z[iStartOffset], n, c->zToken, pnBytes);
119343 *pzToken = c->zToken;
119344 *piStartOffset = iStartOffset;
119345 *piEndOffset = c->iOffset;
119346 *piPosition = c->iToken++;
119347 return SQLITE_OK;
119350 return SQLITE_DONE;
119354 ** The set of routines that implement the porter-stemmer tokenizer
119356 static const sqlite3_tokenizer_module porterTokenizerModule = {
119358 porterCreate,
119359 porterDestroy,
119360 porterOpen,
119361 porterClose,
119362 porterNext,
119366 ** Allocate a new porter tokenizer. Return a pointer to the new
119367 ** tokenizer in *ppModule
119369 SQLITE_PRIVATE void sqlite3Fts3PorterTokenizerModule(
119370 sqlite3_tokenizer_module const**ppModule
119372 *ppModule = &porterTokenizerModule;
119375 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
119377 /************** End of fts3_porter.c *****************************************/
119378 /************** Begin file fts3_tokenizer.c **********************************/
119380 ** 2007 June 22
119382 ** The author disclaims copyright to this source code. In place of
119383 ** a legal notice, here is a blessing:
119385 ** May you do good and not evil.
119386 ** May you find forgiveness for yourself and forgive others.
119387 ** May you share freely, never taking more than you give.
119389 ******************************************************************************
119391 ** This is part of an SQLite module implementing full-text search.
119392 ** This particular file implements the generic tokenizer interface.
119396 ** The code in this file is only compiled if:
119398 ** * The FTS3 module is being built as an extension
119399 ** (in which case SQLITE_CORE is not defined), or
119401 ** * The FTS3 module is being built into the core of
119402 ** SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
119404 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
119406 #ifndef SQLITE_CORE
119407 SQLITE_EXTENSION_INIT1
119408 #endif
119412 ** Implementation of the SQL scalar function for accessing the underlying
119413 ** hash table. This function may be called as follows:
119415 ** SELECT <function-name>(<key-name>);
119416 ** SELECT <function-name>(<key-name>, <pointer>);
119418 ** where <function-name> is the name passed as the second argument
119419 ** to the sqlite3Fts3InitHashTable() function (e.g. 'fts3_tokenizer').
119421 ** If the <pointer> argument is specified, it must be a blob value
119422 ** containing a pointer to be stored as the hash data corresponding
119423 ** to the string <key-name>. If <pointer> is not specified, then
119424 ** the string <key-name> must already exist in the has table. Otherwise,
119425 ** an error is returned.
119427 ** Whether or not the <pointer> argument is specified, the value returned
119428 ** is a blob containing the pointer stored as the hash data corresponding
119429 ** to string <key-name> (after the hash-table is updated, if applicable).
119431 static void scalarFunc(
119432 sqlite3_context *context,
119433 int argc,
119434 sqlite3_value **argv
119436 Fts3Hash *pHash;
119437 void *pPtr = 0;
119438 const unsigned char *zName;
119439 int nName;
119441 assert( argc==1 || argc==2 );
119443 pHash = (Fts3Hash *)sqlite3_user_data(context);
119445 zName = sqlite3_value_text(argv[0]);
119446 nName = sqlite3_value_bytes(argv[0])+1;
119448 if( argc==2 ){
119449 void *pOld;
119450 int n = sqlite3_value_bytes(argv[1]);
119451 if( n!=sizeof(pPtr) ){
119452 sqlite3_result_error(context, "argument type mismatch", -1);
119453 return;
119455 pPtr = *(void **)sqlite3_value_blob(argv[1]);
119456 pOld = sqlite3Fts3HashInsert(pHash, (void *)zName, nName, pPtr);
119457 if( pOld==pPtr ){
119458 sqlite3_result_error(context, "out of memory", -1);
119459 return;
119461 }else{
119462 pPtr = sqlite3Fts3HashFind(pHash, zName, nName);
119463 if( !pPtr ){
119464 char *zErr = sqlite3_mprintf("unknown tokenizer: %s", zName);
119465 sqlite3_result_error(context, zErr, -1);
119466 sqlite3_free(zErr);
119467 return;
119471 sqlite3_result_blob(context, (void *)&pPtr, sizeof(pPtr), SQLITE_TRANSIENT);
119474 SQLITE_PRIVATE int sqlite3Fts3IsIdChar(char c){
119475 static const char isFtsIdChar[] = {
119476 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0x */
119477 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 1x */
119478 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 2x */
119479 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, /* 3x */
119480 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 4x */
119481 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, /* 5x */
119482 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 6x */
119483 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, /* 7x */
119485 return (c&0x80 || isFtsIdChar[(int)(c)]);
119488 SQLITE_PRIVATE const char *sqlite3Fts3NextToken(const char *zStr, int *pn){
119489 const char *z1;
119490 const char *z2 = 0;
119492 /* Find the start of the next token. */
119493 z1 = zStr;
119494 while( z2==0 ){
119495 char c = *z1;
119496 switch( c ){
119497 case '\0': return 0; /* No more tokens here */
119498 case '\'':
119499 case '"':
119500 case '`': {
119501 z2 = z1;
119502 while( *++z2 && (*z2!=c || *++z2==c) );
119503 break;
119505 case '[':
119506 z2 = &z1[1];
119507 while( *z2 && z2[0]!=']' ) z2++;
119508 if( *z2 ) z2++;
119509 break;
119511 default:
119512 if( sqlite3Fts3IsIdChar(*z1) ){
119513 z2 = &z1[1];
119514 while( sqlite3Fts3IsIdChar(*z2) ) z2++;
119515 }else{
119516 z1++;
119521 *pn = (int)(z2-z1);
119522 return z1;
119525 SQLITE_PRIVATE int sqlite3Fts3InitTokenizer(
119526 Fts3Hash *pHash, /* Tokenizer hash table */
119527 const char *zArg, /* Tokenizer name */
119528 sqlite3_tokenizer **ppTok, /* OUT: Tokenizer (if applicable) */
119529 char **pzErr /* OUT: Set to malloced error message */
119531 int rc;
119532 char *z = (char *)zArg;
119533 int n;
119534 char *zCopy;
119535 char *zEnd; /* Pointer to nul-term of zCopy */
119536 sqlite3_tokenizer_module *m;
119538 zCopy = sqlite3_mprintf("%s", zArg);
119539 if( !zCopy ) return SQLITE_NOMEM;
119540 zEnd = &zCopy[strlen(zCopy)];
119542 z = (char *)sqlite3Fts3NextToken(zCopy, &n);
119543 z[n] = '\0';
119544 sqlite3Fts3Dequote(z);
119546 m = (sqlite3_tokenizer_module *)sqlite3Fts3HashFind(pHash,z,(int)strlen(z)+1);
119547 if( !m ){
119548 *pzErr = sqlite3_mprintf("unknown tokenizer: %s", z);
119549 rc = SQLITE_ERROR;
119550 }else{
119551 char const **aArg = 0;
119552 int iArg = 0;
119553 z = &z[n+1];
119554 while( z<zEnd && (NULL!=(z = (char *)sqlite3Fts3NextToken(z, &n))) ){
119555 int nNew = sizeof(char *)*(iArg+1);
119556 char const **aNew = (const char **)sqlite3_realloc((void *)aArg, nNew);
119557 if( !aNew ){
119558 sqlite3_free(zCopy);
119559 sqlite3_free((void *)aArg);
119560 return SQLITE_NOMEM;
119562 aArg = aNew;
119563 aArg[iArg++] = z;
119564 z[n] = '\0';
119565 sqlite3Fts3Dequote(z);
119566 z = &z[n+1];
119568 rc = m->xCreate(iArg, aArg, ppTok);
119569 assert( rc!=SQLITE_OK || *ppTok );
119570 if( rc!=SQLITE_OK ){
119571 *pzErr = sqlite3_mprintf("unknown tokenizer");
119572 }else{
119573 (*ppTok)->pModule = m;
119575 sqlite3_free((void *)aArg);
119578 sqlite3_free(zCopy);
119579 return rc;
119583 #ifdef SQLITE_TEST
119587 ** Implementation of a special SQL scalar function for testing tokenizers
119588 ** designed to be used in concert with the Tcl testing framework. This
119589 ** function must be called with two arguments:
119591 ** SELECT <function-name>(<key-name>, <input-string>);
119592 ** SELECT <function-name>(<key-name>, <pointer>);
119594 ** where <function-name> is the name passed as the second argument
119595 ** to the sqlite3Fts3InitHashTable() function (e.g. 'fts3_tokenizer')
119596 ** concatenated with the string '_test' (e.g. 'fts3_tokenizer_test').
119598 ** The return value is a string that may be interpreted as a Tcl
119599 ** list. For each token in the <input-string>, three elements are
119600 ** added to the returned list. The first is the token position, the
119601 ** second is the token text (folded, stemmed, etc.) and the third is the
119602 ** substring of <input-string> associated with the token. For example,
119603 ** using the built-in "simple" tokenizer:
119605 ** SELECT fts_tokenizer_test('simple', 'I don't see how');
119607 ** will return the string:
119609 ** "{0 i I 1 dont don't 2 see see 3 how how}"
119612 static void testFunc(
119613 sqlite3_context *context,
119614 int argc,
119615 sqlite3_value **argv
119617 Fts3Hash *pHash;
119618 sqlite3_tokenizer_module *p;
119619 sqlite3_tokenizer *pTokenizer = 0;
119620 sqlite3_tokenizer_cursor *pCsr = 0;
119622 const char *zErr = 0;
119624 const char *zName;
119625 int nName;
119626 const char *zInput;
119627 int nInput;
119629 const char *zArg = 0;
119631 const char *zToken;
119632 int nToken;
119633 int iStart;
119634 int iEnd;
119635 int iPos;
119637 Tcl_Obj *pRet;
119639 assert( argc==2 || argc==3 );
119641 nName = sqlite3_value_bytes(argv[0]);
119642 zName = (const char *)sqlite3_value_text(argv[0]);
119643 nInput = sqlite3_value_bytes(argv[argc-1]);
119644 zInput = (const char *)sqlite3_value_text(argv[argc-1]);
119646 if( argc==3 ){
119647 zArg = (const char *)sqlite3_value_text(argv[1]);
119650 pHash = (Fts3Hash *)sqlite3_user_data(context);
119651 p = (sqlite3_tokenizer_module *)sqlite3Fts3HashFind(pHash, zName, nName+1);
119653 if( !p ){
119654 char *zErr = sqlite3_mprintf("unknown tokenizer: %s", zName);
119655 sqlite3_result_error(context, zErr, -1);
119656 sqlite3_free(zErr);
119657 return;
119660 pRet = Tcl_NewObj();
119661 Tcl_IncrRefCount(pRet);
119663 if( SQLITE_OK!=p->xCreate(zArg ? 1 : 0, &zArg, &pTokenizer) ){
119664 zErr = "error in xCreate()";
119665 goto finish;
119667 pTokenizer->pModule = p;
119668 if( SQLITE_OK!=p->xOpen(pTokenizer, zInput, nInput, &pCsr) ){
119669 zErr = "error in xOpen()";
119670 goto finish;
119672 pCsr->pTokenizer = pTokenizer;
119674 while( SQLITE_OK==p->xNext(pCsr, &zToken, &nToken, &iStart, &iEnd, &iPos) ){
119675 Tcl_ListObjAppendElement(0, pRet, Tcl_NewIntObj(iPos));
119676 Tcl_ListObjAppendElement(0, pRet, Tcl_NewStringObj(zToken, nToken));
119677 zToken = &zInput[iStart];
119678 nToken = iEnd-iStart;
119679 Tcl_ListObjAppendElement(0, pRet, Tcl_NewStringObj(zToken, nToken));
119682 if( SQLITE_OK!=p->xClose(pCsr) ){
119683 zErr = "error in xClose()";
119684 goto finish;
119686 if( SQLITE_OK!=p->xDestroy(pTokenizer) ){
119687 zErr = "error in xDestroy()";
119688 goto finish;
119691 finish:
119692 if( zErr ){
119693 sqlite3_result_error(context, zErr, -1);
119694 }else{
119695 sqlite3_result_text(context, Tcl_GetString(pRet), -1, SQLITE_TRANSIENT);
119697 Tcl_DecrRefCount(pRet);
119700 static
119701 int registerTokenizer(
119702 sqlite3 *db,
119703 char *zName,
119704 const sqlite3_tokenizer_module *p
119706 int rc;
119707 sqlite3_stmt *pStmt;
119708 const char zSql[] = "SELECT fts3_tokenizer(?, ?)";
119710 rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
119711 if( rc!=SQLITE_OK ){
119712 return rc;
119715 sqlite3_bind_text(pStmt, 1, zName, -1, SQLITE_STATIC);
119716 sqlite3_bind_blob(pStmt, 2, &p, sizeof(p), SQLITE_STATIC);
119717 sqlite3_step(pStmt);
119719 return sqlite3_finalize(pStmt);
119722 static
119723 int queryTokenizer(
119724 sqlite3 *db,
119725 char *zName,
119726 const sqlite3_tokenizer_module **pp
119728 int rc;
119729 sqlite3_stmt *pStmt;
119730 const char zSql[] = "SELECT fts3_tokenizer(?)";
119732 *pp = 0;
119733 rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
119734 if( rc!=SQLITE_OK ){
119735 return rc;
119738 sqlite3_bind_text(pStmt, 1, zName, -1, SQLITE_STATIC);
119739 if( SQLITE_ROW==sqlite3_step(pStmt) ){
119740 if( sqlite3_column_type(pStmt, 0)==SQLITE_BLOB ){
119741 memcpy((void *)pp, sqlite3_column_blob(pStmt, 0), sizeof(*pp));
119745 return sqlite3_finalize(pStmt);
119748 SQLITE_PRIVATE void sqlite3Fts3SimpleTokenizerModule(sqlite3_tokenizer_module const**ppModule);
119751 ** Implementation of the scalar function fts3_tokenizer_internal_test().
119752 ** This function is used for testing only, it is not included in the
119753 ** build unless SQLITE_TEST is defined.
119755 ** The purpose of this is to test that the fts3_tokenizer() function
119756 ** can be used as designed by the C-code in the queryTokenizer and
119757 ** registerTokenizer() functions above. These two functions are repeated
119758 ** in the README.tokenizer file as an example, so it is important to
119759 ** test them.
119761 ** To run the tests, evaluate the fts3_tokenizer_internal_test() scalar
119762 ** function with no arguments. An assert() will fail if a problem is
119763 ** detected. i.e.:
119765 ** SELECT fts3_tokenizer_internal_test();
119768 static void intTestFunc(
119769 sqlite3_context *context,
119770 int argc,
119771 sqlite3_value **argv
119773 int rc;
119774 const sqlite3_tokenizer_module *p1;
119775 const sqlite3_tokenizer_module *p2;
119776 sqlite3 *db = (sqlite3 *)sqlite3_user_data(context);
119778 UNUSED_PARAMETER(argc);
119779 UNUSED_PARAMETER(argv);
119781 /* Test the query function */
119782 sqlite3Fts3SimpleTokenizerModule(&p1);
119783 rc = queryTokenizer(db, "simple", &p2);
119784 assert( rc==SQLITE_OK );
119785 assert( p1==p2 );
119786 rc = queryTokenizer(db, "nosuchtokenizer", &p2);
119787 assert( rc==SQLITE_ERROR );
119788 assert( p2==0 );
119789 assert( 0==strcmp(sqlite3_errmsg(db), "unknown tokenizer: nosuchtokenizer") );
119791 /* Test the storage function */
119792 rc = registerTokenizer(db, "nosuchtokenizer", p1);
119793 assert( rc==SQLITE_OK );
119794 rc = queryTokenizer(db, "nosuchtokenizer", &p2);
119795 assert( rc==SQLITE_OK );
119796 assert( p2==p1 );
119798 sqlite3_result_text(context, "ok", -1, SQLITE_STATIC);
119801 #endif
119804 ** Set up SQL objects in database db used to access the contents of
119805 ** the hash table pointed to by argument pHash. The hash table must
119806 ** been initialised to use string keys, and to take a private copy
119807 ** of the key when a value is inserted. i.e. by a call similar to:
119809 ** sqlite3Fts3HashInit(pHash, FTS3_HASH_STRING, 1);
119811 ** This function adds a scalar function (see header comment above
119812 ** scalarFunc() in this file for details) and, if ENABLE_TABLE is
119813 ** defined at compilation time, a temporary virtual table (see header
119814 ** comment above struct HashTableVtab) to the database schema. Both
119815 ** provide read/write access to the contents of *pHash.
119817 ** The third argument to this function, zName, is used as the name
119818 ** of both the scalar and, if created, the virtual table.
119820 SQLITE_PRIVATE int sqlite3Fts3InitHashTable(
119821 sqlite3 *db,
119822 Fts3Hash *pHash,
119823 const char *zName
119825 int rc = SQLITE_OK;
119826 void *p = (void *)pHash;
119827 const int any = SQLITE_ANY;
119829 #ifdef SQLITE_TEST
119830 char *zTest = 0;
119831 char *zTest2 = 0;
119832 void *pdb = (void *)db;
119833 zTest = sqlite3_mprintf("%s_test", zName);
119834 zTest2 = sqlite3_mprintf("%s_internal_test", zName);
119835 if( !zTest || !zTest2 ){
119836 rc = SQLITE_NOMEM;
119838 #endif
119840 if( SQLITE_OK==rc ){
119841 rc = sqlite3_create_function(db, zName, 1, any, p, scalarFunc, 0, 0);
119843 if( SQLITE_OK==rc ){
119844 rc = sqlite3_create_function(db, zName, 2, any, p, scalarFunc, 0, 0);
119846 #ifdef SQLITE_TEST
119847 if( SQLITE_OK==rc ){
119848 rc = sqlite3_create_function(db, zTest, 2, any, p, testFunc, 0, 0);
119850 if( SQLITE_OK==rc ){
119851 rc = sqlite3_create_function(db, zTest, 3, any, p, testFunc, 0, 0);
119853 if( SQLITE_OK==rc ){
119854 rc = sqlite3_create_function(db, zTest2, 0, any, pdb, intTestFunc, 0, 0);
119856 #endif
119858 #ifdef SQLITE_TEST
119859 sqlite3_free(zTest);
119860 sqlite3_free(zTest2);
119861 #endif
119863 return rc;
119866 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
119868 /************** End of fts3_tokenizer.c **************************************/
119869 /************** Begin file fts3_tokenizer1.c *********************************/
119871 ** 2006 Oct 10
119873 ** The author disclaims copyright to this source code. In place of
119874 ** a legal notice, here is a blessing:
119876 ** May you do good and not evil.
119877 ** May you find forgiveness for yourself and forgive others.
119878 ** May you share freely, never taking more than you give.
119880 ******************************************************************************
119882 ** Implementation of the "simple" full-text-search tokenizer.
119886 ** The code in this file is only compiled if:
119888 ** * The FTS3 module is being built as an extension
119889 ** (in which case SQLITE_CORE is not defined), or
119891 ** * The FTS3 module is being built into the core of
119892 ** SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
119894 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
119899 typedef struct simple_tokenizer {
119900 sqlite3_tokenizer base;
119901 char delim[128]; /* flag ASCII delimiters */
119902 } simple_tokenizer;
119904 typedef struct simple_tokenizer_cursor {
119905 sqlite3_tokenizer_cursor base;
119906 const char *pInput; /* input we are tokenizing */
119907 int nBytes; /* size of the input */
119908 int iOffset; /* current position in pInput */
119909 int iToken; /* index of next token to be returned */
119910 char *pToken; /* storage for current token */
119911 int nTokenAllocated; /* space allocated to zToken buffer */
119912 } simple_tokenizer_cursor;
119915 static int simpleDelim(simple_tokenizer *t, unsigned char c){
119916 return c<0x80 && t->delim[c];
119918 static int fts3_isalnum(int x){
119919 return (x>='0' && x<='9') || (x>='A' && x<='Z') || (x>='a' && x<='z');
119923 ** Create a new tokenizer instance.
119925 static int simpleCreate(
119926 int argc, const char * const *argv,
119927 sqlite3_tokenizer **ppTokenizer
119929 simple_tokenizer *t;
119931 t = (simple_tokenizer *) sqlite3_malloc(sizeof(*t));
119932 if( t==NULL ) return SQLITE_NOMEM;
119933 memset(t, 0, sizeof(*t));
119935 /* TODO(shess) Delimiters need to remain the same from run to run,
119936 ** else we need to reindex. One solution would be a meta-table to
119937 ** track such information in the database, then we'd only want this
119938 ** information on the initial create.
119940 if( argc>1 ){
119941 int i, n = (int)strlen(argv[1]);
119942 for(i=0; i<n; i++){
119943 unsigned char ch = argv[1][i];
119944 /* We explicitly don't support UTF-8 delimiters for now. */
119945 if( ch>=0x80 ){
119946 sqlite3_free(t);
119947 return SQLITE_ERROR;
119949 t->delim[ch] = 1;
119951 } else {
119952 /* Mark non-alphanumeric ASCII characters as delimiters */
119953 int i;
119954 for(i=1; i<0x80; i++){
119955 t->delim[i] = !fts3_isalnum(i) ? -1 : 0;
119959 *ppTokenizer = &t->base;
119960 return SQLITE_OK;
119964 ** Destroy a tokenizer
119966 static int simpleDestroy(sqlite3_tokenizer *pTokenizer){
119967 sqlite3_free(pTokenizer);
119968 return SQLITE_OK;
119972 ** Prepare to begin tokenizing a particular string. The input
119973 ** string to be tokenized is pInput[0..nBytes-1]. A cursor
119974 ** used to incrementally tokenize this string is returned in
119975 ** *ppCursor.
119977 static int simpleOpen(
119978 sqlite3_tokenizer *pTokenizer, /* The tokenizer */
119979 const char *pInput, int nBytes, /* String to be tokenized */
119980 sqlite3_tokenizer_cursor **ppCursor /* OUT: Tokenization cursor */
119982 simple_tokenizer_cursor *c;
119984 UNUSED_PARAMETER(pTokenizer);
119986 c = (simple_tokenizer_cursor *) sqlite3_malloc(sizeof(*c));
119987 if( c==NULL ) return SQLITE_NOMEM;
119989 c->pInput = pInput;
119990 if( pInput==0 ){
119991 c->nBytes = 0;
119992 }else if( nBytes<0 ){
119993 c->nBytes = (int)strlen(pInput);
119994 }else{
119995 c->nBytes = nBytes;
119997 c->iOffset = 0; /* start tokenizing at the beginning */
119998 c->iToken = 0;
119999 c->pToken = NULL; /* no space allocated, yet. */
120000 c->nTokenAllocated = 0;
120002 *ppCursor = &c->base;
120003 return SQLITE_OK;
120007 ** Close a tokenization cursor previously opened by a call to
120008 ** simpleOpen() above.
120010 static int simpleClose(sqlite3_tokenizer_cursor *pCursor){
120011 simple_tokenizer_cursor *c = (simple_tokenizer_cursor *) pCursor;
120012 sqlite3_free(c->pToken);
120013 sqlite3_free(c);
120014 return SQLITE_OK;
120018 ** Extract the next token from a tokenization cursor. The cursor must
120019 ** have been opened by a prior call to simpleOpen().
120021 static int simpleNext(
120022 sqlite3_tokenizer_cursor *pCursor, /* Cursor returned by simpleOpen */
120023 const char **ppToken, /* OUT: *ppToken is the token text */
120024 int *pnBytes, /* OUT: Number of bytes in token */
120025 int *piStartOffset, /* OUT: Starting offset of token */
120026 int *piEndOffset, /* OUT: Ending offset of token */
120027 int *piPosition /* OUT: Position integer of token */
120029 simple_tokenizer_cursor *c = (simple_tokenizer_cursor *) pCursor;
120030 simple_tokenizer *t = (simple_tokenizer *) pCursor->pTokenizer;
120031 unsigned char *p = (unsigned char *)c->pInput;
120033 while( c->iOffset<c->nBytes ){
120034 int iStartOffset;
120036 /* Scan past delimiter characters */
120037 while( c->iOffset<c->nBytes && simpleDelim(t, p[c->iOffset]) ){
120038 c->iOffset++;
120041 /* Count non-delimiter characters. */
120042 iStartOffset = c->iOffset;
120043 while( c->iOffset<c->nBytes && !simpleDelim(t, p[c->iOffset]) ){
120044 c->iOffset++;
120047 if( c->iOffset>iStartOffset ){
120048 int i, n = c->iOffset-iStartOffset;
120049 if( n>c->nTokenAllocated ){
120050 char *pNew;
120051 c->nTokenAllocated = n+20;
120052 pNew = sqlite3_realloc(c->pToken, c->nTokenAllocated);
120053 if( !pNew ) return SQLITE_NOMEM;
120054 c->pToken = pNew;
120056 for(i=0; i<n; i++){
120057 /* TODO(shess) This needs expansion to handle UTF-8
120058 ** case-insensitivity.
120060 unsigned char ch = p[iStartOffset+i];
120061 c->pToken[i] = (char)((ch>='A' && ch<='Z') ? ch-'A'+'a' : ch);
120063 *ppToken = c->pToken;
120064 *pnBytes = n;
120065 *piStartOffset = iStartOffset;
120066 *piEndOffset = c->iOffset;
120067 *piPosition = c->iToken++;
120069 return SQLITE_OK;
120072 return SQLITE_DONE;
120076 ** The set of routines that implement the simple tokenizer
120078 static const sqlite3_tokenizer_module simpleTokenizerModule = {
120080 simpleCreate,
120081 simpleDestroy,
120082 simpleOpen,
120083 simpleClose,
120084 simpleNext,
120088 ** Allocate a new simple tokenizer. Return a pointer to the new
120089 ** tokenizer in *ppModule
120091 SQLITE_PRIVATE void sqlite3Fts3SimpleTokenizerModule(
120092 sqlite3_tokenizer_module const**ppModule
120094 *ppModule = &simpleTokenizerModule;
120097 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
120099 /************** End of fts3_tokenizer1.c *************************************/
120100 /************** Begin file fts3_write.c **************************************/
120102 ** 2009 Oct 23
120104 ** The author disclaims copyright to this source code. In place of
120105 ** a legal notice, here is a blessing:
120107 ** May you do good and not evil.
120108 ** May you find forgiveness for yourself and forgive others.
120109 ** May you share freely, never taking more than you give.
120111 ******************************************************************************
120113 ** This file is part of the SQLite FTS3 extension module. Specifically,
120114 ** this file contains code to insert, update and delete rows from FTS3
120115 ** tables. It also contains code to merge FTS3 b-tree segments. Some
120116 ** of the sub-routines used to merge segments are also used by the query
120117 ** code in fts3.c.
120120 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
120124 ** When full-text index nodes are loaded from disk, the buffer that they
120125 ** are loaded into has the following number of bytes of padding at the end
120126 ** of it. i.e. if a full-text index node is 900 bytes in size, then a buffer
120127 ** of 920 bytes is allocated for it.
120129 ** This means that if we have a pointer into a buffer containing node data,
120130 ** it is always safe to read up to two varints from it without risking an
120131 ** overread, even if the node data is corrupted.
120133 #define FTS3_NODE_PADDING (FTS3_VARINT_MAX*2)
120135 typedef struct PendingList PendingList;
120136 typedef struct SegmentNode SegmentNode;
120137 typedef struct SegmentWriter SegmentWriter;
120140 ** Data structure used while accumulating terms in the pending-terms hash
120141 ** table. The hash table entry maps from term (a string) to a malloc'd
120142 ** instance of this structure.
120144 struct PendingList {
120145 int nData;
120146 char *aData;
120147 int nSpace;
120148 sqlite3_int64 iLastDocid;
120149 sqlite3_int64 iLastCol;
120150 sqlite3_int64 iLastPos;
120155 ** Each cursor has a (possibly empty) linked list of the following objects.
120157 struct Fts3DeferredToken {
120158 Fts3PhraseToken *pToken; /* Pointer to corresponding expr token */
120159 int iCol; /* Column token must occur in */
120160 Fts3DeferredToken *pNext; /* Next in list of deferred tokens */
120161 PendingList *pList; /* Doclist is assembled here */
120165 ** An instance of this structure is used to iterate through the terms on
120166 ** a contiguous set of segment b-tree leaf nodes. Although the details of
120167 ** this structure are only manipulated by code in this file, opaque handles
120168 ** of type Fts3SegReader* are also used by code in fts3.c to iterate through
120169 ** terms when querying the full-text index. See functions:
120171 ** sqlite3Fts3SegReaderNew()
120172 ** sqlite3Fts3SegReaderFree()
120173 ** sqlite3Fts3SegReaderCost()
120174 ** sqlite3Fts3SegReaderIterate()
120176 ** Methods used to manipulate Fts3SegReader structures:
120178 ** fts3SegReaderNext()
120179 ** fts3SegReaderFirstDocid()
120180 ** fts3SegReaderNextDocid()
120182 struct Fts3SegReader {
120183 int iIdx; /* Index within level, or 0x7FFFFFFF for PT */
120185 sqlite3_int64 iStartBlock; /* Rowid of first leaf block to traverse */
120186 sqlite3_int64 iLeafEndBlock; /* Rowid of final leaf block to traverse */
120187 sqlite3_int64 iEndBlock; /* Rowid of final block in segment (or 0) */
120188 sqlite3_int64 iCurrentBlock; /* Current leaf block (or 0) */
120190 char *aNode; /* Pointer to node data (or NULL) */
120191 int nNode; /* Size of buffer at aNode (or 0) */
120192 Fts3HashElem **ppNextElem;
120194 /* Variables set by fts3SegReaderNext(). These may be read directly
120195 ** by the caller. They are valid from the time SegmentReaderNew() returns
120196 ** until SegmentReaderNext() returns something other than SQLITE_OK
120197 ** (i.e. SQLITE_DONE).
120199 int nTerm; /* Number of bytes in current term */
120200 char *zTerm; /* Pointer to current term */
120201 int nTermAlloc; /* Allocated size of zTerm buffer */
120202 char *aDoclist; /* Pointer to doclist of current entry */
120203 int nDoclist; /* Size of doclist in current entry */
120205 /* The following variables are used to iterate through the current doclist */
120206 char *pOffsetList;
120207 sqlite3_int64 iDocid;
120210 #define fts3SegReaderIsPending(p) ((p)->ppNextElem!=0)
120211 #define fts3SegReaderIsRootOnly(p) ((p)->aNode==(char *)&(p)[1])
120214 ** An instance of this structure is used to create a segment b-tree in the
120215 ** database. The internal details of this type are only accessed by the
120216 ** following functions:
120218 ** fts3SegWriterAdd()
120219 ** fts3SegWriterFlush()
120220 ** fts3SegWriterFree()
120222 struct SegmentWriter {
120223 SegmentNode *pTree; /* Pointer to interior tree structure */
120224 sqlite3_int64 iFirst; /* First slot in %_segments written */
120225 sqlite3_int64 iFree; /* Next free slot in %_segments */
120226 char *zTerm; /* Pointer to previous term buffer */
120227 int nTerm; /* Number of bytes in zTerm */
120228 int nMalloc; /* Size of malloc'd buffer at zMalloc */
120229 char *zMalloc; /* Malloc'd space (possibly) used for zTerm */
120230 int nSize; /* Size of allocation at aData */
120231 int nData; /* Bytes of data in aData */
120232 char *aData; /* Pointer to block from malloc() */
120236 ** Type SegmentNode is used by the following three functions to create
120237 ** the interior part of the segment b+-tree structures (everything except
120238 ** the leaf nodes). These functions and type are only ever used by code
120239 ** within the fts3SegWriterXXX() family of functions described above.
120241 ** fts3NodeAddTerm()
120242 ** fts3NodeWrite()
120243 ** fts3NodeFree()
120245 struct SegmentNode {
120246 SegmentNode *pParent; /* Parent node (or NULL for root node) */
120247 SegmentNode *pRight; /* Pointer to right-sibling */
120248 SegmentNode *pLeftmost; /* Pointer to left-most node of this depth */
120249 int nEntry; /* Number of terms written to node so far */
120250 char *zTerm; /* Pointer to previous term buffer */
120251 int nTerm; /* Number of bytes in zTerm */
120252 int nMalloc; /* Size of malloc'd buffer at zMalloc */
120253 char *zMalloc; /* Malloc'd space (possibly) used for zTerm */
120254 int nData; /* Bytes of valid data so far */
120255 char *aData; /* Node data */
120259 ** Valid values for the second argument to fts3SqlStmt().
120261 #define SQL_DELETE_CONTENT 0
120262 #define SQL_IS_EMPTY 1
120263 #define SQL_DELETE_ALL_CONTENT 2
120264 #define SQL_DELETE_ALL_SEGMENTS 3
120265 #define SQL_DELETE_ALL_SEGDIR 4
120266 #define SQL_DELETE_ALL_DOCSIZE 5
120267 #define SQL_DELETE_ALL_STAT 6
120268 #define SQL_SELECT_CONTENT_BY_ROWID 7
120269 #define SQL_NEXT_SEGMENT_INDEX 8
120270 #define SQL_INSERT_SEGMENTS 9
120271 #define SQL_NEXT_SEGMENTS_ID 10
120272 #define SQL_INSERT_SEGDIR 11
120273 #define SQL_SELECT_LEVEL 12
120274 #define SQL_SELECT_ALL_LEVEL 13
120275 #define SQL_SELECT_LEVEL_COUNT 14
120276 #define SQL_SELECT_SEGDIR_COUNT_MAX 15
120277 #define SQL_DELETE_SEGDIR_BY_LEVEL 16
120278 #define SQL_DELETE_SEGMENTS_RANGE 17
120279 #define SQL_CONTENT_INSERT 18
120280 #define SQL_DELETE_DOCSIZE 19
120281 #define SQL_REPLACE_DOCSIZE 20
120282 #define SQL_SELECT_DOCSIZE 21
120283 #define SQL_SELECT_DOCTOTAL 22
120284 #define SQL_REPLACE_DOCTOTAL 23
120287 ** This function is used to obtain an SQLite prepared statement handle
120288 ** for the statement identified by the second argument. If successful,
120289 ** *pp is set to the requested statement handle and SQLITE_OK returned.
120290 ** Otherwise, an SQLite error code is returned and *pp is set to 0.
120292 ** If argument apVal is not NULL, then it must point to an array with
120293 ** at least as many entries as the requested statement has bound
120294 ** parameters. The values are bound to the statements parameters before
120295 ** returning.
120297 static int fts3SqlStmt(
120298 Fts3Table *p, /* Virtual table handle */
120299 int eStmt, /* One of the SQL_XXX constants above */
120300 sqlite3_stmt **pp, /* OUT: Statement handle */
120301 sqlite3_value **apVal /* Values to bind to statement */
120303 const char *azSql[] = {
120304 /* 0 */ "DELETE FROM %Q.'%q_content' WHERE rowid = ?",
120305 /* 1 */ "SELECT NOT EXISTS(SELECT docid FROM %Q.'%q_content' WHERE rowid!=?)",
120306 /* 2 */ "DELETE FROM %Q.'%q_content'",
120307 /* 3 */ "DELETE FROM %Q.'%q_segments'",
120308 /* 4 */ "DELETE FROM %Q.'%q_segdir'",
120309 /* 5 */ "DELETE FROM %Q.'%q_docsize'",
120310 /* 6 */ "DELETE FROM %Q.'%q_stat'",
120311 /* 7 */ "SELECT %s FROM %Q.'%q_content' AS x WHERE rowid=?",
120312 /* 8 */ "SELECT (SELECT max(idx) FROM %Q.'%q_segdir' WHERE level = ?) + 1",
120313 /* 9 */ "INSERT INTO %Q.'%q_segments'(blockid, block) VALUES(?, ?)",
120314 /* 10 */ "SELECT coalesce((SELECT max(blockid) FROM %Q.'%q_segments') + 1, 1)",
120315 /* 11 */ "INSERT INTO %Q.'%q_segdir' VALUES(?,?,?,?,?,?)",
120317 /* Return segments in order from oldest to newest.*/
120318 /* 12 */ "SELECT idx, start_block, leaves_end_block, end_block, root "
120319 "FROM %Q.'%q_segdir' WHERE level = ? ORDER BY idx ASC",
120320 /* 13 */ "SELECT idx, start_block, leaves_end_block, end_block, root "
120321 "FROM %Q.'%q_segdir' ORDER BY level DESC, idx ASC",
120323 /* 14 */ "SELECT count(*) FROM %Q.'%q_segdir' WHERE level = ?",
120324 /* 15 */ "SELECT count(*), max(level) FROM %Q.'%q_segdir'",
120326 /* 16 */ "DELETE FROM %Q.'%q_segdir' WHERE level = ?",
120327 /* 17 */ "DELETE FROM %Q.'%q_segments' WHERE blockid BETWEEN ? AND ?",
120328 /* 18 */ "INSERT INTO %Q.'%q_content' VALUES(%s)",
120329 /* 19 */ "DELETE FROM %Q.'%q_docsize' WHERE docid = ?",
120330 /* 20 */ "REPLACE INTO %Q.'%q_docsize' VALUES(?,?)",
120331 /* 21 */ "SELECT size FROM %Q.'%q_docsize' WHERE docid=?",
120332 /* 22 */ "SELECT value FROM %Q.'%q_stat' WHERE id=0",
120333 /* 23 */ "REPLACE INTO %Q.'%q_stat' VALUES(0,?)",
120335 int rc = SQLITE_OK;
120336 sqlite3_stmt *pStmt;
120338 assert( SizeofArray(azSql)==SizeofArray(p->aStmt) );
120339 assert( eStmt<SizeofArray(azSql) && eStmt>=0 );
120341 pStmt = p->aStmt[eStmt];
120342 if( !pStmt ){
120343 char *zSql;
120344 if( eStmt==SQL_CONTENT_INSERT ){
120345 zSql = sqlite3_mprintf(azSql[eStmt], p->zDb, p->zName, p->zWriteExprlist);
120346 }else if( eStmt==SQL_SELECT_CONTENT_BY_ROWID ){
120347 zSql = sqlite3_mprintf(azSql[eStmt], p->zReadExprlist, p->zDb, p->zName);
120348 }else{
120349 zSql = sqlite3_mprintf(azSql[eStmt], p->zDb, p->zName);
120351 if( !zSql ){
120352 rc = SQLITE_NOMEM;
120353 }else{
120354 rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, NULL);
120355 sqlite3_free(zSql);
120356 assert( rc==SQLITE_OK || pStmt==0 );
120357 p->aStmt[eStmt] = pStmt;
120360 if( apVal ){
120361 int i;
120362 int nParam = sqlite3_bind_parameter_count(pStmt);
120363 for(i=0; rc==SQLITE_OK && i<nParam; i++){
120364 rc = sqlite3_bind_value(pStmt, i+1, apVal[i]);
120367 *pp = pStmt;
120368 return rc;
120371 static int fts3SelectDocsize(
120372 Fts3Table *pTab, /* FTS3 table handle */
120373 int eStmt, /* Either SQL_SELECT_DOCSIZE or DOCTOTAL */
120374 sqlite3_int64 iDocid, /* Docid to bind for SQL_SELECT_DOCSIZE */
120375 sqlite3_stmt **ppStmt /* OUT: Statement handle */
120377 sqlite3_stmt *pStmt = 0; /* Statement requested from fts3SqlStmt() */
120378 int rc; /* Return code */
120380 assert( eStmt==SQL_SELECT_DOCSIZE || eStmt==SQL_SELECT_DOCTOTAL );
120382 rc = fts3SqlStmt(pTab, eStmt, &pStmt, 0);
120383 if( rc==SQLITE_OK ){
120384 if( eStmt==SQL_SELECT_DOCSIZE ){
120385 sqlite3_bind_int64(pStmt, 1, iDocid);
120387 rc = sqlite3_step(pStmt);
120388 if( rc!=SQLITE_ROW || sqlite3_column_type(pStmt, 0)!=SQLITE_BLOB ){
120389 rc = sqlite3_reset(pStmt);
120390 if( rc==SQLITE_OK ) rc = SQLITE_CORRUPT;
120391 pStmt = 0;
120392 }else{
120393 rc = SQLITE_OK;
120397 *ppStmt = pStmt;
120398 return rc;
120401 SQLITE_PRIVATE int sqlite3Fts3SelectDoctotal(
120402 Fts3Table *pTab, /* Fts3 table handle */
120403 sqlite3_stmt **ppStmt /* OUT: Statement handle */
120405 return fts3SelectDocsize(pTab, SQL_SELECT_DOCTOTAL, 0, ppStmt);
120408 SQLITE_PRIVATE int sqlite3Fts3SelectDocsize(
120409 Fts3Table *pTab, /* Fts3 table handle */
120410 sqlite3_int64 iDocid, /* Docid to read size data for */
120411 sqlite3_stmt **ppStmt /* OUT: Statement handle */
120413 return fts3SelectDocsize(pTab, SQL_SELECT_DOCSIZE, iDocid, ppStmt);
120417 ** Similar to fts3SqlStmt(). Except, after binding the parameters in
120418 ** array apVal[] to the SQL statement identified by eStmt, the statement
120419 ** is executed.
120421 ** Returns SQLITE_OK if the statement is successfully executed, or an
120422 ** SQLite error code otherwise.
120424 static void fts3SqlExec(
120425 int *pRC, /* Result code */
120426 Fts3Table *p, /* The FTS3 table */
120427 int eStmt, /* Index of statement to evaluate */
120428 sqlite3_value **apVal /* Parameters to bind */
120430 sqlite3_stmt *pStmt;
120431 int rc;
120432 if( *pRC ) return;
120433 rc = fts3SqlStmt(p, eStmt, &pStmt, apVal);
120434 if( rc==SQLITE_OK ){
120435 sqlite3_step(pStmt);
120436 rc = sqlite3_reset(pStmt);
120438 *pRC = rc;
120443 ** This function ensures that the caller has obtained a shared-cache
120444 ** table-lock on the %_content table. This is required before reading
120445 ** data from the fts3 table. If this lock is not acquired first, then
120446 ** the caller may end up holding read-locks on the %_segments and %_segdir
120447 ** tables, but no read-lock on the %_content table. If this happens
120448 ** a second connection will be able to write to the fts3 table, but
120449 ** attempting to commit those writes might return SQLITE_LOCKED or
120450 ** SQLITE_LOCKED_SHAREDCACHE (because the commit attempts to obtain
120451 ** write-locks on the %_segments and %_segdir ** tables).
120453 ** We try to avoid this because if FTS3 returns any error when committing
120454 ** a transaction, the whole transaction will be rolled back. And this is
120455 ** not what users expect when they get SQLITE_LOCKED_SHAREDCACHE. It can
120456 ** still happen if the user reads data directly from the %_segments or
120457 ** %_segdir tables instead of going through FTS3 though.
120459 SQLITE_PRIVATE int sqlite3Fts3ReadLock(Fts3Table *p){
120460 int rc; /* Return code */
120461 sqlite3_stmt *pStmt; /* Statement used to obtain lock */
120463 rc = fts3SqlStmt(p, SQL_SELECT_CONTENT_BY_ROWID, &pStmt, 0);
120464 if( rc==SQLITE_OK ){
120465 sqlite3_bind_null(pStmt, 1);
120466 sqlite3_step(pStmt);
120467 rc = sqlite3_reset(pStmt);
120469 return rc;
120473 ** Set *ppStmt to a statement handle that may be used to iterate through
120474 ** all rows in the %_segdir table, from oldest to newest. If successful,
120475 ** return SQLITE_OK. If an error occurs while preparing the statement,
120476 ** return an SQLite error code.
120478 ** There is only ever one instance of this SQL statement compiled for
120479 ** each FTS3 table.
120481 ** The statement returns the following columns from the %_segdir table:
120483 ** 0: idx
120484 ** 1: start_block
120485 ** 2: leaves_end_block
120486 ** 3: end_block
120487 ** 4: root
120489 SQLITE_PRIVATE int sqlite3Fts3AllSegdirs(Fts3Table *p, int iLevel, sqlite3_stmt **ppStmt){
120490 int rc;
120491 sqlite3_stmt *pStmt = 0;
120492 if( iLevel<0 ){
120493 rc = fts3SqlStmt(p, SQL_SELECT_ALL_LEVEL, &pStmt, 0);
120494 }else{
120495 rc = fts3SqlStmt(p, SQL_SELECT_LEVEL, &pStmt, 0);
120496 if( rc==SQLITE_OK ) sqlite3_bind_int(pStmt, 1, iLevel);
120498 *ppStmt = pStmt;
120499 return rc;
120504 ** Append a single varint to a PendingList buffer. SQLITE_OK is returned
120505 ** if successful, or an SQLite error code otherwise.
120507 ** This function also serves to allocate the PendingList structure itself.
120508 ** For example, to create a new PendingList structure containing two
120509 ** varints:
120511 ** PendingList *p = 0;
120512 ** fts3PendingListAppendVarint(&p, 1);
120513 ** fts3PendingListAppendVarint(&p, 2);
120515 static int fts3PendingListAppendVarint(
120516 PendingList **pp, /* IN/OUT: Pointer to PendingList struct */
120517 sqlite3_int64 i /* Value to append to data */
120519 PendingList *p = *pp;
120521 /* Allocate or grow the PendingList as required. */
120522 if( !p ){
120523 p = sqlite3_malloc(sizeof(*p) + 100);
120524 if( !p ){
120525 return SQLITE_NOMEM;
120527 p->nSpace = 100;
120528 p->aData = (char *)&p[1];
120529 p->nData = 0;
120531 else if( p->nData+FTS3_VARINT_MAX+1>p->nSpace ){
120532 int nNew = p->nSpace * 2;
120533 p = sqlite3_realloc(p, sizeof(*p) + nNew);
120534 if( !p ){
120535 sqlite3_free(*pp);
120536 *pp = 0;
120537 return SQLITE_NOMEM;
120539 p->nSpace = nNew;
120540 p->aData = (char *)&p[1];
120543 /* Append the new serialized varint to the end of the list. */
120544 p->nData += sqlite3Fts3PutVarint(&p->aData[p->nData], i);
120545 p->aData[p->nData] = '\0';
120546 *pp = p;
120547 return SQLITE_OK;
120551 ** Add a docid/column/position entry to a PendingList structure. Non-zero
120552 ** is returned if the structure is sqlite3_realloced as part of adding
120553 ** the entry. Otherwise, zero.
120555 ** If an OOM error occurs, *pRc is set to SQLITE_NOMEM before returning.
120556 ** Zero is always returned in this case. Otherwise, if no OOM error occurs,
120557 ** it is set to SQLITE_OK.
120559 static int fts3PendingListAppend(
120560 PendingList **pp, /* IN/OUT: PendingList structure */
120561 sqlite3_int64 iDocid, /* Docid for entry to add */
120562 sqlite3_int64 iCol, /* Column for entry to add */
120563 sqlite3_int64 iPos, /* Position of term for entry to add */
120564 int *pRc /* OUT: Return code */
120566 PendingList *p = *pp;
120567 int rc = SQLITE_OK;
120569 assert( !p || p->iLastDocid<=iDocid );
120571 if( !p || p->iLastDocid!=iDocid ){
120572 sqlite3_int64 iDelta = iDocid - (p ? p->iLastDocid : 0);
120573 if( p ){
120574 assert( p->nData<p->nSpace );
120575 assert( p->aData[p->nData]==0 );
120576 p->nData++;
120578 if( SQLITE_OK!=(rc = fts3PendingListAppendVarint(&p, iDelta)) ){
120579 goto pendinglistappend_out;
120581 p->iLastCol = -1;
120582 p->iLastPos = 0;
120583 p->iLastDocid = iDocid;
120585 if( iCol>0 && p->iLastCol!=iCol ){
120586 if( SQLITE_OK!=(rc = fts3PendingListAppendVarint(&p, 1))
120587 || SQLITE_OK!=(rc = fts3PendingListAppendVarint(&p, iCol))
120589 goto pendinglistappend_out;
120591 p->iLastCol = iCol;
120592 p->iLastPos = 0;
120594 if( iCol>=0 ){
120595 assert( iPos>p->iLastPos || (iPos==0 && p->iLastPos==0) );
120596 rc = fts3PendingListAppendVarint(&p, 2+iPos-p->iLastPos);
120597 if( rc==SQLITE_OK ){
120598 p->iLastPos = iPos;
120602 pendinglistappend_out:
120603 *pRc = rc;
120604 if( p!=*pp ){
120605 *pp = p;
120606 return 1;
120608 return 0;
120612 ** Tokenize the nul-terminated string zText and add all tokens to the
120613 ** pending-terms hash-table. The docid used is that currently stored in
120614 ** p->iPrevDocid, and the column is specified by argument iCol.
120616 ** If successful, SQLITE_OK is returned. Otherwise, an SQLite error code.
120618 static int fts3PendingTermsAdd(
120619 Fts3Table *p, /* Table into which text will be inserted */
120620 const char *zText, /* Text of document to be inserted */
120621 int iCol, /* Column into which text is being inserted */
120622 u32 *pnWord /* OUT: Number of tokens inserted */
120624 int rc;
120625 int iStart;
120626 int iEnd;
120627 int iPos;
120628 int nWord = 0;
120630 char const *zToken;
120631 int nToken;
120633 sqlite3_tokenizer *pTokenizer = p->pTokenizer;
120634 sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
120635 sqlite3_tokenizer_cursor *pCsr;
120636 int (*xNext)(sqlite3_tokenizer_cursor *pCursor,
120637 const char**,int*,int*,int*,int*);
120639 assert( pTokenizer && pModule );
120641 rc = pModule->xOpen(pTokenizer, zText, -1, &pCsr);
120642 if( rc!=SQLITE_OK ){
120643 return rc;
120645 pCsr->pTokenizer = pTokenizer;
120647 xNext = pModule->xNext;
120648 while( SQLITE_OK==rc
120649 && SQLITE_OK==(rc = xNext(pCsr, &zToken, &nToken, &iStart, &iEnd, &iPos))
120651 PendingList *pList;
120653 if( iPos>=nWord ) nWord = iPos+1;
120655 /* Positions cannot be negative; we use -1 as a terminator internally.
120656 ** Tokens must have a non-zero length.
120658 if( iPos<0 || !zToken || nToken<=0 ){
120659 rc = SQLITE_ERROR;
120660 break;
120663 pList = (PendingList *)fts3HashFind(&p->pendingTerms, zToken, nToken);
120664 if( pList ){
120665 p->nPendingData -= (pList->nData + nToken + sizeof(Fts3HashElem));
120667 if( fts3PendingListAppend(&pList, p->iPrevDocid, iCol, iPos, &rc) ){
120668 if( pList==fts3HashInsert(&p->pendingTerms, zToken, nToken, pList) ){
120669 /* Malloc failed while inserting the new entry. This can only
120670 ** happen if there was no previous entry for this token.
120672 assert( 0==fts3HashFind(&p->pendingTerms, zToken, nToken) );
120673 sqlite3_free(pList);
120674 rc = SQLITE_NOMEM;
120677 if( rc==SQLITE_OK ){
120678 p->nPendingData += (pList->nData + nToken + sizeof(Fts3HashElem));
120682 pModule->xClose(pCsr);
120683 *pnWord = nWord;
120684 return (rc==SQLITE_DONE ? SQLITE_OK : rc);
120688 ** Calling this function indicates that subsequent calls to
120689 ** fts3PendingTermsAdd() are to add term/position-list pairs for the
120690 ** contents of the document with docid iDocid.
120692 static int fts3PendingTermsDocid(Fts3Table *p, sqlite_int64 iDocid){
120693 /* TODO(shess) Explore whether partially flushing the buffer on
120694 ** forced-flush would provide better performance. I suspect that if
120695 ** we ordered the doclists by size and flushed the largest until the
120696 ** buffer was half empty, that would let the less frequent terms
120697 ** generate longer doclists.
120699 if( iDocid<=p->iPrevDocid || p->nPendingData>p->nMaxPendingData ){
120700 int rc = sqlite3Fts3PendingTermsFlush(p);
120701 if( rc!=SQLITE_OK ) return rc;
120703 p->iPrevDocid = iDocid;
120704 return SQLITE_OK;
120708 ** Discard the contents of the pending-terms hash table.
120710 SQLITE_PRIVATE void sqlite3Fts3PendingTermsClear(Fts3Table *p){
120711 Fts3HashElem *pElem;
120712 for(pElem=fts3HashFirst(&p->pendingTerms); pElem; pElem=fts3HashNext(pElem)){
120713 sqlite3_free(fts3HashData(pElem));
120715 fts3HashClear(&p->pendingTerms);
120716 p->nPendingData = 0;
120720 ** This function is called by the xUpdate() method as part of an INSERT
120721 ** operation. It adds entries for each term in the new record to the
120722 ** pendingTerms hash table.
120724 ** Argument apVal is the same as the similarly named argument passed to
120725 ** fts3InsertData(). Parameter iDocid is the docid of the new row.
120727 static int fts3InsertTerms(Fts3Table *p, sqlite3_value **apVal, u32 *aSz){
120728 int i; /* Iterator variable */
120729 for(i=2; i<p->nColumn+2; i++){
120730 const char *zText = (const char *)sqlite3_value_text(apVal[i]);
120731 if( zText ){
120732 int rc = fts3PendingTermsAdd(p, zText, i-2, &aSz[i-2]);
120733 if( rc!=SQLITE_OK ){
120734 return rc;
120737 aSz[p->nColumn] += sqlite3_value_bytes(apVal[i]);
120739 return SQLITE_OK;
120743 ** This function is called by the xUpdate() method for an INSERT operation.
120744 ** The apVal parameter is passed a copy of the apVal argument passed by
120745 ** SQLite to the xUpdate() method. i.e:
120747 ** apVal[0] Not used for INSERT.
120748 ** apVal[1] rowid
120749 ** apVal[2] Left-most user-defined column
120750 ** ...
120751 ** apVal[p->nColumn+1] Right-most user-defined column
120752 ** apVal[p->nColumn+2] Hidden column with same name as table
120753 ** apVal[p->nColumn+3] Hidden "docid" column (alias for rowid)
120755 static int fts3InsertData(
120756 Fts3Table *p, /* Full-text table */
120757 sqlite3_value **apVal, /* Array of values to insert */
120758 sqlite3_int64 *piDocid /* OUT: Docid for row just inserted */
120760 int rc; /* Return code */
120761 sqlite3_stmt *pContentInsert; /* INSERT INTO %_content VALUES(...) */
120763 /* Locate the statement handle used to insert data into the %_content
120764 ** table. The SQL for this statement is:
120766 ** INSERT INTO %_content VALUES(?, ?, ?, ...)
120768 ** The statement features N '?' variables, where N is the number of user
120769 ** defined columns in the FTS3 table, plus one for the docid field.
120771 rc = fts3SqlStmt(p, SQL_CONTENT_INSERT, &pContentInsert, &apVal[1]);
120772 if( rc!=SQLITE_OK ){
120773 return rc;
120776 /* There is a quirk here. The users INSERT statement may have specified
120777 ** a value for the "rowid" field, for the "docid" field, or for both.
120778 ** Which is a problem, since "rowid" and "docid" are aliases for the
120779 ** same value. For example:
120781 ** INSERT INTO fts3tbl(rowid, docid) VALUES(1, 2);
120783 ** In FTS3, this is an error. It is an error to specify non-NULL values
120784 ** for both docid and some other rowid alias.
120786 if( SQLITE_NULL!=sqlite3_value_type(apVal[3+p->nColumn]) ){
120787 if( SQLITE_NULL==sqlite3_value_type(apVal[0])
120788 && SQLITE_NULL!=sqlite3_value_type(apVal[1])
120790 /* A rowid/docid conflict. */
120791 return SQLITE_ERROR;
120793 rc = sqlite3_bind_value(pContentInsert, 1, apVal[3+p->nColumn]);
120794 if( rc!=SQLITE_OK ) return rc;
120797 /* Execute the statement to insert the record. Set *piDocid to the
120798 ** new docid value.
120800 sqlite3_step(pContentInsert);
120801 rc = sqlite3_reset(pContentInsert);
120803 *piDocid = sqlite3_last_insert_rowid(p->db);
120804 return rc;
120810 ** Remove all data from the FTS3 table. Clear the hash table containing
120811 ** pending terms.
120813 static int fts3DeleteAll(Fts3Table *p){
120814 int rc = SQLITE_OK; /* Return code */
120816 /* Discard the contents of the pending-terms hash table. */
120817 sqlite3Fts3PendingTermsClear(p);
120819 /* Delete everything from the %_content, %_segments and %_segdir tables. */
120820 fts3SqlExec(&rc, p, SQL_DELETE_ALL_CONTENT, 0);
120821 fts3SqlExec(&rc, p, SQL_DELETE_ALL_SEGMENTS, 0);
120822 fts3SqlExec(&rc, p, SQL_DELETE_ALL_SEGDIR, 0);
120823 if( p->bHasDocsize ){
120824 fts3SqlExec(&rc, p, SQL_DELETE_ALL_DOCSIZE, 0);
120826 if( p->bHasStat ){
120827 fts3SqlExec(&rc, p, SQL_DELETE_ALL_STAT, 0);
120829 return rc;
120833 ** The first element in the apVal[] array is assumed to contain the docid
120834 ** (an integer) of a row about to be deleted. Remove all terms from the
120835 ** full-text index.
120837 static void fts3DeleteTerms(
120838 int *pRC, /* Result code */
120839 Fts3Table *p, /* The FTS table to delete from */
120840 sqlite3_value **apVal, /* apVal[] contains the docid to be deleted */
120841 u32 *aSz /* Sizes of deleted document written here */
120843 int rc;
120844 sqlite3_stmt *pSelect;
120846 if( *pRC ) return;
120847 rc = fts3SqlStmt(p, SQL_SELECT_CONTENT_BY_ROWID, &pSelect, apVal);
120848 if( rc==SQLITE_OK ){
120849 if( SQLITE_ROW==sqlite3_step(pSelect) ){
120850 int i;
120851 for(i=1; i<=p->nColumn; i++){
120852 const char *zText = (const char *)sqlite3_column_text(pSelect, i);
120853 rc = fts3PendingTermsAdd(p, zText, -1, &aSz[i-1]);
120854 if( rc!=SQLITE_OK ){
120855 sqlite3_reset(pSelect);
120856 *pRC = rc;
120857 return;
120859 aSz[p->nColumn] += sqlite3_column_bytes(pSelect, i);
120862 rc = sqlite3_reset(pSelect);
120863 }else{
120864 sqlite3_reset(pSelect);
120866 *pRC = rc;
120870 ** Forward declaration to account for the circular dependency between
120871 ** functions fts3SegmentMerge() and fts3AllocateSegdirIdx().
120873 static int fts3SegmentMerge(Fts3Table *, int);
120876 ** This function allocates a new level iLevel index in the segdir table.
120877 ** Usually, indexes are allocated within a level sequentially starting
120878 ** with 0, so the allocated index is one greater than the value returned
120879 ** by:
120881 ** SELECT max(idx) FROM %_segdir WHERE level = :iLevel
120883 ** However, if there are already FTS3_MERGE_COUNT indexes at the requested
120884 ** level, they are merged into a single level (iLevel+1) segment and the
120885 ** allocated index is 0.
120887 ** If successful, *piIdx is set to the allocated index slot and SQLITE_OK
120888 ** returned. Otherwise, an SQLite error code is returned.
120890 static int fts3AllocateSegdirIdx(Fts3Table *p, int iLevel, int *piIdx){
120891 int rc; /* Return Code */
120892 sqlite3_stmt *pNextIdx; /* Query for next idx at level iLevel */
120893 int iNext = 0; /* Result of query pNextIdx */
120895 /* Set variable iNext to the next available segdir index at level iLevel. */
120896 rc = fts3SqlStmt(p, SQL_NEXT_SEGMENT_INDEX, &pNextIdx, 0);
120897 if( rc==SQLITE_OK ){
120898 sqlite3_bind_int(pNextIdx, 1, iLevel);
120899 if( SQLITE_ROW==sqlite3_step(pNextIdx) ){
120900 iNext = sqlite3_column_int(pNextIdx, 0);
120902 rc = sqlite3_reset(pNextIdx);
120905 if( rc==SQLITE_OK ){
120906 /* If iNext is FTS3_MERGE_COUNT, indicating that level iLevel is already
120907 ** full, merge all segments in level iLevel into a single iLevel+1
120908 ** segment and allocate (newly freed) index 0 at level iLevel. Otherwise,
120909 ** if iNext is less than FTS3_MERGE_COUNT, allocate index iNext.
120911 if( iNext>=FTS3_MERGE_COUNT ){
120912 rc = fts3SegmentMerge(p, iLevel);
120913 *piIdx = 0;
120914 }else{
120915 *piIdx = iNext;
120919 return rc;
120923 ** The %_segments table is declared as follows:
120925 ** CREATE TABLE %_segments(blockid INTEGER PRIMARY KEY, block BLOB)
120927 ** This function reads data from a single row of the %_segments table. The
120928 ** specific row is identified by the iBlockid parameter. If paBlob is not
120929 ** NULL, then a buffer is allocated using sqlite3_malloc() and populated
120930 ** with the contents of the blob stored in the "block" column of the
120931 ** identified table row is. Whether or not paBlob is NULL, *pnBlob is set
120932 ** to the size of the blob in bytes before returning.
120934 ** If an error occurs, or the table does not contain the specified row,
120935 ** an SQLite error code is returned. Otherwise, SQLITE_OK is returned. If
120936 ** paBlob is non-NULL, then it is the responsibility of the caller to
120937 ** eventually free the returned buffer.
120939 ** This function may leave an open sqlite3_blob* handle in the
120940 ** Fts3Table.pSegments variable. This handle is reused by subsequent calls
120941 ** to this function. The handle may be closed by calling the
120942 ** sqlite3Fts3SegmentsClose() function. Reusing a blob handle is a handy
120943 ** performance improvement, but the blob handle should always be closed
120944 ** before control is returned to the user (to prevent a lock being held
120945 ** on the database file for longer than necessary). Thus, any virtual table
120946 ** method (xFilter etc.) that may directly or indirectly call this function
120947 ** must call sqlite3Fts3SegmentsClose() before returning.
120949 SQLITE_PRIVATE int sqlite3Fts3ReadBlock(
120950 Fts3Table *p, /* FTS3 table handle */
120951 sqlite3_int64 iBlockid, /* Access the row with blockid=$iBlockid */
120952 char **paBlob, /* OUT: Blob data in malloc'd buffer */
120953 int *pnBlob /* OUT: Size of blob data */
120955 int rc; /* Return code */
120957 /* pnBlob must be non-NULL. paBlob may be NULL or non-NULL. */
120958 assert( pnBlob);
120960 if( p->pSegments ){
120961 rc = sqlite3_blob_reopen(p->pSegments, iBlockid);
120962 }else{
120963 if( 0==p->zSegmentsTbl ){
120964 p->zSegmentsTbl = sqlite3_mprintf("%s_segments", p->zName);
120965 if( 0==p->zSegmentsTbl ) return SQLITE_NOMEM;
120967 rc = sqlite3_blob_open(
120968 p->db, p->zDb, p->zSegmentsTbl, "block", iBlockid, 0, &p->pSegments
120972 if( rc==SQLITE_OK ){
120973 int nByte = sqlite3_blob_bytes(p->pSegments);
120974 if( paBlob ){
120975 char *aByte = sqlite3_malloc(nByte + FTS3_NODE_PADDING);
120976 if( !aByte ){
120977 rc = SQLITE_NOMEM;
120978 }else{
120979 rc = sqlite3_blob_read(p->pSegments, aByte, nByte, 0);
120980 memset(&aByte[nByte], 0, FTS3_NODE_PADDING);
120981 if( rc!=SQLITE_OK ){
120982 sqlite3_free(aByte);
120983 aByte = 0;
120986 *paBlob = aByte;
120988 *pnBlob = nByte;
120991 return rc;
120995 ** Close the blob handle at p->pSegments, if it is open. See comments above
120996 ** the sqlite3Fts3ReadBlock() function for details.
120998 SQLITE_PRIVATE void sqlite3Fts3SegmentsClose(Fts3Table *p){
120999 sqlite3_blob_close(p->pSegments);
121000 p->pSegments = 0;
121004 ** Move the iterator passed as the first argument to the next term in the
121005 ** segment. If successful, SQLITE_OK is returned. If there is no next term,
121006 ** SQLITE_DONE. Otherwise, an SQLite error code.
121008 static int fts3SegReaderNext(Fts3Table *p, Fts3SegReader *pReader){
121009 char *pNext; /* Cursor variable */
121010 int nPrefix; /* Number of bytes in term prefix */
121011 int nSuffix; /* Number of bytes in term suffix */
121013 if( !pReader->aDoclist ){
121014 pNext = pReader->aNode;
121015 }else{
121016 pNext = &pReader->aDoclist[pReader->nDoclist];
121019 if( !pNext || pNext>=&pReader->aNode[pReader->nNode] ){
121020 int rc; /* Return code from Fts3ReadBlock() */
121022 if( fts3SegReaderIsPending(pReader) ){
121023 Fts3HashElem *pElem = *(pReader->ppNextElem);
121024 if( pElem==0 ){
121025 pReader->aNode = 0;
121026 }else{
121027 PendingList *pList = (PendingList *)fts3HashData(pElem);
121028 pReader->zTerm = (char *)fts3HashKey(pElem);
121029 pReader->nTerm = fts3HashKeysize(pElem);
121030 pReader->nNode = pReader->nDoclist = pList->nData + 1;
121031 pReader->aNode = pReader->aDoclist = pList->aData;
121032 pReader->ppNextElem++;
121033 assert( pReader->aNode );
121035 return SQLITE_OK;
121038 if( !fts3SegReaderIsRootOnly(pReader) ){
121039 sqlite3_free(pReader->aNode);
121041 pReader->aNode = 0;
121043 /* If iCurrentBlock>=iLeafEndBlock, this is an EOF condition. All leaf
121044 ** blocks have already been traversed. */
121045 assert( pReader->iCurrentBlock<=pReader->iLeafEndBlock );
121046 if( pReader->iCurrentBlock>=pReader->iLeafEndBlock ){
121047 return SQLITE_OK;
121050 rc = sqlite3Fts3ReadBlock(
121051 p, ++pReader->iCurrentBlock, &pReader->aNode, &pReader->nNode
121053 if( rc!=SQLITE_OK ) return rc;
121054 pNext = pReader->aNode;
121057 /* Because of the FTS3_NODE_PADDING bytes of padding, the following is
121058 ** safe (no risk of overread) even if the node data is corrupted.
121060 pNext += sqlite3Fts3GetVarint32(pNext, &nPrefix);
121061 pNext += sqlite3Fts3GetVarint32(pNext, &nSuffix);
121062 if( nPrefix<0 || nSuffix<=0
121063 || &pNext[nSuffix]>&pReader->aNode[pReader->nNode]
121065 return SQLITE_CORRUPT;
121068 if( nPrefix+nSuffix>pReader->nTermAlloc ){
121069 int nNew = (nPrefix+nSuffix)*2;
121070 char *zNew = sqlite3_realloc(pReader->zTerm, nNew);
121071 if( !zNew ){
121072 return SQLITE_NOMEM;
121074 pReader->zTerm = zNew;
121075 pReader->nTermAlloc = nNew;
121077 memcpy(&pReader->zTerm[nPrefix], pNext, nSuffix);
121078 pReader->nTerm = nPrefix+nSuffix;
121079 pNext += nSuffix;
121080 pNext += sqlite3Fts3GetVarint32(pNext, &pReader->nDoclist);
121081 pReader->aDoclist = pNext;
121082 pReader->pOffsetList = 0;
121084 /* Check that the doclist does not appear to extend past the end of the
121085 ** b-tree node. And that the final byte of the doclist is 0x00. If either
121086 ** of these statements is untrue, then the data structure is corrupt.
121088 if( &pReader->aDoclist[pReader->nDoclist]>&pReader->aNode[pReader->nNode]
121089 || pReader->aDoclist[pReader->nDoclist-1]
121091 return SQLITE_CORRUPT;
121093 return SQLITE_OK;
121097 ** Set the SegReader to point to the first docid in the doclist associated
121098 ** with the current term.
121100 static void fts3SegReaderFirstDocid(Fts3SegReader *pReader){
121101 int n;
121102 assert( pReader->aDoclist );
121103 assert( !pReader->pOffsetList );
121104 n = sqlite3Fts3GetVarint(pReader->aDoclist, &pReader->iDocid);
121105 pReader->pOffsetList = &pReader->aDoclist[n];
121109 ** Advance the SegReader to point to the next docid in the doclist
121110 ** associated with the current term.
121112 ** If arguments ppOffsetList and pnOffsetList are not NULL, then
121113 ** *ppOffsetList is set to point to the first column-offset list
121114 ** in the doclist entry (i.e. immediately past the docid varint).
121115 ** *pnOffsetList is set to the length of the set of column-offset
121116 ** lists, not including the nul-terminator byte. For example:
121118 static void fts3SegReaderNextDocid(
121119 Fts3SegReader *pReader,
121120 char **ppOffsetList,
121121 int *pnOffsetList
121123 char *p = pReader->pOffsetList;
121124 char c = 0;
121126 /* Pointer p currently points at the first byte of an offset list. The
121127 ** following two lines advance it to point one byte past the end of
121128 ** the same offset list.
121130 while( *p | c ) c = *p++ & 0x80;
121133 /* If required, populate the output variables with a pointer to and the
121134 ** size of the previous offset-list.
121136 if( ppOffsetList ){
121137 *ppOffsetList = pReader->pOffsetList;
121138 *pnOffsetList = (int)(p - pReader->pOffsetList - 1);
121141 /* If there are no more entries in the doclist, set pOffsetList to
121142 ** NULL. Otherwise, set Fts3SegReader.iDocid to the next docid and
121143 ** Fts3SegReader.pOffsetList to point to the next offset list before
121144 ** returning.
121146 if( p>=&pReader->aDoclist[pReader->nDoclist] ){
121147 pReader->pOffsetList = 0;
121148 }else{
121149 sqlite3_int64 iDelta;
121150 pReader->pOffsetList = p + sqlite3Fts3GetVarint(p, &iDelta);
121151 pReader->iDocid += iDelta;
121156 ** This function is called to estimate the amount of data that will be
121157 ** loaded from the disk If SegReaderIterate() is called on this seg-reader,
121158 ** in units of average document size.
121160 ** This can be used as follows: If the caller has a small doclist that
121161 ** contains references to N documents, and is considering merging it with
121162 ** a large doclist (size X "average documents"), it may opt not to load
121163 ** the large doclist if X>N.
121165 SQLITE_PRIVATE int sqlite3Fts3SegReaderCost(
121166 Fts3Cursor *pCsr, /* FTS3 cursor handle */
121167 Fts3SegReader *pReader, /* Segment-reader handle */
121168 int *pnCost /* IN/OUT: Number of bytes read */
121170 Fts3Table *p = (Fts3Table*)pCsr->base.pVtab;
121171 int rc = SQLITE_OK; /* Return code */
121172 int nCost = 0; /* Cost in bytes to return */
121173 int pgsz = p->nPgsz; /* Database page size */
121175 /* If this seg-reader is reading the pending-terms table, or if all data
121176 ** for the segment is stored on the root page of the b-tree, then the cost
121177 ** is zero. In this case all required data is already in main memory.
121179 if( p->bHasStat
121180 && !fts3SegReaderIsPending(pReader)
121181 && !fts3SegReaderIsRootOnly(pReader)
121183 int nBlob = 0;
121184 sqlite3_int64 iBlock;
121186 if( pCsr->nRowAvg==0 ){
121187 /* The average document size, which is required to calculate the cost
121188 ** of each doclist, has not yet been determined. Read the required
121189 ** data from the %_stat table to calculate it.
121191 ** Entry 0 of the %_stat table is a blob containing (nCol+1) FTS3
121192 ** varints, where nCol is the number of columns in the FTS3 table.
121193 ** The first varint is the number of documents currently stored in
121194 ** the table. The following nCol varints contain the total amount of
121195 ** data stored in all rows of each column of the table, from left
121196 ** to right.
121198 sqlite3_stmt *pStmt;
121199 sqlite3_int64 nDoc = 0;
121200 sqlite3_int64 nByte = 0;
121201 const char *pEnd;
121202 const char *a;
121204 rc = sqlite3Fts3SelectDoctotal(p, &pStmt);
121205 if( rc!=SQLITE_OK ) return rc;
121206 a = sqlite3_column_blob(pStmt, 0);
121207 assert( a );
121209 pEnd = &a[sqlite3_column_bytes(pStmt, 0)];
121210 a += sqlite3Fts3GetVarint(a, &nDoc);
121211 while( a<pEnd ){
121212 a += sqlite3Fts3GetVarint(a, &nByte);
121214 if( nDoc==0 || nByte==0 ){
121215 sqlite3_reset(pStmt);
121216 return SQLITE_CORRUPT;
121219 pCsr->nRowAvg = (int)(((nByte / nDoc) + pgsz) / pgsz);
121220 assert( pCsr->nRowAvg>0 );
121221 rc = sqlite3_reset(pStmt);
121222 if( rc!=SQLITE_OK ) return rc;
121225 /* Assume that a blob flows over onto overflow pages if it is larger
121226 ** than (pgsz-35) bytes in size (the file-format documentation
121227 ** confirms this).
121229 for(iBlock=pReader->iStartBlock; iBlock<=pReader->iLeafEndBlock; iBlock++){
121230 rc = sqlite3Fts3ReadBlock(p, iBlock, 0, &nBlob);
121231 if( rc!=SQLITE_OK ) break;
121232 if( (nBlob+35)>pgsz ){
121233 int nOvfl = (nBlob + 34)/pgsz;
121234 nCost += ((nOvfl + pCsr->nRowAvg - 1)/pCsr->nRowAvg);
121239 *pnCost += nCost;
121240 return rc;
121244 ** Free all allocations associated with the iterator passed as the
121245 ** second argument.
121247 SQLITE_PRIVATE void sqlite3Fts3SegReaderFree(Fts3SegReader *pReader){
121248 if( pReader && !fts3SegReaderIsPending(pReader) ){
121249 sqlite3_free(pReader->zTerm);
121250 if( !fts3SegReaderIsRootOnly(pReader) ){
121251 sqlite3_free(pReader->aNode);
121254 sqlite3_free(pReader);
121258 ** Allocate a new SegReader object.
121260 SQLITE_PRIVATE int sqlite3Fts3SegReaderNew(
121261 int iAge, /* Segment "age". */
121262 sqlite3_int64 iStartLeaf, /* First leaf to traverse */
121263 sqlite3_int64 iEndLeaf, /* Final leaf to traverse */
121264 sqlite3_int64 iEndBlock, /* Final block of segment */
121265 const char *zRoot, /* Buffer containing root node */
121266 int nRoot, /* Size of buffer containing root node */
121267 Fts3SegReader **ppReader /* OUT: Allocated Fts3SegReader */
121269 int rc = SQLITE_OK; /* Return code */
121270 Fts3SegReader *pReader; /* Newly allocated SegReader object */
121271 int nExtra = 0; /* Bytes to allocate segment root node */
121273 assert( iStartLeaf<=iEndLeaf );
121274 if( iStartLeaf==0 ){
121275 nExtra = nRoot + FTS3_NODE_PADDING;
121278 pReader = (Fts3SegReader *)sqlite3_malloc(sizeof(Fts3SegReader) + nExtra);
121279 if( !pReader ){
121280 return SQLITE_NOMEM;
121282 memset(pReader, 0, sizeof(Fts3SegReader));
121283 pReader->iIdx = iAge;
121284 pReader->iStartBlock = iStartLeaf;
121285 pReader->iLeafEndBlock = iEndLeaf;
121286 pReader->iEndBlock = iEndBlock;
121288 if( nExtra ){
121289 /* The entire segment is stored in the root node. */
121290 pReader->aNode = (char *)&pReader[1];
121291 pReader->nNode = nRoot;
121292 memcpy(pReader->aNode, zRoot, nRoot);
121293 memset(&pReader->aNode[nRoot], 0, FTS3_NODE_PADDING);
121294 }else{
121295 pReader->iCurrentBlock = iStartLeaf-1;
121298 if( rc==SQLITE_OK ){
121299 *ppReader = pReader;
121300 }else{
121301 sqlite3Fts3SegReaderFree(pReader);
121303 return rc;
121307 ** This is a comparison function used as a qsort() callback when sorting
121308 ** an array of pending terms by term. This occurs as part of flushing
121309 ** the contents of the pending-terms hash table to the database.
121311 static int fts3CompareElemByTerm(const void *lhs, const void *rhs){
121312 char *z1 = fts3HashKey(*(Fts3HashElem **)lhs);
121313 char *z2 = fts3HashKey(*(Fts3HashElem **)rhs);
121314 int n1 = fts3HashKeysize(*(Fts3HashElem **)lhs);
121315 int n2 = fts3HashKeysize(*(Fts3HashElem **)rhs);
121317 int n = (n1<n2 ? n1 : n2);
121318 int c = memcmp(z1, z2, n);
121319 if( c==0 ){
121320 c = n1 - n2;
121322 return c;
121326 ** This function is used to allocate an Fts3SegReader that iterates through
121327 ** a subset of the terms stored in the Fts3Table.pendingTerms array.
121329 SQLITE_PRIVATE int sqlite3Fts3SegReaderPending(
121330 Fts3Table *p, /* Virtual table handle */
121331 const char *zTerm, /* Term to search for */
121332 int nTerm, /* Size of buffer zTerm */
121333 int isPrefix, /* True for a term-prefix query */
121334 Fts3SegReader **ppReader /* OUT: SegReader for pending-terms */
121336 Fts3SegReader *pReader = 0; /* Fts3SegReader object to return */
121337 Fts3HashElem *pE; /* Iterator variable */
121338 Fts3HashElem **aElem = 0; /* Array of term hash entries to scan */
121339 int nElem = 0; /* Size of array at aElem */
121340 int rc = SQLITE_OK; /* Return Code */
121342 if( isPrefix ){
121343 int nAlloc = 0; /* Size of allocated array at aElem */
121345 for(pE=fts3HashFirst(&p->pendingTerms); pE; pE=fts3HashNext(pE)){
121346 char *zKey = (char *)fts3HashKey(pE);
121347 int nKey = fts3HashKeysize(pE);
121348 if( nTerm==0 || (nKey>=nTerm && 0==memcmp(zKey, zTerm, nTerm)) ){
121349 if( nElem==nAlloc ){
121350 Fts3HashElem **aElem2;
121351 nAlloc += 16;
121352 aElem2 = (Fts3HashElem **)sqlite3_realloc(
121353 aElem, nAlloc*sizeof(Fts3HashElem *)
121355 if( !aElem2 ){
121356 rc = SQLITE_NOMEM;
121357 nElem = 0;
121358 break;
121360 aElem = aElem2;
121362 aElem[nElem++] = pE;
121366 /* If more than one term matches the prefix, sort the Fts3HashElem
121367 ** objects in term order using qsort(). This uses the same comparison
121368 ** callback as is used when flushing terms to disk.
121370 if( nElem>1 ){
121371 qsort(aElem, nElem, sizeof(Fts3HashElem *), fts3CompareElemByTerm);
121374 }else{
121375 pE = fts3HashFindElem(&p->pendingTerms, zTerm, nTerm);
121376 if( pE ){
121377 aElem = &pE;
121378 nElem = 1;
121382 if( nElem>0 ){
121383 int nByte = sizeof(Fts3SegReader) + (nElem+1)*sizeof(Fts3HashElem *);
121384 pReader = (Fts3SegReader *)sqlite3_malloc(nByte);
121385 if( !pReader ){
121386 rc = SQLITE_NOMEM;
121387 }else{
121388 memset(pReader, 0, nByte);
121389 pReader->iIdx = 0x7FFFFFFF;
121390 pReader->ppNextElem = (Fts3HashElem **)&pReader[1];
121391 memcpy(pReader->ppNextElem, aElem, nElem*sizeof(Fts3HashElem *));
121395 if( isPrefix ){
121396 sqlite3_free(aElem);
121398 *ppReader = pReader;
121399 return rc;
121403 ** Compare the entries pointed to by two Fts3SegReader structures.
121404 ** Comparison is as follows:
121406 ** 1) EOF is greater than not EOF.
121408 ** 2) The current terms (if any) are compared using memcmp(). If one
121409 ** term is a prefix of another, the longer term is considered the
121410 ** larger.
121412 ** 3) By segment age. An older segment is considered larger.
121414 static int fts3SegReaderCmp(Fts3SegReader *pLhs, Fts3SegReader *pRhs){
121415 int rc;
121416 if( pLhs->aNode && pRhs->aNode ){
121417 int rc2 = pLhs->nTerm - pRhs->nTerm;
121418 if( rc2<0 ){
121419 rc = memcmp(pLhs->zTerm, pRhs->zTerm, pLhs->nTerm);
121420 }else{
121421 rc = memcmp(pLhs->zTerm, pRhs->zTerm, pRhs->nTerm);
121423 if( rc==0 ){
121424 rc = rc2;
121426 }else{
121427 rc = (pLhs->aNode==0) - (pRhs->aNode==0);
121429 if( rc==0 ){
121430 rc = pRhs->iIdx - pLhs->iIdx;
121432 assert( rc!=0 );
121433 return rc;
121437 ** A different comparison function for SegReader structures. In this
121438 ** version, it is assumed that each SegReader points to an entry in
121439 ** a doclist for identical terms. Comparison is made as follows:
121441 ** 1) EOF (end of doclist in this case) is greater than not EOF.
121443 ** 2) By current docid.
121445 ** 3) By segment age. An older segment is considered larger.
121447 static int fts3SegReaderDoclistCmp(Fts3SegReader *pLhs, Fts3SegReader *pRhs){
121448 int rc = (pLhs->pOffsetList==0)-(pRhs->pOffsetList==0);
121449 if( rc==0 ){
121450 if( pLhs->iDocid==pRhs->iDocid ){
121451 rc = pRhs->iIdx - pLhs->iIdx;
121452 }else{
121453 rc = (pLhs->iDocid > pRhs->iDocid) ? 1 : -1;
121456 assert( pLhs->aNode && pRhs->aNode );
121457 return rc;
121461 ** Compare the term that the Fts3SegReader object passed as the first argument
121462 ** points to with the term specified by arguments zTerm and nTerm.
121464 ** If the pSeg iterator is already at EOF, return 0. Otherwise, return
121465 ** -ve if the pSeg term is less than zTerm/nTerm, 0 if the two terms are
121466 ** equal, or +ve if the pSeg term is greater than zTerm/nTerm.
121468 static int fts3SegReaderTermCmp(
121469 Fts3SegReader *pSeg, /* Segment reader object */
121470 const char *zTerm, /* Term to compare to */
121471 int nTerm /* Size of term zTerm in bytes */
121473 int res = 0;
121474 if( pSeg->aNode ){
121475 if( pSeg->nTerm>nTerm ){
121476 res = memcmp(pSeg->zTerm, zTerm, nTerm);
121477 }else{
121478 res = memcmp(pSeg->zTerm, zTerm, pSeg->nTerm);
121480 if( res==0 ){
121481 res = pSeg->nTerm-nTerm;
121484 return res;
121488 ** Argument apSegment is an array of nSegment elements. It is known that
121489 ** the final (nSegment-nSuspect) members are already in sorted order
121490 ** (according to the comparison function provided). This function shuffles
121491 ** the array around until all entries are in sorted order.
121493 static void fts3SegReaderSort(
121494 Fts3SegReader **apSegment, /* Array to sort entries of */
121495 int nSegment, /* Size of apSegment array */
121496 int nSuspect, /* Unsorted entry count */
121497 int (*xCmp)(Fts3SegReader *, Fts3SegReader *) /* Comparison function */
121499 int i; /* Iterator variable */
121501 assert( nSuspect<=nSegment );
121503 if( nSuspect==nSegment ) nSuspect--;
121504 for(i=nSuspect-1; i>=0; i--){
121505 int j;
121506 for(j=i; j<(nSegment-1); j++){
121507 Fts3SegReader *pTmp;
121508 if( xCmp(apSegment[j], apSegment[j+1])<0 ) break;
121509 pTmp = apSegment[j+1];
121510 apSegment[j+1] = apSegment[j];
121511 apSegment[j] = pTmp;
121515 #ifndef NDEBUG
121516 /* Check that the list really is sorted now. */
121517 for(i=0; i<(nSuspect-1); i++){
121518 assert( xCmp(apSegment[i], apSegment[i+1])<0 );
121520 #endif
121524 ** Insert a record into the %_segments table.
121526 static int fts3WriteSegment(
121527 Fts3Table *p, /* Virtual table handle */
121528 sqlite3_int64 iBlock, /* Block id for new block */
121529 char *z, /* Pointer to buffer containing block data */
121530 int n /* Size of buffer z in bytes */
121532 sqlite3_stmt *pStmt;
121533 int rc = fts3SqlStmt(p, SQL_INSERT_SEGMENTS, &pStmt, 0);
121534 if( rc==SQLITE_OK ){
121535 sqlite3_bind_int64(pStmt, 1, iBlock);
121536 sqlite3_bind_blob(pStmt, 2, z, n, SQLITE_STATIC);
121537 sqlite3_step(pStmt);
121538 rc = sqlite3_reset(pStmt);
121540 return rc;
121544 ** Insert a record into the %_segdir table.
121546 static int fts3WriteSegdir(
121547 Fts3Table *p, /* Virtual table handle */
121548 int iLevel, /* Value for "level" field */
121549 int iIdx, /* Value for "idx" field */
121550 sqlite3_int64 iStartBlock, /* Value for "start_block" field */
121551 sqlite3_int64 iLeafEndBlock, /* Value for "leaves_end_block" field */
121552 sqlite3_int64 iEndBlock, /* Value for "end_block" field */
121553 char *zRoot, /* Blob value for "root" field */
121554 int nRoot /* Number of bytes in buffer zRoot */
121556 sqlite3_stmt *pStmt;
121557 int rc = fts3SqlStmt(p, SQL_INSERT_SEGDIR, &pStmt, 0);
121558 if( rc==SQLITE_OK ){
121559 sqlite3_bind_int(pStmt, 1, iLevel);
121560 sqlite3_bind_int(pStmt, 2, iIdx);
121561 sqlite3_bind_int64(pStmt, 3, iStartBlock);
121562 sqlite3_bind_int64(pStmt, 4, iLeafEndBlock);
121563 sqlite3_bind_int64(pStmt, 5, iEndBlock);
121564 sqlite3_bind_blob(pStmt, 6, zRoot, nRoot, SQLITE_STATIC);
121565 sqlite3_step(pStmt);
121566 rc = sqlite3_reset(pStmt);
121568 return rc;
121572 ** Return the size of the common prefix (if any) shared by zPrev and
121573 ** zNext, in bytes. For example,
121575 ** fts3PrefixCompress("abc", 3, "abcdef", 6) // returns 3
121576 ** fts3PrefixCompress("abX", 3, "abcdef", 6) // returns 2
121577 ** fts3PrefixCompress("abX", 3, "Xbcdef", 6) // returns 0
121579 static int fts3PrefixCompress(
121580 const char *zPrev, /* Buffer containing previous term */
121581 int nPrev, /* Size of buffer zPrev in bytes */
121582 const char *zNext, /* Buffer containing next term */
121583 int nNext /* Size of buffer zNext in bytes */
121585 int n;
121586 UNUSED_PARAMETER(nNext);
121587 for(n=0; n<nPrev && zPrev[n]==zNext[n]; n++);
121588 return n;
121592 ** Add term zTerm to the SegmentNode. It is guaranteed that zTerm is larger
121593 ** (according to memcmp) than the previous term.
121595 static int fts3NodeAddTerm(
121596 Fts3Table *p, /* Virtual table handle */
121597 SegmentNode **ppTree, /* IN/OUT: SegmentNode handle */
121598 int isCopyTerm, /* True if zTerm/nTerm is transient */
121599 const char *zTerm, /* Pointer to buffer containing term */
121600 int nTerm /* Size of term in bytes */
121602 SegmentNode *pTree = *ppTree;
121603 int rc;
121604 SegmentNode *pNew;
121606 /* First try to append the term to the current node. Return early if
121607 ** this is possible.
121609 if( pTree ){
121610 int nData = pTree->nData; /* Current size of node in bytes */
121611 int nReq = nData; /* Required space after adding zTerm */
121612 int nPrefix; /* Number of bytes of prefix compression */
121613 int nSuffix; /* Suffix length */
121615 nPrefix = fts3PrefixCompress(pTree->zTerm, pTree->nTerm, zTerm, nTerm);
121616 nSuffix = nTerm-nPrefix;
121618 nReq += sqlite3Fts3VarintLen(nPrefix)+sqlite3Fts3VarintLen(nSuffix)+nSuffix;
121619 if( nReq<=p->nNodeSize || !pTree->zTerm ){
121621 if( nReq>p->nNodeSize ){
121622 /* An unusual case: this is the first term to be added to the node
121623 ** and the static node buffer (p->nNodeSize bytes) is not large
121624 ** enough. Use a separately malloced buffer instead This wastes
121625 ** p->nNodeSize bytes, but since this scenario only comes about when
121626 ** the database contain two terms that share a prefix of almost 2KB,
121627 ** this is not expected to be a serious problem.
121629 assert( pTree->aData==(char *)&pTree[1] );
121630 pTree->aData = (char *)sqlite3_malloc(nReq);
121631 if( !pTree->aData ){
121632 return SQLITE_NOMEM;
121636 if( pTree->zTerm ){
121637 /* There is no prefix-length field for first term in a node */
121638 nData += sqlite3Fts3PutVarint(&pTree->aData[nData], nPrefix);
121641 nData += sqlite3Fts3PutVarint(&pTree->aData[nData], nSuffix);
121642 memcpy(&pTree->aData[nData], &zTerm[nPrefix], nSuffix);
121643 pTree->nData = nData + nSuffix;
121644 pTree->nEntry++;
121646 if( isCopyTerm ){
121647 if( pTree->nMalloc<nTerm ){
121648 char *zNew = sqlite3_realloc(pTree->zMalloc, nTerm*2);
121649 if( !zNew ){
121650 return SQLITE_NOMEM;
121652 pTree->nMalloc = nTerm*2;
121653 pTree->zMalloc = zNew;
121655 pTree->zTerm = pTree->zMalloc;
121656 memcpy(pTree->zTerm, zTerm, nTerm);
121657 pTree->nTerm = nTerm;
121658 }else{
121659 pTree->zTerm = (char *)zTerm;
121660 pTree->nTerm = nTerm;
121662 return SQLITE_OK;
121666 /* If control flows to here, it was not possible to append zTerm to the
121667 ** current node. Create a new node (a right-sibling of the current node).
121668 ** If this is the first node in the tree, the term is added to it.
121670 ** Otherwise, the term is not added to the new node, it is left empty for
121671 ** now. Instead, the term is inserted into the parent of pTree. If pTree
121672 ** has no parent, one is created here.
121674 pNew = (SegmentNode *)sqlite3_malloc(sizeof(SegmentNode) + p->nNodeSize);
121675 if( !pNew ){
121676 return SQLITE_NOMEM;
121678 memset(pNew, 0, sizeof(SegmentNode));
121679 pNew->nData = 1 + FTS3_VARINT_MAX;
121680 pNew->aData = (char *)&pNew[1];
121682 if( pTree ){
121683 SegmentNode *pParent = pTree->pParent;
121684 rc = fts3NodeAddTerm(p, &pParent, isCopyTerm, zTerm, nTerm);
121685 if( pTree->pParent==0 ){
121686 pTree->pParent = pParent;
121688 pTree->pRight = pNew;
121689 pNew->pLeftmost = pTree->pLeftmost;
121690 pNew->pParent = pParent;
121691 pNew->zMalloc = pTree->zMalloc;
121692 pNew->nMalloc = pTree->nMalloc;
121693 pTree->zMalloc = 0;
121694 }else{
121695 pNew->pLeftmost = pNew;
121696 rc = fts3NodeAddTerm(p, &pNew, isCopyTerm, zTerm, nTerm);
121699 *ppTree = pNew;
121700 return rc;
121704 ** Helper function for fts3NodeWrite().
121706 static int fts3TreeFinishNode(
121707 SegmentNode *pTree,
121708 int iHeight,
121709 sqlite3_int64 iLeftChild
121711 int nStart;
121712 assert( iHeight>=1 && iHeight<128 );
121713 nStart = FTS3_VARINT_MAX - sqlite3Fts3VarintLen(iLeftChild);
121714 pTree->aData[nStart] = (char)iHeight;
121715 sqlite3Fts3PutVarint(&pTree->aData[nStart+1], iLeftChild);
121716 return nStart;
121720 ** Write the buffer for the segment node pTree and all of its peers to the
121721 ** database. Then call this function recursively to write the parent of
121722 ** pTree and its peers to the database.
121724 ** Except, if pTree is a root node, do not write it to the database. Instead,
121725 ** set output variables *paRoot and *pnRoot to contain the root node.
121727 ** If successful, SQLITE_OK is returned and output variable *piLast is
121728 ** set to the largest blockid written to the database (or zero if no
121729 ** blocks were written to the db). Otherwise, an SQLite error code is
121730 ** returned.
121732 static int fts3NodeWrite(
121733 Fts3Table *p, /* Virtual table handle */
121734 SegmentNode *pTree, /* SegmentNode handle */
121735 int iHeight, /* Height of this node in tree */
121736 sqlite3_int64 iLeaf, /* Block id of first leaf node */
121737 sqlite3_int64 iFree, /* Block id of next free slot in %_segments */
121738 sqlite3_int64 *piLast, /* OUT: Block id of last entry written */
121739 char **paRoot, /* OUT: Data for root node */
121740 int *pnRoot /* OUT: Size of root node in bytes */
121742 int rc = SQLITE_OK;
121744 if( !pTree->pParent ){
121745 /* Root node of the tree. */
121746 int nStart = fts3TreeFinishNode(pTree, iHeight, iLeaf);
121747 *piLast = iFree-1;
121748 *pnRoot = pTree->nData - nStart;
121749 *paRoot = &pTree->aData[nStart];
121750 }else{
121751 SegmentNode *pIter;
121752 sqlite3_int64 iNextFree = iFree;
121753 sqlite3_int64 iNextLeaf = iLeaf;
121754 for(pIter=pTree->pLeftmost; pIter && rc==SQLITE_OK; pIter=pIter->pRight){
121755 int nStart = fts3TreeFinishNode(pIter, iHeight, iNextLeaf);
121756 int nWrite = pIter->nData - nStart;
121758 rc = fts3WriteSegment(p, iNextFree, &pIter->aData[nStart], nWrite);
121759 iNextFree++;
121760 iNextLeaf += (pIter->nEntry+1);
121762 if( rc==SQLITE_OK ){
121763 assert( iNextLeaf==iFree );
121764 rc = fts3NodeWrite(
121765 p, pTree->pParent, iHeight+1, iFree, iNextFree, piLast, paRoot, pnRoot
121770 return rc;
121774 ** Free all memory allocations associated with the tree pTree.
121776 static void fts3NodeFree(SegmentNode *pTree){
121777 if( pTree ){
121778 SegmentNode *p = pTree->pLeftmost;
121779 fts3NodeFree(p->pParent);
121780 while( p ){
121781 SegmentNode *pRight = p->pRight;
121782 if( p->aData!=(char *)&p[1] ){
121783 sqlite3_free(p->aData);
121785 assert( pRight==0 || p->zMalloc==0 );
121786 sqlite3_free(p->zMalloc);
121787 sqlite3_free(p);
121788 p = pRight;
121794 ** Add a term to the segment being constructed by the SegmentWriter object
121795 ** *ppWriter. When adding the first term to a segment, *ppWriter should
121796 ** be passed NULL. This function will allocate a new SegmentWriter object
121797 ** and return it via the input/output variable *ppWriter in this case.
121799 ** If successful, SQLITE_OK is returned. Otherwise, an SQLite error code.
121801 static int fts3SegWriterAdd(
121802 Fts3Table *p, /* Virtual table handle */
121803 SegmentWriter **ppWriter, /* IN/OUT: SegmentWriter handle */
121804 int isCopyTerm, /* True if buffer zTerm must be copied */
121805 const char *zTerm, /* Pointer to buffer containing term */
121806 int nTerm, /* Size of term in bytes */
121807 const char *aDoclist, /* Pointer to buffer containing doclist */
121808 int nDoclist /* Size of doclist in bytes */
121810 int nPrefix; /* Size of term prefix in bytes */
121811 int nSuffix; /* Size of term suffix in bytes */
121812 int nReq; /* Number of bytes required on leaf page */
121813 int nData;
121814 SegmentWriter *pWriter = *ppWriter;
121816 if( !pWriter ){
121817 int rc;
121818 sqlite3_stmt *pStmt;
121820 /* Allocate the SegmentWriter structure */
121821 pWriter = (SegmentWriter *)sqlite3_malloc(sizeof(SegmentWriter));
121822 if( !pWriter ) return SQLITE_NOMEM;
121823 memset(pWriter, 0, sizeof(SegmentWriter));
121824 *ppWriter = pWriter;
121826 /* Allocate a buffer in which to accumulate data */
121827 pWriter->aData = (char *)sqlite3_malloc(p->nNodeSize);
121828 if( !pWriter->aData ) return SQLITE_NOMEM;
121829 pWriter->nSize = p->nNodeSize;
121831 /* Find the next free blockid in the %_segments table */
121832 rc = fts3SqlStmt(p, SQL_NEXT_SEGMENTS_ID, &pStmt, 0);
121833 if( rc!=SQLITE_OK ) return rc;
121834 if( SQLITE_ROW==sqlite3_step(pStmt) ){
121835 pWriter->iFree = sqlite3_column_int64(pStmt, 0);
121836 pWriter->iFirst = pWriter->iFree;
121838 rc = sqlite3_reset(pStmt);
121839 if( rc!=SQLITE_OK ) return rc;
121841 nData = pWriter->nData;
121843 nPrefix = fts3PrefixCompress(pWriter->zTerm, pWriter->nTerm, zTerm, nTerm);
121844 nSuffix = nTerm-nPrefix;
121846 /* Figure out how many bytes are required by this new entry */
121847 nReq = sqlite3Fts3VarintLen(nPrefix) + /* varint containing prefix size */
121848 sqlite3Fts3VarintLen(nSuffix) + /* varint containing suffix size */
121849 nSuffix + /* Term suffix */
121850 sqlite3Fts3VarintLen(nDoclist) + /* Size of doclist */
121851 nDoclist; /* Doclist data */
121853 if( nData>0 && nData+nReq>p->nNodeSize ){
121854 int rc;
121856 /* The current leaf node is full. Write it out to the database. */
121857 rc = fts3WriteSegment(p, pWriter->iFree++, pWriter->aData, nData);
121858 if( rc!=SQLITE_OK ) return rc;
121860 /* Add the current term to the interior node tree. The term added to
121861 ** the interior tree must:
121863 ** a) be greater than the largest term on the leaf node just written
121864 ** to the database (still available in pWriter->zTerm), and
121866 ** b) be less than or equal to the term about to be added to the new
121867 ** leaf node (zTerm/nTerm).
121869 ** In other words, it must be the prefix of zTerm 1 byte longer than
121870 ** the common prefix (if any) of zTerm and pWriter->zTerm.
121872 assert( nPrefix<nTerm );
121873 rc = fts3NodeAddTerm(p, &pWriter->pTree, isCopyTerm, zTerm, nPrefix+1);
121874 if( rc!=SQLITE_OK ) return rc;
121876 nData = 0;
121877 pWriter->nTerm = 0;
121879 nPrefix = 0;
121880 nSuffix = nTerm;
121881 nReq = 1 + /* varint containing prefix size */
121882 sqlite3Fts3VarintLen(nTerm) + /* varint containing suffix size */
121883 nTerm + /* Term suffix */
121884 sqlite3Fts3VarintLen(nDoclist) + /* Size of doclist */
121885 nDoclist; /* Doclist data */
121888 /* If the buffer currently allocated is too small for this entry, realloc
121889 ** the buffer to make it large enough.
121891 if( nReq>pWriter->nSize ){
121892 char *aNew = sqlite3_realloc(pWriter->aData, nReq);
121893 if( !aNew ) return SQLITE_NOMEM;
121894 pWriter->aData = aNew;
121895 pWriter->nSize = nReq;
121897 assert( nData+nReq<=pWriter->nSize );
121899 /* Append the prefix-compressed term and doclist to the buffer. */
121900 nData += sqlite3Fts3PutVarint(&pWriter->aData[nData], nPrefix);
121901 nData += sqlite3Fts3PutVarint(&pWriter->aData[nData], nSuffix);
121902 memcpy(&pWriter->aData[nData], &zTerm[nPrefix], nSuffix);
121903 nData += nSuffix;
121904 nData += sqlite3Fts3PutVarint(&pWriter->aData[nData], nDoclist);
121905 memcpy(&pWriter->aData[nData], aDoclist, nDoclist);
121906 pWriter->nData = nData + nDoclist;
121908 /* Save the current term so that it can be used to prefix-compress the next.
121909 ** If the isCopyTerm parameter is true, then the buffer pointed to by
121910 ** zTerm is transient, so take a copy of the term data. Otherwise, just
121911 ** store a copy of the pointer.
121913 if( isCopyTerm ){
121914 if( nTerm>pWriter->nMalloc ){
121915 char *zNew = sqlite3_realloc(pWriter->zMalloc, nTerm*2);
121916 if( !zNew ){
121917 return SQLITE_NOMEM;
121919 pWriter->nMalloc = nTerm*2;
121920 pWriter->zMalloc = zNew;
121921 pWriter->zTerm = zNew;
121923 assert( pWriter->zTerm==pWriter->zMalloc );
121924 memcpy(pWriter->zTerm, zTerm, nTerm);
121925 }else{
121926 pWriter->zTerm = (char *)zTerm;
121928 pWriter->nTerm = nTerm;
121930 return SQLITE_OK;
121934 ** Flush all data associated with the SegmentWriter object pWriter to the
121935 ** database. This function must be called after all terms have been added
121936 ** to the segment using fts3SegWriterAdd(). If successful, SQLITE_OK is
121937 ** returned. Otherwise, an SQLite error code.
121939 static int fts3SegWriterFlush(
121940 Fts3Table *p, /* Virtual table handle */
121941 SegmentWriter *pWriter, /* SegmentWriter to flush to the db */
121942 int iLevel, /* Value for 'level' column of %_segdir */
121943 int iIdx /* Value for 'idx' column of %_segdir */
121945 int rc; /* Return code */
121946 if( pWriter->pTree ){
121947 sqlite3_int64 iLast = 0; /* Largest block id written to database */
121948 sqlite3_int64 iLastLeaf; /* Largest leaf block id written to db */
121949 char *zRoot = NULL; /* Pointer to buffer containing root node */
121950 int nRoot = 0; /* Size of buffer zRoot */
121952 iLastLeaf = pWriter->iFree;
121953 rc = fts3WriteSegment(p, pWriter->iFree++, pWriter->aData, pWriter->nData);
121954 if( rc==SQLITE_OK ){
121955 rc = fts3NodeWrite(p, pWriter->pTree, 1,
121956 pWriter->iFirst, pWriter->iFree, &iLast, &zRoot, &nRoot);
121958 if( rc==SQLITE_OK ){
121959 rc = fts3WriteSegdir(
121960 p, iLevel, iIdx, pWriter->iFirst, iLastLeaf, iLast, zRoot, nRoot);
121962 }else{
121963 /* The entire tree fits on the root node. Write it to the segdir table. */
121964 rc = fts3WriteSegdir(
121965 p, iLevel, iIdx, 0, 0, 0, pWriter->aData, pWriter->nData);
121967 return rc;
121971 ** Release all memory held by the SegmentWriter object passed as the
121972 ** first argument.
121974 static void fts3SegWriterFree(SegmentWriter *pWriter){
121975 if( pWriter ){
121976 sqlite3_free(pWriter->aData);
121977 sqlite3_free(pWriter->zMalloc);
121978 fts3NodeFree(pWriter->pTree);
121979 sqlite3_free(pWriter);
121984 ** The first value in the apVal[] array is assumed to contain an integer.
121985 ** This function tests if there exist any documents with docid values that
121986 ** are different from that integer. i.e. if deleting the document with docid
121987 ** apVal[0] would mean the FTS3 table were empty.
121989 ** If successful, *pisEmpty is set to true if the table is empty except for
121990 ** document apVal[0], or false otherwise, and SQLITE_OK is returned. If an
121991 ** error occurs, an SQLite error code is returned.
121993 static int fts3IsEmpty(Fts3Table *p, sqlite3_value **apVal, int *pisEmpty){
121994 sqlite3_stmt *pStmt;
121995 int rc;
121996 rc = fts3SqlStmt(p, SQL_IS_EMPTY, &pStmt, apVal);
121997 if( rc==SQLITE_OK ){
121998 if( SQLITE_ROW==sqlite3_step(pStmt) ){
121999 *pisEmpty = sqlite3_column_int(pStmt, 0);
122001 rc = sqlite3_reset(pStmt);
122003 return rc;
122007 ** Set *pnSegment to the total number of segments in the database. Set
122008 ** *pnMax to the largest segment level in the database (segment levels
122009 ** are stored in the 'level' column of the %_segdir table).
122011 ** Return SQLITE_OK if successful, or an SQLite error code if not.
122013 static int fts3SegmentCountMax(Fts3Table *p, int *pnSegment, int *pnMax){
122014 sqlite3_stmt *pStmt;
122015 int rc;
122017 rc = fts3SqlStmt(p, SQL_SELECT_SEGDIR_COUNT_MAX, &pStmt, 0);
122018 if( rc!=SQLITE_OK ) return rc;
122019 if( SQLITE_ROW==sqlite3_step(pStmt) ){
122020 *pnSegment = sqlite3_column_int(pStmt, 0);
122021 *pnMax = sqlite3_column_int(pStmt, 1);
122023 return sqlite3_reset(pStmt);
122027 ** This function is used after merging multiple segments into a single large
122028 ** segment to delete the old, now redundant, segment b-trees. Specifically,
122029 ** it:
122031 ** 1) Deletes all %_segments entries for the segments associated with
122032 ** each of the SegReader objects in the array passed as the third
122033 ** argument, and
122035 ** 2) deletes all %_segdir entries with level iLevel, or all %_segdir
122036 ** entries regardless of level if (iLevel<0).
122038 ** SQLITE_OK is returned if successful, otherwise an SQLite error code.
122040 static int fts3DeleteSegdir(
122041 Fts3Table *p, /* Virtual table handle */
122042 int iLevel, /* Level of %_segdir entries to delete */
122043 Fts3SegReader **apSegment, /* Array of SegReader objects */
122044 int nReader /* Size of array apSegment */
122046 int rc; /* Return Code */
122047 int i; /* Iterator variable */
122048 sqlite3_stmt *pDelete; /* SQL statement to delete rows */
122050 rc = fts3SqlStmt(p, SQL_DELETE_SEGMENTS_RANGE, &pDelete, 0);
122051 for(i=0; rc==SQLITE_OK && i<nReader; i++){
122052 Fts3SegReader *pSegment = apSegment[i];
122053 if( pSegment->iStartBlock ){
122054 sqlite3_bind_int64(pDelete, 1, pSegment->iStartBlock);
122055 sqlite3_bind_int64(pDelete, 2, pSegment->iEndBlock);
122056 sqlite3_step(pDelete);
122057 rc = sqlite3_reset(pDelete);
122060 if( rc!=SQLITE_OK ){
122061 return rc;
122064 if( iLevel==FTS3_SEGCURSOR_ALL ){
122065 fts3SqlExec(&rc, p, SQL_DELETE_ALL_SEGDIR, 0);
122066 }else if( iLevel==FTS3_SEGCURSOR_PENDING ){
122067 sqlite3Fts3PendingTermsClear(p);
122068 }else{
122069 assert( iLevel>=0 );
122070 rc = fts3SqlStmt(p, SQL_DELETE_SEGDIR_BY_LEVEL, &pDelete, 0);
122071 if( rc==SQLITE_OK ){
122072 sqlite3_bind_int(pDelete, 1, iLevel);
122073 sqlite3_step(pDelete);
122074 rc = sqlite3_reset(pDelete);
122078 return rc;
122082 ** When this function is called, buffer *ppList (size *pnList bytes) contains
122083 ** a position list that may (or may not) feature multiple columns. This
122084 ** function adjusts the pointer *ppList and the length *pnList so that they
122085 ** identify the subset of the position list that corresponds to column iCol.
122087 ** If there are no entries in the input position list for column iCol, then
122088 ** *pnList is set to zero before returning.
122090 static void fts3ColumnFilter(
122091 int iCol, /* Column to filter on */
122092 char **ppList, /* IN/OUT: Pointer to position list */
122093 int *pnList /* IN/OUT: Size of buffer *ppList in bytes */
122095 char *pList = *ppList;
122096 int nList = *pnList;
122097 char *pEnd = &pList[nList];
122098 int iCurrent = 0;
122099 char *p = pList;
122101 assert( iCol>=0 );
122102 while( 1 ){
122103 char c = 0;
122104 while( p<pEnd && (c | *p)&0xFE ) c = *p++ & 0x80;
122106 if( iCol==iCurrent ){
122107 nList = (int)(p - pList);
122108 break;
122111 nList -= (int)(p - pList);
122112 pList = p;
122113 if( nList==0 ){
122114 break;
122116 p = &pList[1];
122117 p += sqlite3Fts3GetVarint32(p, &iCurrent);
122120 *ppList = pList;
122121 *pnList = nList;
122124 SQLITE_PRIVATE int sqlite3Fts3SegReaderStart(
122125 Fts3Table *p, /* Virtual table handle */
122126 Fts3SegReaderCursor *pCsr, /* Cursor object */
122127 Fts3SegFilter *pFilter /* Restrictions on range of iteration */
122129 int i;
122131 /* Initialize the cursor object */
122132 pCsr->pFilter = pFilter;
122134 /* If the Fts3SegFilter defines a specific term (or term prefix) to search
122135 ** for, then advance each segment iterator until it points to a term of
122136 ** equal or greater value than the specified term. This prevents many
122137 ** unnecessary merge/sort operations for the case where single segment
122138 ** b-tree leaf nodes contain more than one term.
122140 for(i=0; i<pCsr->nSegment; i++){
122141 int nTerm = pFilter->nTerm;
122142 const char *zTerm = pFilter->zTerm;
122143 Fts3SegReader *pSeg = pCsr->apSegment[i];
122145 int rc = fts3SegReaderNext(p, pSeg);
122146 if( rc!=SQLITE_OK ) return rc;
122147 }while( zTerm && fts3SegReaderTermCmp(pSeg, zTerm, nTerm)<0 );
122149 fts3SegReaderSort(
122150 pCsr->apSegment, pCsr->nSegment, pCsr->nSegment, fts3SegReaderCmp);
122152 return SQLITE_OK;
122155 SQLITE_PRIVATE int sqlite3Fts3SegReaderStep(
122156 Fts3Table *p, /* Virtual table handle */
122157 Fts3SegReaderCursor *pCsr /* Cursor object */
122159 int rc = SQLITE_OK;
122161 int isIgnoreEmpty = (pCsr->pFilter->flags & FTS3_SEGMENT_IGNORE_EMPTY);
122162 int isRequirePos = (pCsr->pFilter->flags & FTS3_SEGMENT_REQUIRE_POS);
122163 int isColFilter = (pCsr->pFilter->flags & FTS3_SEGMENT_COLUMN_FILTER);
122164 int isPrefix = (pCsr->pFilter->flags & FTS3_SEGMENT_PREFIX);
122165 int isScan = (pCsr->pFilter->flags & FTS3_SEGMENT_SCAN);
122167 Fts3SegReader **apSegment = pCsr->apSegment;
122168 int nSegment = pCsr->nSegment;
122169 Fts3SegFilter *pFilter = pCsr->pFilter;
122171 if( pCsr->nSegment==0 ) return SQLITE_OK;
122174 int nMerge;
122175 int i;
122177 /* Advance the first pCsr->nAdvance entries in the apSegment[] array
122178 ** forward. Then sort the list in order of current term again.
122180 for(i=0; i<pCsr->nAdvance; i++){
122181 rc = fts3SegReaderNext(p, apSegment[i]);
122182 if( rc!=SQLITE_OK ) return rc;
122184 fts3SegReaderSort(apSegment, nSegment, pCsr->nAdvance, fts3SegReaderCmp);
122185 pCsr->nAdvance = 0;
122187 /* If all the seg-readers are at EOF, we're finished. return SQLITE_OK. */
122188 assert( rc==SQLITE_OK );
122189 if( apSegment[0]->aNode==0 ) break;
122191 pCsr->nTerm = apSegment[0]->nTerm;
122192 pCsr->zTerm = apSegment[0]->zTerm;
122194 /* If this is a prefix-search, and if the term that apSegment[0] points
122195 ** to does not share a suffix with pFilter->zTerm/nTerm, then all
122196 ** required callbacks have been made. In this case exit early.
122198 ** Similarly, if this is a search for an exact match, and the first term
122199 ** of segment apSegment[0] is not a match, exit early.
122201 if( pFilter->zTerm && !isScan ){
122202 if( pCsr->nTerm<pFilter->nTerm
122203 || (!isPrefix && pCsr->nTerm>pFilter->nTerm)
122204 || memcmp(pCsr->zTerm, pFilter->zTerm, pFilter->nTerm)
122206 break;
122210 nMerge = 1;
122211 while( nMerge<nSegment
122212 && apSegment[nMerge]->aNode
122213 && apSegment[nMerge]->nTerm==pCsr->nTerm
122214 && 0==memcmp(pCsr->zTerm, apSegment[nMerge]->zTerm, pCsr->nTerm)
122216 nMerge++;
122219 assert( isIgnoreEmpty || (isRequirePos && !isColFilter) );
122220 if( nMerge==1 && !isIgnoreEmpty ){
122221 pCsr->aDoclist = apSegment[0]->aDoclist;
122222 pCsr->nDoclist = apSegment[0]->nDoclist;
122223 rc = SQLITE_ROW;
122224 }else{
122225 int nDoclist = 0; /* Size of doclist */
122226 sqlite3_int64 iPrev = 0; /* Previous docid stored in doclist */
122228 /* The current term of the first nMerge entries in the array
122229 ** of Fts3SegReader objects is the same. The doclists must be merged
122230 ** and a single term returned with the merged doclist.
122232 for(i=0; i<nMerge; i++){
122233 fts3SegReaderFirstDocid(apSegment[i]);
122235 fts3SegReaderSort(apSegment, nMerge, nMerge, fts3SegReaderDoclistCmp);
122236 while( apSegment[0]->pOffsetList ){
122237 int j; /* Number of segments that share a docid */
122238 char *pList;
122239 int nList;
122240 int nByte;
122241 sqlite3_int64 iDocid = apSegment[0]->iDocid;
122242 fts3SegReaderNextDocid(apSegment[0], &pList, &nList);
122243 j = 1;
122244 while( j<nMerge
122245 && apSegment[j]->pOffsetList
122246 && apSegment[j]->iDocid==iDocid
122248 fts3SegReaderNextDocid(apSegment[j], 0, 0);
122252 if( isColFilter ){
122253 fts3ColumnFilter(pFilter->iCol, &pList, &nList);
122256 if( !isIgnoreEmpty || nList>0 ){
122257 nByte = sqlite3Fts3VarintLen(iDocid-iPrev) + (isRequirePos?nList+1:0);
122258 if( nDoclist+nByte>pCsr->nBuffer ){
122259 char *aNew;
122260 pCsr->nBuffer = (nDoclist+nByte)*2;
122261 aNew = sqlite3_realloc(pCsr->aBuffer, pCsr->nBuffer);
122262 if( !aNew ){
122263 return SQLITE_NOMEM;
122265 pCsr->aBuffer = aNew;
122267 nDoclist += sqlite3Fts3PutVarint(
122268 &pCsr->aBuffer[nDoclist], iDocid-iPrev
122270 iPrev = iDocid;
122271 if( isRequirePos ){
122272 memcpy(&pCsr->aBuffer[nDoclist], pList, nList);
122273 nDoclist += nList;
122274 pCsr->aBuffer[nDoclist++] = '\0';
122278 fts3SegReaderSort(apSegment, nMerge, j, fts3SegReaderDoclistCmp);
122280 if( nDoclist>0 ){
122281 pCsr->aDoclist = pCsr->aBuffer;
122282 pCsr->nDoclist = nDoclist;
122283 rc = SQLITE_ROW;
122286 pCsr->nAdvance = nMerge;
122287 }while( rc==SQLITE_OK );
122289 return rc;
122292 SQLITE_PRIVATE void sqlite3Fts3SegReaderFinish(
122293 Fts3SegReaderCursor *pCsr /* Cursor object */
122295 if( pCsr ){
122296 int i;
122297 for(i=0; i<pCsr->nSegment; i++){
122298 sqlite3Fts3SegReaderFree(pCsr->apSegment[i]);
122300 sqlite3_free(pCsr->apSegment);
122301 sqlite3_free(pCsr->aBuffer);
122303 pCsr->nSegment = 0;
122304 pCsr->apSegment = 0;
122305 pCsr->aBuffer = 0;
122310 ** Merge all level iLevel segments in the database into a single
122311 ** iLevel+1 segment. Or, if iLevel<0, merge all segments into a
122312 ** single segment with a level equal to the numerically largest level
122313 ** currently present in the database.
122315 ** If this function is called with iLevel<0, but there is only one
122316 ** segment in the database, SQLITE_DONE is returned immediately.
122317 ** Otherwise, if successful, SQLITE_OK is returned. If an error occurs,
122318 ** an SQLite error code is returned.
122320 static int fts3SegmentMerge(Fts3Table *p, int iLevel){
122321 int rc; /* Return code */
122322 int iIdx = 0; /* Index of new segment */
122323 int iNewLevel = 0; /* Level to create new segment at */
122324 SegmentWriter *pWriter = 0; /* Used to write the new, merged, segment */
122325 Fts3SegFilter filter; /* Segment term filter condition */
122326 Fts3SegReaderCursor csr; /* Cursor to iterate through level(s) */
122328 rc = sqlite3Fts3SegReaderCursor(p, iLevel, 0, 0, 1, 0, &csr);
122329 if( rc!=SQLITE_OK || csr.nSegment==0 ) goto finished;
122331 if( iLevel==FTS3_SEGCURSOR_ALL ){
122332 /* This call is to merge all segments in the database to a single
122333 ** segment. The level of the new segment is equal to the the numerically
122334 ** greatest segment level currently present in the database. The index
122335 ** of the new segment is always 0. */
122336 int nDummy; /* TODO: Remove this */
122337 if( csr.nSegment==1 ){
122338 rc = SQLITE_DONE;
122339 goto finished;
122341 rc = fts3SegmentCountMax(p, &nDummy, &iNewLevel);
122342 }else{
122343 /* This call is to merge all segments at level iLevel. Find the next
122344 ** available segment index at level iLevel+1. The call to
122345 ** fts3AllocateSegdirIdx() will merge the segments at level iLevel+1 to
122346 ** a single iLevel+2 segment if necessary. */
122347 iNewLevel = iLevel+1;
122348 rc = fts3AllocateSegdirIdx(p, iNewLevel, &iIdx);
122350 if( rc!=SQLITE_OK ) goto finished;
122351 assert( csr.nSegment>0 );
122352 assert( iNewLevel>=0 );
122354 memset(&filter, 0, sizeof(Fts3SegFilter));
122355 filter.flags = FTS3_SEGMENT_REQUIRE_POS;
122356 filter.flags |= (iLevel==FTS3_SEGCURSOR_ALL ? FTS3_SEGMENT_IGNORE_EMPTY : 0);
122358 rc = sqlite3Fts3SegReaderStart(p, &csr, &filter);
122359 while( SQLITE_OK==rc ){
122360 rc = sqlite3Fts3SegReaderStep(p, &csr);
122361 if( rc!=SQLITE_ROW ) break;
122362 rc = fts3SegWriterAdd(p, &pWriter, 1,
122363 csr.zTerm, csr.nTerm, csr.aDoclist, csr.nDoclist);
122365 if( rc!=SQLITE_OK ) goto finished;
122366 assert( pWriter );
122368 rc = fts3DeleteSegdir(p, iLevel, csr.apSegment, csr.nSegment);
122369 if( rc!=SQLITE_OK ) goto finished;
122370 rc = fts3SegWriterFlush(p, pWriter, iNewLevel, iIdx);
122372 finished:
122373 fts3SegWriterFree(pWriter);
122374 sqlite3Fts3SegReaderFinish(&csr);
122375 return rc;
122380 ** Flush the contents of pendingTerms to a level 0 segment.
122382 SQLITE_PRIVATE int sqlite3Fts3PendingTermsFlush(Fts3Table *p){
122383 return fts3SegmentMerge(p, FTS3_SEGCURSOR_PENDING);
122387 ** Encode N integers as varints into a blob.
122389 static void fts3EncodeIntArray(
122390 int N, /* The number of integers to encode */
122391 u32 *a, /* The integer values */
122392 char *zBuf, /* Write the BLOB here */
122393 int *pNBuf /* Write number of bytes if zBuf[] used here */
122395 int i, j;
122396 for(i=j=0; i<N; i++){
122397 j += sqlite3Fts3PutVarint(&zBuf[j], (sqlite3_int64)a[i]);
122399 *pNBuf = j;
122403 ** Decode a blob of varints into N integers
122405 static void fts3DecodeIntArray(
122406 int N, /* The number of integers to decode */
122407 u32 *a, /* Write the integer values */
122408 const char *zBuf, /* The BLOB containing the varints */
122409 int nBuf /* size of the BLOB */
122411 int i, j;
122412 UNUSED_PARAMETER(nBuf);
122413 for(i=j=0; i<N; i++){
122414 sqlite3_int64 x;
122415 j += sqlite3Fts3GetVarint(&zBuf[j], &x);
122416 assert(j<=nBuf);
122417 a[i] = (u32)(x & 0xffffffff);
122422 ** Insert the sizes (in tokens) for each column of the document
122423 ** with docid equal to p->iPrevDocid. The sizes are encoded as
122424 ** a blob of varints.
122426 static void fts3InsertDocsize(
122427 int *pRC, /* Result code */
122428 Fts3Table *p, /* Table into which to insert */
122429 u32 *aSz /* Sizes of each column */
122431 char *pBlob; /* The BLOB encoding of the document size */
122432 int nBlob; /* Number of bytes in the BLOB */
122433 sqlite3_stmt *pStmt; /* Statement used to insert the encoding */
122434 int rc; /* Result code from subfunctions */
122436 if( *pRC ) return;
122437 pBlob = sqlite3_malloc( 10*p->nColumn );
122438 if( pBlob==0 ){
122439 *pRC = SQLITE_NOMEM;
122440 return;
122442 fts3EncodeIntArray(p->nColumn, aSz, pBlob, &nBlob);
122443 rc = fts3SqlStmt(p, SQL_REPLACE_DOCSIZE, &pStmt, 0);
122444 if( rc ){
122445 sqlite3_free(pBlob);
122446 *pRC = rc;
122447 return;
122449 sqlite3_bind_int64(pStmt, 1, p->iPrevDocid);
122450 sqlite3_bind_blob(pStmt, 2, pBlob, nBlob, sqlite3_free);
122451 sqlite3_step(pStmt);
122452 *pRC = sqlite3_reset(pStmt);
122456 ** Record 0 of the %_stat table contains a blob consisting of N varints,
122457 ** where N is the number of user defined columns in the fts3 table plus
122458 ** two. If nCol is the number of user defined columns, then values of the
122459 ** varints are set as follows:
122461 ** Varint 0: Total number of rows in the table.
122463 ** Varint 1..nCol: For each column, the total number of tokens stored in
122464 ** the column for all rows of the table.
122466 ** Varint 1+nCol: The total size, in bytes, of all text values in all
122467 ** columns of all rows of the table.
122470 static void fts3UpdateDocTotals(
122471 int *pRC, /* The result code */
122472 Fts3Table *p, /* Table being updated */
122473 u32 *aSzIns, /* Size increases */
122474 u32 *aSzDel, /* Size decreases */
122475 int nChng /* Change in the number of documents */
122477 char *pBlob; /* Storage for BLOB written into %_stat */
122478 int nBlob; /* Size of BLOB written into %_stat */
122479 u32 *a; /* Array of integers that becomes the BLOB */
122480 sqlite3_stmt *pStmt; /* Statement for reading and writing */
122481 int i; /* Loop counter */
122482 int rc; /* Result code from subfunctions */
122484 const int nStat = p->nColumn+2;
122486 if( *pRC ) return;
122487 a = sqlite3_malloc( (sizeof(u32)+10)*nStat );
122488 if( a==0 ){
122489 *pRC = SQLITE_NOMEM;
122490 return;
122492 pBlob = (char*)&a[nStat];
122493 rc = fts3SqlStmt(p, SQL_SELECT_DOCTOTAL, &pStmt, 0);
122494 if( rc ){
122495 sqlite3_free(a);
122496 *pRC = rc;
122497 return;
122499 if( sqlite3_step(pStmt)==SQLITE_ROW ){
122500 fts3DecodeIntArray(nStat, a,
122501 sqlite3_column_blob(pStmt, 0),
122502 sqlite3_column_bytes(pStmt, 0));
122503 }else{
122504 memset(a, 0, sizeof(u32)*(nStat) );
122506 sqlite3_reset(pStmt);
122507 if( nChng<0 && a[0]<(u32)(-nChng) ){
122508 a[0] = 0;
122509 }else{
122510 a[0] += nChng;
122512 for(i=0; i<p->nColumn+1; i++){
122513 u32 x = a[i+1];
122514 if( x+aSzIns[i] < aSzDel[i] ){
122515 x = 0;
122516 }else{
122517 x = x + aSzIns[i] - aSzDel[i];
122519 a[i+1] = x;
122521 fts3EncodeIntArray(nStat, a, pBlob, &nBlob);
122522 rc = fts3SqlStmt(p, SQL_REPLACE_DOCTOTAL, &pStmt, 0);
122523 if( rc ){
122524 sqlite3_free(a);
122525 *pRC = rc;
122526 return;
122528 sqlite3_bind_blob(pStmt, 1, pBlob, nBlob, SQLITE_STATIC);
122529 sqlite3_step(pStmt);
122530 *pRC = sqlite3_reset(pStmt);
122531 sqlite3_free(a);
122535 ** Handle a 'special' INSERT of the form:
122537 ** "INSERT INTO tbl(tbl) VALUES(<expr>)"
122539 ** Argument pVal contains the result of <expr>. Currently the only
122540 ** meaningful value to insert is the text 'optimize'.
122542 static int fts3SpecialInsert(Fts3Table *p, sqlite3_value *pVal){
122543 int rc; /* Return Code */
122544 const char *zVal = (const char *)sqlite3_value_text(pVal);
122545 int nVal = sqlite3_value_bytes(pVal);
122547 if( !zVal ){
122548 return SQLITE_NOMEM;
122549 }else if( nVal==8 && 0==sqlite3_strnicmp(zVal, "optimize", 8) ){
122550 rc = fts3SegmentMerge(p, FTS3_SEGCURSOR_ALL);
122551 if( rc==SQLITE_DONE ){
122552 rc = SQLITE_OK;
122553 }else{
122554 sqlite3Fts3PendingTermsClear(p);
122556 #ifdef SQLITE_TEST
122557 }else if( nVal>9 && 0==sqlite3_strnicmp(zVal, "nodesize=", 9) ){
122558 p->nNodeSize = atoi(&zVal[9]);
122559 rc = SQLITE_OK;
122560 }else if( nVal>11 && 0==sqlite3_strnicmp(zVal, "maxpending=", 9) ){
122561 p->nMaxPendingData = atoi(&zVal[11]);
122562 rc = SQLITE_OK;
122563 #endif
122564 }else{
122565 rc = SQLITE_ERROR;
122568 sqlite3Fts3SegmentsClose(p);
122569 return rc;
122573 ** Return the deferred doclist associated with deferred token pDeferred.
122574 ** This function assumes that sqlite3Fts3CacheDeferredDoclists() has already
122575 ** been called to allocate and populate the doclist.
122577 SQLITE_PRIVATE char *sqlite3Fts3DeferredDoclist(Fts3DeferredToken *pDeferred, int *pnByte){
122578 if( pDeferred->pList ){
122579 *pnByte = pDeferred->pList->nData;
122580 return pDeferred->pList->aData;
122582 *pnByte = 0;
122583 return 0;
122587 ** Helper fucntion for FreeDeferredDoclists(). This function removes all
122588 ** references to deferred doclists from within the tree of Fts3Expr
122589 ** structures headed by
122591 static void fts3DeferredDoclistClear(Fts3Expr *pExpr){
122592 if( pExpr ){
122593 fts3DeferredDoclistClear(pExpr->pLeft);
122594 fts3DeferredDoclistClear(pExpr->pRight);
122595 if( pExpr->isLoaded ){
122596 sqlite3_free(pExpr->aDoclist);
122597 pExpr->isLoaded = 0;
122598 pExpr->aDoclist = 0;
122599 pExpr->nDoclist = 0;
122600 pExpr->pCurrent = 0;
122601 pExpr->iCurrent = 0;
122607 ** Delete all cached deferred doclists. Deferred doclists are cached
122608 ** (allocated) by the sqlite3Fts3CacheDeferredDoclists() function.
122610 SQLITE_PRIVATE void sqlite3Fts3FreeDeferredDoclists(Fts3Cursor *pCsr){
122611 Fts3DeferredToken *pDef;
122612 for(pDef=pCsr->pDeferred; pDef; pDef=pDef->pNext){
122613 sqlite3_free(pDef->pList);
122614 pDef->pList = 0;
122616 if( pCsr->pDeferred ){
122617 fts3DeferredDoclistClear(pCsr->pExpr);
122622 ** Free all entries in the pCsr->pDeffered list. Entries are added to
122623 ** this list using sqlite3Fts3DeferToken().
122625 SQLITE_PRIVATE void sqlite3Fts3FreeDeferredTokens(Fts3Cursor *pCsr){
122626 Fts3DeferredToken *pDef;
122627 Fts3DeferredToken *pNext;
122628 for(pDef=pCsr->pDeferred; pDef; pDef=pNext){
122629 pNext = pDef->pNext;
122630 sqlite3_free(pDef->pList);
122631 sqlite3_free(pDef);
122633 pCsr->pDeferred = 0;
122637 ** Generate deferred-doclists for all tokens in the pCsr->pDeferred list
122638 ** based on the row that pCsr currently points to.
122640 ** A deferred-doclist is like any other doclist with position information
122641 ** included, except that it only contains entries for a single row of the
122642 ** table, not for all rows.
122644 SQLITE_PRIVATE int sqlite3Fts3CacheDeferredDoclists(Fts3Cursor *pCsr){
122645 int rc = SQLITE_OK; /* Return code */
122646 if( pCsr->pDeferred ){
122647 int i; /* Used to iterate through table columns */
122648 sqlite3_int64 iDocid; /* Docid of the row pCsr points to */
122649 Fts3DeferredToken *pDef; /* Used to iterate through deferred tokens */
122651 Fts3Table *p = (Fts3Table *)pCsr->base.pVtab;
122652 sqlite3_tokenizer *pT = p->pTokenizer;
122653 sqlite3_tokenizer_module const *pModule = pT->pModule;
122655 assert( pCsr->isRequireSeek==0 );
122656 iDocid = sqlite3_column_int64(pCsr->pStmt, 0);
122658 for(i=0; i<p->nColumn && rc==SQLITE_OK; i++){
122659 const char *zText = (const char *)sqlite3_column_text(pCsr->pStmt, i+1);
122660 sqlite3_tokenizer_cursor *pTC = 0;
122662 rc = pModule->xOpen(pT, zText, -1, &pTC);
122663 while( rc==SQLITE_OK ){
122664 char const *zToken; /* Buffer containing token */
122665 int nToken; /* Number of bytes in token */
122666 int iDum1, iDum2; /* Dummy variables */
122667 int iPos; /* Position of token in zText */
122669 pTC->pTokenizer = pT;
122670 rc = pModule->xNext(pTC, &zToken, &nToken, &iDum1, &iDum2, &iPos);
122671 for(pDef=pCsr->pDeferred; pDef && rc==SQLITE_OK; pDef=pDef->pNext){
122672 Fts3PhraseToken *pPT = pDef->pToken;
122673 if( (pDef->iCol>=p->nColumn || pDef->iCol==i)
122674 && (pPT->n==nToken || (pPT->isPrefix && pPT->n<nToken))
122675 && (0==memcmp(zToken, pPT->z, pPT->n))
122677 fts3PendingListAppend(&pDef->pList, iDocid, i, iPos, &rc);
122681 if( pTC ) pModule->xClose(pTC);
122682 if( rc==SQLITE_DONE ) rc = SQLITE_OK;
122685 for(pDef=pCsr->pDeferred; pDef && rc==SQLITE_OK; pDef=pDef->pNext){
122686 if( pDef->pList ){
122687 rc = fts3PendingListAppendVarint(&pDef->pList, 0);
122692 return rc;
122696 ** Add an entry for token pToken to the pCsr->pDeferred list.
122698 SQLITE_PRIVATE int sqlite3Fts3DeferToken(
122699 Fts3Cursor *pCsr, /* Fts3 table cursor */
122700 Fts3PhraseToken *pToken, /* Token to defer */
122701 int iCol /* Column that token must appear in (or -1) */
122703 Fts3DeferredToken *pDeferred;
122704 pDeferred = sqlite3_malloc(sizeof(*pDeferred));
122705 if( !pDeferred ){
122706 return SQLITE_NOMEM;
122708 memset(pDeferred, 0, sizeof(*pDeferred));
122709 pDeferred->pToken = pToken;
122710 pDeferred->pNext = pCsr->pDeferred;
122711 pDeferred->iCol = iCol;
122712 pCsr->pDeferred = pDeferred;
122714 assert( pToken->pDeferred==0 );
122715 pToken->pDeferred = pDeferred;
122717 return SQLITE_OK;
122722 ** This function does the work for the xUpdate method of FTS3 virtual
122723 ** tables.
122725 SQLITE_PRIVATE int sqlite3Fts3UpdateMethod(
122726 sqlite3_vtab *pVtab, /* FTS3 vtab object */
122727 int nArg, /* Size of argument array */
122728 sqlite3_value **apVal, /* Array of arguments */
122729 sqlite_int64 *pRowid /* OUT: The affected (or effected) rowid */
122731 Fts3Table *p = (Fts3Table *)pVtab;
122732 int rc = SQLITE_OK; /* Return Code */
122733 int isRemove = 0; /* True for an UPDATE or DELETE */
122734 sqlite3_int64 iRemove = 0; /* Rowid removed by UPDATE or DELETE */
122735 u32 *aSzIns; /* Sizes of inserted documents */
122736 u32 *aSzDel; /* Sizes of deleted documents */
122737 int nChng = 0; /* Net change in number of documents */
122739 assert( p->pSegments==0 );
122741 /* Allocate space to hold the change in document sizes */
122742 aSzIns = sqlite3_malloc( sizeof(aSzIns[0])*(p->nColumn+1)*2 );
122743 if( aSzIns==0 ) return SQLITE_NOMEM;
122744 aSzDel = &aSzIns[p->nColumn+1];
122745 memset(aSzIns, 0, sizeof(aSzIns[0])*(p->nColumn+1)*2);
122747 /* If this is a DELETE or UPDATE operation, remove the old record. */
122748 if( sqlite3_value_type(apVal[0])!=SQLITE_NULL ){
122749 int isEmpty = 0;
122750 rc = fts3IsEmpty(p, apVal, &isEmpty);
122751 if( rc==SQLITE_OK ){
122752 if( isEmpty ){
122753 /* Deleting this row means the whole table is empty. In this case
122754 ** delete the contents of all three tables and throw away any
122755 ** data in the pendingTerms hash table.
122757 rc = fts3DeleteAll(p);
122758 }else{
122759 isRemove = 1;
122760 iRemove = sqlite3_value_int64(apVal[0]);
122761 rc = fts3PendingTermsDocid(p, iRemove);
122762 fts3DeleteTerms(&rc, p, apVal, aSzDel);
122763 fts3SqlExec(&rc, p, SQL_DELETE_CONTENT, apVal);
122764 if( p->bHasDocsize ){
122765 fts3SqlExec(&rc, p, SQL_DELETE_DOCSIZE, apVal);
122767 nChng--;
122770 }else if( sqlite3_value_type(apVal[p->nColumn+2])!=SQLITE_NULL ){
122771 sqlite3_free(aSzIns);
122772 return fts3SpecialInsert(p, apVal[p->nColumn+2]);
122775 /* If this is an INSERT or UPDATE operation, insert the new record. */
122776 if( nArg>1 && rc==SQLITE_OK ){
122777 rc = fts3InsertData(p, apVal, pRowid);
122778 if( rc==SQLITE_OK && (!isRemove || *pRowid!=iRemove) ){
122779 rc = fts3PendingTermsDocid(p, *pRowid);
122781 if( rc==SQLITE_OK ){
122782 rc = fts3InsertTerms(p, apVal, aSzIns);
122784 if( p->bHasDocsize ){
122785 fts3InsertDocsize(&rc, p, aSzIns);
122787 nChng++;
122790 if( p->bHasStat ){
122791 fts3UpdateDocTotals(&rc, p, aSzIns, aSzDel, nChng);
122794 sqlite3_free(aSzIns);
122795 sqlite3Fts3SegmentsClose(p);
122796 return rc;
122800 ** Flush any data in the pending-terms hash table to disk. If successful,
122801 ** merge all segments in the database (including the new segment, if
122802 ** there was any data to flush) into a single segment.
122804 SQLITE_PRIVATE int sqlite3Fts3Optimize(Fts3Table *p){
122805 int rc;
122806 rc = sqlite3_exec(p->db, "SAVEPOINT fts3", 0, 0, 0);
122807 if( rc==SQLITE_OK ){
122808 rc = fts3SegmentMerge(p, FTS3_SEGCURSOR_ALL);
122809 if( rc==SQLITE_OK ){
122810 rc = sqlite3_exec(p->db, "RELEASE fts3", 0, 0, 0);
122811 if( rc==SQLITE_OK ){
122812 sqlite3Fts3PendingTermsClear(p);
122814 }else{
122815 sqlite3_exec(p->db, "ROLLBACK TO fts3", 0, 0, 0);
122816 sqlite3_exec(p->db, "RELEASE fts3", 0, 0, 0);
122819 sqlite3Fts3SegmentsClose(p);
122820 return rc;
122823 #endif
122825 /************** End of fts3_write.c ******************************************/
122826 /************** Begin file fts3_snippet.c ************************************/
122828 ** 2009 Oct 23
122830 ** The author disclaims copyright to this source code. In place of
122831 ** a legal notice, here is a blessing:
122833 ** May you do good and not evil.
122834 ** May you find forgiveness for yourself and forgive others.
122835 ** May you share freely, never taking more than you give.
122837 ******************************************************************************
122840 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
122844 ** Characters that may appear in the second argument to matchinfo().
122846 #define FTS3_MATCHINFO_NPHRASE 'p' /* 1 value */
122847 #define FTS3_MATCHINFO_NCOL 'c' /* 1 value */
122848 #define FTS3_MATCHINFO_NDOC 'n' /* 1 value */
122849 #define FTS3_MATCHINFO_AVGLENGTH 'a' /* nCol values */
122850 #define FTS3_MATCHINFO_LENGTH 'l' /* nCol values */
122851 #define FTS3_MATCHINFO_LCS 's' /* nCol values */
122852 #define FTS3_MATCHINFO_HITS 'x' /* 3*nCol*nPhrase values */
122855 ** The default value for the second argument to matchinfo().
122857 #define FTS3_MATCHINFO_DEFAULT "pcx"
122861 ** Used as an fts3ExprIterate() context when loading phrase doclists to
122862 ** Fts3Expr.aDoclist[]/nDoclist.
122864 typedef struct LoadDoclistCtx LoadDoclistCtx;
122865 struct LoadDoclistCtx {
122866 Fts3Cursor *pCsr; /* FTS3 Cursor */
122867 int nPhrase; /* Number of phrases seen so far */
122868 int nToken; /* Number of tokens seen so far */
122872 ** The following types are used as part of the implementation of the
122873 ** fts3BestSnippet() routine.
122875 typedef struct SnippetIter SnippetIter;
122876 typedef struct SnippetPhrase SnippetPhrase;
122877 typedef struct SnippetFragment SnippetFragment;
122879 struct SnippetIter {
122880 Fts3Cursor *pCsr; /* Cursor snippet is being generated from */
122881 int iCol; /* Extract snippet from this column */
122882 int nSnippet; /* Requested snippet length (in tokens) */
122883 int nPhrase; /* Number of phrases in query */
122884 SnippetPhrase *aPhrase; /* Array of size nPhrase */
122885 int iCurrent; /* First token of current snippet */
122888 struct SnippetPhrase {
122889 int nToken; /* Number of tokens in phrase */
122890 char *pList; /* Pointer to start of phrase position list */
122891 int iHead; /* Next value in position list */
122892 char *pHead; /* Position list data following iHead */
122893 int iTail; /* Next value in trailing position list */
122894 char *pTail; /* Position list data following iTail */
122897 struct SnippetFragment {
122898 int iCol; /* Column snippet is extracted from */
122899 int iPos; /* Index of first token in snippet */
122900 u64 covered; /* Mask of query phrases covered */
122901 u64 hlmask; /* Mask of snippet terms to highlight */
122905 ** This type is used as an fts3ExprIterate() context object while
122906 ** accumulating the data returned by the matchinfo() function.
122908 typedef struct MatchInfo MatchInfo;
122909 struct MatchInfo {
122910 Fts3Cursor *pCursor; /* FTS3 Cursor */
122911 int nCol; /* Number of columns in table */
122912 int nPhrase; /* Number of matchable phrases in query */
122913 sqlite3_int64 nDoc; /* Number of docs in database */
122914 u32 *aMatchinfo; /* Pre-allocated buffer */
122920 ** The snippet() and offsets() functions both return text values. An instance
122921 ** of the following structure is used to accumulate those values while the
122922 ** functions are running. See fts3StringAppend() for details.
122924 typedef struct StrBuffer StrBuffer;
122925 struct StrBuffer {
122926 char *z; /* Pointer to buffer containing string */
122927 int n; /* Length of z in bytes (excl. nul-term) */
122928 int nAlloc; /* Allocated size of buffer z in bytes */
122933 ** This function is used to help iterate through a position-list. A position
122934 ** list is a list of unique integers, sorted from smallest to largest. Each
122935 ** element of the list is represented by an FTS3 varint that takes the value
122936 ** of the difference between the current element and the previous one plus
122937 ** two. For example, to store the position-list:
122939 ** 4 9 113
122941 ** the three varints:
122943 ** 6 7 106
122945 ** are encoded.
122947 ** When this function is called, *pp points to the start of an element of
122948 ** the list. *piPos contains the value of the previous entry in the list.
122949 ** After it returns, *piPos contains the value of the next element of the
122950 ** list and *pp is advanced to the following varint.
122952 static void fts3GetDeltaPosition(char **pp, int *piPos){
122953 int iVal;
122954 *pp += sqlite3Fts3GetVarint32(*pp, &iVal);
122955 *piPos += (iVal-2);
122959 ** Helper function for fts3ExprIterate() (see below).
122961 static int fts3ExprIterate2(
122962 Fts3Expr *pExpr, /* Expression to iterate phrases of */
122963 int *piPhrase, /* Pointer to phrase counter */
122964 int (*x)(Fts3Expr*,int,void*), /* Callback function to invoke for phrases */
122965 void *pCtx /* Second argument to pass to callback */
122967 int rc; /* Return code */
122968 int eType = pExpr->eType; /* Type of expression node pExpr */
122970 if( eType!=FTSQUERY_PHRASE ){
122971 assert( pExpr->pLeft && pExpr->pRight );
122972 rc = fts3ExprIterate2(pExpr->pLeft, piPhrase, x, pCtx);
122973 if( rc==SQLITE_OK && eType!=FTSQUERY_NOT ){
122974 rc = fts3ExprIterate2(pExpr->pRight, piPhrase, x, pCtx);
122976 }else{
122977 rc = x(pExpr, *piPhrase, pCtx);
122978 (*piPhrase)++;
122980 return rc;
122984 ** Iterate through all phrase nodes in an FTS3 query, except those that
122985 ** are part of a sub-tree that is the right-hand-side of a NOT operator.
122986 ** For each phrase node found, the supplied callback function is invoked.
122988 ** If the callback function returns anything other than SQLITE_OK,
122989 ** the iteration is abandoned and the error code returned immediately.
122990 ** Otherwise, SQLITE_OK is returned after a callback has been made for
122991 ** all eligible phrase nodes.
122993 static int fts3ExprIterate(
122994 Fts3Expr *pExpr, /* Expression to iterate phrases of */
122995 int (*x)(Fts3Expr*,int,void*), /* Callback function to invoke for phrases */
122996 void *pCtx /* Second argument to pass to callback */
122998 int iPhrase = 0; /* Variable used as the phrase counter */
122999 return fts3ExprIterate2(pExpr, &iPhrase, x, pCtx);
123003 ** The argument to this function is always a phrase node. Its doclist
123004 ** (Fts3Expr.aDoclist[]) and the doclists associated with all phrase nodes
123005 ** to the left of this one in the query tree have already been loaded.
123007 ** If this phrase node is part of a series of phrase nodes joined by
123008 ** NEAR operators (and is not the left-most of said series), then elements are
123009 ** removed from the phrases doclist consistent with the NEAR restriction. If
123010 ** required, elements may be removed from the doclists of phrases to the
123011 ** left of this one that are part of the same series of NEAR operator
123012 ** connected phrases.
123014 ** If an OOM error occurs, SQLITE_NOMEM is returned. Otherwise, SQLITE_OK.
123016 static int fts3ExprNearTrim(Fts3Expr *pExpr){
123017 int rc = SQLITE_OK;
123018 Fts3Expr *pParent = pExpr->pParent;
123020 assert( pExpr->eType==FTSQUERY_PHRASE );
123021 while( rc==SQLITE_OK
123022 && pParent
123023 && pParent->eType==FTSQUERY_NEAR
123024 && pParent->pRight==pExpr
123026 /* This expression (pExpr) is the right-hand-side of a NEAR operator.
123027 ** Find the expression to the left of the same operator.
123029 int nNear = pParent->nNear;
123030 Fts3Expr *pLeft = pParent->pLeft;
123032 if( pLeft->eType!=FTSQUERY_PHRASE ){
123033 assert( pLeft->eType==FTSQUERY_NEAR );
123034 assert( pLeft->pRight->eType==FTSQUERY_PHRASE );
123035 pLeft = pLeft->pRight;
123038 rc = sqlite3Fts3ExprNearTrim(pLeft, pExpr, nNear);
123040 pExpr = pLeft;
123041 pParent = pExpr->pParent;
123044 return rc;
123048 ** This is an fts3ExprIterate() callback used while loading the doclists
123049 ** for each phrase into Fts3Expr.aDoclist[]/nDoclist. See also
123050 ** fts3ExprLoadDoclists().
123052 static int fts3ExprLoadDoclistsCb(Fts3Expr *pExpr, int iPhrase, void *ctx){
123053 int rc = SQLITE_OK;
123054 LoadDoclistCtx *p = (LoadDoclistCtx *)ctx;
123056 UNUSED_PARAMETER(iPhrase);
123058 p->nPhrase++;
123059 p->nToken += pExpr->pPhrase->nToken;
123061 if( pExpr->isLoaded==0 ){
123062 rc = sqlite3Fts3ExprLoadDoclist(p->pCsr, pExpr);
123063 pExpr->isLoaded = 1;
123064 if( rc==SQLITE_OK ){
123065 rc = fts3ExprNearTrim(pExpr);
123069 return rc;
123073 ** Load the doclists for each phrase in the query associated with FTS3 cursor
123074 ** pCsr.
123076 ** If pnPhrase is not NULL, then *pnPhrase is set to the number of matchable
123077 ** phrases in the expression (all phrases except those directly or
123078 ** indirectly descended from the right-hand-side of a NOT operator). If
123079 ** pnToken is not NULL, then it is set to the number of tokens in all
123080 ** matchable phrases of the expression.
123082 static int fts3ExprLoadDoclists(
123083 Fts3Cursor *pCsr, /* Fts3 cursor for current query */
123084 int *pnPhrase, /* OUT: Number of phrases in query */
123085 int *pnToken /* OUT: Number of tokens in query */
123087 int rc; /* Return Code */
123088 LoadDoclistCtx sCtx = {0,0,0}; /* Context for fts3ExprIterate() */
123089 sCtx.pCsr = pCsr;
123090 rc = fts3ExprIterate(pCsr->pExpr, fts3ExprLoadDoclistsCb, (void *)&sCtx);
123091 if( pnPhrase ) *pnPhrase = sCtx.nPhrase;
123092 if( pnToken ) *pnToken = sCtx.nToken;
123093 return rc;
123096 static int fts3ExprPhraseCountCb(Fts3Expr *pExpr, int iPhrase, void *ctx){
123097 (*(int *)ctx)++;
123098 UNUSED_PARAMETER(pExpr);
123099 UNUSED_PARAMETER(iPhrase);
123100 return SQLITE_OK;
123102 static int fts3ExprPhraseCount(Fts3Expr *pExpr){
123103 int nPhrase = 0;
123104 (void)fts3ExprIterate(pExpr, fts3ExprPhraseCountCb, (void *)&nPhrase);
123105 return nPhrase;
123109 ** Advance the position list iterator specified by the first two
123110 ** arguments so that it points to the first element with a value greater
123111 ** than or equal to parameter iNext.
123113 static void fts3SnippetAdvance(char **ppIter, int *piIter, int iNext){
123114 char *pIter = *ppIter;
123115 if( pIter ){
123116 int iIter = *piIter;
123118 while( iIter<iNext ){
123119 if( 0==(*pIter & 0xFE) ){
123120 iIter = -1;
123121 pIter = 0;
123122 break;
123124 fts3GetDeltaPosition(&pIter, &iIter);
123127 *piIter = iIter;
123128 *ppIter = pIter;
123133 ** Advance the snippet iterator to the next candidate snippet.
123135 static int fts3SnippetNextCandidate(SnippetIter *pIter){
123136 int i; /* Loop counter */
123138 if( pIter->iCurrent<0 ){
123139 /* The SnippetIter object has just been initialized. The first snippet
123140 ** candidate always starts at offset 0 (even if this candidate has a
123141 ** score of 0.0).
123143 pIter->iCurrent = 0;
123145 /* Advance the 'head' iterator of each phrase to the first offset that
123146 ** is greater than or equal to (iNext+nSnippet).
123148 for(i=0; i<pIter->nPhrase; i++){
123149 SnippetPhrase *pPhrase = &pIter->aPhrase[i];
123150 fts3SnippetAdvance(&pPhrase->pHead, &pPhrase->iHead, pIter->nSnippet);
123152 }else{
123153 int iStart;
123154 int iEnd = 0x7FFFFFFF;
123156 for(i=0; i<pIter->nPhrase; i++){
123157 SnippetPhrase *pPhrase = &pIter->aPhrase[i];
123158 if( pPhrase->pHead && pPhrase->iHead<iEnd ){
123159 iEnd = pPhrase->iHead;
123162 if( iEnd==0x7FFFFFFF ){
123163 return 1;
123166 pIter->iCurrent = iStart = iEnd - pIter->nSnippet + 1;
123167 for(i=0; i<pIter->nPhrase; i++){
123168 SnippetPhrase *pPhrase = &pIter->aPhrase[i];
123169 fts3SnippetAdvance(&pPhrase->pHead, &pPhrase->iHead, iEnd+1);
123170 fts3SnippetAdvance(&pPhrase->pTail, &pPhrase->iTail, iStart);
123174 return 0;
123178 ** Retrieve information about the current candidate snippet of snippet
123179 ** iterator pIter.
123181 static void fts3SnippetDetails(
123182 SnippetIter *pIter, /* Snippet iterator */
123183 u64 mCovered, /* Bitmask of phrases already covered */
123184 int *piToken, /* OUT: First token of proposed snippet */
123185 int *piScore, /* OUT: "Score" for this snippet */
123186 u64 *pmCover, /* OUT: Bitmask of phrases covered */
123187 u64 *pmHighlight /* OUT: Bitmask of terms to highlight */
123189 int iStart = pIter->iCurrent; /* First token of snippet */
123190 int iScore = 0; /* Score of this snippet */
123191 int i; /* Loop counter */
123192 u64 mCover = 0; /* Mask of phrases covered by this snippet */
123193 u64 mHighlight = 0; /* Mask of tokens to highlight in snippet */
123195 for(i=0; i<pIter->nPhrase; i++){
123196 SnippetPhrase *pPhrase = &pIter->aPhrase[i];
123197 if( pPhrase->pTail ){
123198 char *pCsr = pPhrase->pTail;
123199 int iCsr = pPhrase->iTail;
123201 while( iCsr<(iStart+pIter->nSnippet) ){
123202 int j;
123203 u64 mPhrase = (u64)1 << i;
123204 u64 mPos = (u64)1 << (iCsr - iStart);
123205 assert( iCsr>=iStart );
123206 if( (mCover|mCovered)&mPhrase ){
123207 iScore++;
123208 }else{
123209 iScore += 1000;
123211 mCover |= mPhrase;
123213 for(j=0; j<pPhrase->nToken; j++){
123214 mHighlight |= (mPos>>j);
123217 if( 0==(*pCsr & 0x0FE) ) break;
123218 fts3GetDeltaPosition(&pCsr, &iCsr);
123223 /* Set the output variables before returning. */
123224 *piToken = iStart;
123225 *piScore = iScore;
123226 *pmCover = mCover;
123227 *pmHighlight = mHighlight;
123231 ** This function is an fts3ExprIterate() callback used by fts3BestSnippet().
123232 ** Each invocation populates an element of the SnippetIter.aPhrase[] array.
123234 static int fts3SnippetFindPositions(Fts3Expr *pExpr, int iPhrase, void *ctx){
123235 SnippetIter *p = (SnippetIter *)ctx;
123236 SnippetPhrase *pPhrase = &p->aPhrase[iPhrase];
123237 char *pCsr;
123239 pPhrase->nToken = pExpr->pPhrase->nToken;
123241 pCsr = sqlite3Fts3FindPositions(pExpr, p->pCsr->iPrevId, p->iCol);
123242 if( pCsr ){
123243 int iFirst = 0;
123244 pPhrase->pList = pCsr;
123245 fts3GetDeltaPosition(&pCsr, &iFirst);
123246 pPhrase->pHead = pCsr;
123247 pPhrase->pTail = pCsr;
123248 pPhrase->iHead = iFirst;
123249 pPhrase->iTail = iFirst;
123250 }else{
123251 assert( pPhrase->pList==0 && pPhrase->pHead==0 && pPhrase->pTail==0 );
123254 return SQLITE_OK;
123258 ** Select the fragment of text consisting of nFragment contiguous tokens
123259 ** from column iCol that represent the "best" snippet. The best snippet
123260 ** is the snippet with the highest score, where scores are calculated
123261 ** by adding:
123263 ** (a) +1 point for each occurence of a matchable phrase in the snippet.
123265 ** (b) +1000 points for the first occurence of each matchable phrase in
123266 ** the snippet for which the corresponding mCovered bit is not set.
123268 ** The selected snippet parameters are stored in structure *pFragment before
123269 ** returning. The score of the selected snippet is stored in *piScore
123270 ** before returning.
123272 static int fts3BestSnippet(
123273 int nSnippet, /* Desired snippet length */
123274 Fts3Cursor *pCsr, /* Cursor to create snippet for */
123275 int iCol, /* Index of column to create snippet from */
123276 u64 mCovered, /* Mask of phrases already covered */
123277 u64 *pmSeen, /* IN/OUT: Mask of phrases seen */
123278 SnippetFragment *pFragment, /* OUT: Best snippet found */
123279 int *piScore /* OUT: Score of snippet pFragment */
123281 int rc; /* Return Code */
123282 int nList; /* Number of phrases in expression */
123283 SnippetIter sIter; /* Iterates through snippet candidates */
123284 int nByte; /* Number of bytes of space to allocate */
123285 int iBestScore = -1; /* Best snippet score found so far */
123286 int i; /* Loop counter */
123288 memset(&sIter, 0, sizeof(sIter));
123290 /* Iterate through the phrases in the expression to count them. The same
123291 ** callback makes sure the doclists are loaded for each phrase.
123293 rc = fts3ExprLoadDoclists(pCsr, &nList, 0);
123294 if( rc!=SQLITE_OK ){
123295 return rc;
123298 /* Now that it is known how many phrases there are, allocate and zero
123299 ** the required space using malloc().
123301 nByte = sizeof(SnippetPhrase) * nList;
123302 sIter.aPhrase = (SnippetPhrase *)sqlite3_malloc(nByte);
123303 if( !sIter.aPhrase ){
123304 return SQLITE_NOMEM;
123306 memset(sIter.aPhrase, 0, nByte);
123308 /* Initialize the contents of the SnippetIter object. Then iterate through
123309 ** the set of phrases in the expression to populate the aPhrase[] array.
123311 sIter.pCsr = pCsr;
123312 sIter.iCol = iCol;
123313 sIter.nSnippet = nSnippet;
123314 sIter.nPhrase = nList;
123315 sIter.iCurrent = -1;
123316 (void)fts3ExprIterate(pCsr->pExpr, fts3SnippetFindPositions, (void *)&sIter);
123318 /* Set the *pmSeen output variable. */
123319 for(i=0; i<nList; i++){
123320 if( sIter.aPhrase[i].pHead ){
123321 *pmSeen |= (u64)1 << i;
123325 /* Loop through all candidate snippets. Store the best snippet in
123326 ** *pFragment. Store its associated 'score' in iBestScore.
123328 pFragment->iCol = iCol;
123329 while( !fts3SnippetNextCandidate(&sIter) ){
123330 int iPos;
123331 int iScore;
123332 u64 mCover;
123333 u64 mHighlight;
123334 fts3SnippetDetails(&sIter, mCovered, &iPos, &iScore, &mCover, &mHighlight);
123335 assert( iScore>=0 );
123336 if( iScore>iBestScore ){
123337 pFragment->iPos = iPos;
123338 pFragment->hlmask = mHighlight;
123339 pFragment->covered = mCover;
123340 iBestScore = iScore;
123344 sqlite3_free(sIter.aPhrase);
123345 *piScore = iBestScore;
123346 return SQLITE_OK;
123351 ** Append a string to the string-buffer passed as the first argument.
123353 ** If nAppend is negative, then the length of the string zAppend is
123354 ** determined using strlen().
123356 static int fts3StringAppend(
123357 StrBuffer *pStr, /* Buffer to append to */
123358 const char *zAppend, /* Pointer to data to append to buffer */
123359 int nAppend /* Size of zAppend in bytes (or -1) */
123361 if( nAppend<0 ){
123362 nAppend = (int)strlen(zAppend);
123365 /* If there is insufficient space allocated at StrBuffer.z, use realloc()
123366 ** to grow the buffer until so that it is big enough to accomadate the
123367 ** appended data.
123369 if( pStr->n+nAppend+1>=pStr->nAlloc ){
123370 int nAlloc = pStr->nAlloc+nAppend+100;
123371 char *zNew = sqlite3_realloc(pStr->z, nAlloc);
123372 if( !zNew ){
123373 return SQLITE_NOMEM;
123375 pStr->z = zNew;
123376 pStr->nAlloc = nAlloc;
123379 /* Append the data to the string buffer. */
123380 memcpy(&pStr->z[pStr->n], zAppend, nAppend);
123381 pStr->n += nAppend;
123382 pStr->z[pStr->n] = '\0';
123384 return SQLITE_OK;
123388 ** The fts3BestSnippet() function often selects snippets that end with a
123389 ** query term. That is, the final term of the snippet is always a term
123390 ** that requires highlighting. For example, if 'X' is a highlighted term
123391 ** and '.' is a non-highlighted term, BestSnippet() may select:
123393 ** ........X.....X
123395 ** This function "shifts" the beginning of the snippet forward in the
123396 ** document so that there are approximately the same number of
123397 ** non-highlighted terms to the right of the final highlighted term as there
123398 ** are to the left of the first highlighted term. For example, to this:
123400 ** ....X.....X....
123402 ** This is done as part of extracting the snippet text, not when selecting
123403 ** the snippet. Snippet selection is done based on doclists only, so there
123404 ** is no way for fts3BestSnippet() to know whether or not the document
123405 ** actually contains terms that follow the final highlighted term.
123407 static int fts3SnippetShift(
123408 Fts3Table *pTab, /* FTS3 table snippet comes from */
123409 int nSnippet, /* Number of tokens desired for snippet */
123410 const char *zDoc, /* Document text to extract snippet from */
123411 int nDoc, /* Size of buffer zDoc in bytes */
123412 int *piPos, /* IN/OUT: First token of snippet */
123413 u64 *pHlmask /* IN/OUT: Mask of tokens to highlight */
123415 u64 hlmask = *pHlmask; /* Local copy of initial highlight-mask */
123417 if( hlmask ){
123418 int nLeft; /* Tokens to the left of first highlight */
123419 int nRight; /* Tokens to the right of last highlight */
123420 int nDesired; /* Ideal number of tokens to shift forward */
123422 for(nLeft=0; !(hlmask & ((u64)1 << nLeft)); nLeft++);
123423 for(nRight=0; !(hlmask & ((u64)1 << (nSnippet-1-nRight))); nRight++);
123424 nDesired = (nLeft-nRight)/2;
123426 /* Ideally, the start of the snippet should be pushed forward in the
123427 ** document nDesired tokens. This block checks if there are actually
123428 ** nDesired tokens to the right of the snippet. If so, *piPos and
123429 ** *pHlMask are updated to shift the snippet nDesired tokens to the
123430 ** right. Otherwise, the snippet is shifted by the number of tokens
123431 ** available.
123433 if( nDesired>0 ){
123434 int nShift; /* Number of tokens to shift snippet by */
123435 int iCurrent = 0; /* Token counter */
123436 int rc; /* Return Code */
123437 sqlite3_tokenizer_module *pMod;
123438 sqlite3_tokenizer_cursor *pC;
123439 pMod = (sqlite3_tokenizer_module *)pTab->pTokenizer->pModule;
123441 /* Open a cursor on zDoc/nDoc. Check if there are (nSnippet+nDesired)
123442 ** or more tokens in zDoc/nDoc.
123444 rc = pMod->xOpen(pTab->pTokenizer, zDoc, nDoc, &pC);
123445 if( rc!=SQLITE_OK ){
123446 return rc;
123448 pC->pTokenizer = pTab->pTokenizer;
123449 while( rc==SQLITE_OK && iCurrent<(nSnippet+nDesired) ){
123450 const char *ZDUMMY; int DUMMY1, DUMMY2, DUMMY3;
123451 rc = pMod->xNext(pC, &ZDUMMY, &DUMMY1, &DUMMY2, &DUMMY3, &iCurrent);
123453 pMod->xClose(pC);
123454 if( rc!=SQLITE_OK && rc!=SQLITE_DONE ){ return rc; }
123456 nShift = (rc==SQLITE_DONE)+iCurrent-nSnippet;
123457 assert( nShift<=nDesired );
123458 if( nShift>0 ){
123459 *piPos += nShift;
123460 *pHlmask = hlmask >> nShift;
123464 return SQLITE_OK;
123468 ** Extract the snippet text for fragment pFragment from cursor pCsr and
123469 ** append it to string buffer pOut.
123471 static int fts3SnippetText(
123472 Fts3Cursor *pCsr, /* FTS3 Cursor */
123473 SnippetFragment *pFragment, /* Snippet to extract */
123474 int iFragment, /* Fragment number */
123475 int isLast, /* True for final fragment in snippet */
123476 int nSnippet, /* Number of tokens in extracted snippet */
123477 const char *zOpen, /* String inserted before highlighted term */
123478 const char *zClose, /* String inserted after highlighted term */
123479 const char *zEllipsis, /* String inserted between snippets */
123480 StrBuffer *pOut /* Write output here */
123482 Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
123483 int rc; /* Return code */
123484 const char *zDoc; /* Document text to extract snippet from */
123485 int nDoc; /* Size of zDoc in bytes */
123486 int iCurrent = 0; /* Current token number of document */
123487 int iEnd = 0; /* Byte offset of end of current token */
123488 int isShiftDone = 0; /* True after snippet is shifted */
123489 int iPos = pFragment->iPos; /* First token of snippet */
123490 u64 hlmask = pFragment->hlmask; /* Highlight-mask for snippet */
123491 int iCol = pFragment->iCol+1; /* Query column to extract text from */
123492 sqlite3_tokenizer_module *pMod; /* Tokenizer module methods object */
123493 sqlite3_tokenizer_cursor *pC; /* Tokenizer cursor open on zDoc/nDoc */
123494 const char *ZDUMMY; /* Dummy argument used with tokenizer */
123495 int DUMMY1; /* Dummy argument used with tokenizer */
123497 zDoc = (const char *)sqlite3_column_text(pCsr->pStmt, iCol);
123498 if( zDoc==0 ){
123499 if( sqlite3_column_type(pCsr->pStmt, iCol)!=SQLITE_NULL ){
123500 return SQLITE_NOMEM;
123502 return SQLITE_OK;
123504 nDoc = sqlite3_column_bytes(pCsr->pStmt, iCol);
123506 /* Open a token cursor on the document. */
123507 pMod = (sqlite3_tokenizer_module *)pTab->pTokenizer->pModule;
123508 rc = pMod->xOpen(pTab->pTokenizer, zDoc, nDoc, &pC);
123509 if( rc!=SQLITE_OK ){
123510 return rc;
123512 pC->pTokenizer = pTab->pTokenizer;
123514 while( rc==SQLITE_OK ){
123515 int iBegin; /* Offset in zDoc of start of token */
123516 int iFin; /* Offset in zDoc of end of token */
123517 int isHighlight; /* True for highlighted terms */
123519 rc = pMod->xNext(pC, &ZDUMMY, &DUMMY1, &iBegin, &iFin, &iCurrent);
123520 if( rc!=SQLITE_OK ){
123521 if( rc==SQLITE_DONE ){
123522 /* Special case - the last token of the snippet is also the last token
123523 ** of the column. Append any punctuation that occurred between the end
123524 ** of the previous token and the end of the document to the output.
123525 ** Then break out of the loop. */
123526 rc = fts3StringAppend(pOut, &zDoc[iEnd], -1);
123528 break;
123530 if( iCurrent<iPos ){ continue; }
123532 if( !isShiftDone ){
123533 int n = nDoc - iBegin;
123534 rc = fts3SnippetShift(pTab, nSnippet, &zDoc[iBegin], n, &iPos, &hlmask);
123535 isShiftDone = 1;
123537 /* Now that the shift has been done, check if the initial "..." are
123538 ** required. They are required if (a) this is not the first fragment,
123539 ** or (b) this fragment does not begin at position 0 of its column.
123541 if( rc==SQLITE_OK && (iPos>0 || iFragment>0) ){
123542 rc = fts3StringAppend(pOut, zEllipsis, -1);
123544 if( rc!=SQLITE_OK || iCurrent<iPos ) continue;
123547 if( iCurrent>=(iPos+nSnippet) ){
123548 if( isLast ){
123549 rc = fts3StringAppend(pOut, zEllipsis, -1);
123551 break;
123554 /* Set isHighlight to true if this term should be highlighted. */
123555 isHighlight = (hlmask & ((u64)1 << (iCurrent-iPos)))!=0;
123557 if( iCurrent>iPos ) rc = fts3StringAppend(pOut, &zDoc[iEnd], iBegin-iEnd);
123558 if( rc==SQLITE_OK && isHighlight ) rc = fts3StringAppend(pOut, zOpen, -1);
123559 if( rc==SQLITE_OK ) rc = fts3StringAppend(pOut, &zDoc[iBegin], iFin-iBegin);
123560 if( rc==SQLITE_OK && isHighlight ) rc = fts3StringAppend(pOut, zClose, -1);
123562 iEnd = iFin;
123565 pMod->xClose(pC);
123566 return rc;
123571 ** This function is used to count the entries in a column-list (a
123572 ** delta-encoded list of term offsets within a single column of a single
123573 ** row). When this function is called, *ppCollist should point to the
123574 ** beginning of the first varint in the column-list (the varint that
123575 ** contains the position of the first matching term in the column data).
123576 ** Before returning, *ppCollist is set to point to the first byte after
123577 ** the last varint in the column-list (either the 0x00 signifying the end
123578 ** of the position-list, or the 0x01 that precedes the column number of
123579 ** the next column in the position-list).
123581 ** The number of elements in the column-list is returned.
123583 static int fts3ColumnlistCount(char **ppCollist){
123584 char *pEnd = *ppCollist;
123585 char c = 0;
123586 int nEntry = 0;
123588 /* A column-list is terminated by either a 0x01 or 0x00. */
123589 while( 0xFE & (*pEnd | c) ){
123590 c = *pEnd++ & 0x80;
123591 if( !c ) nEntry++;
123594 *ppCollist = pEnd;
123595 return nEntry;
123598 static void fts3LoadColumnlistCounts(char **pp, u32 *aOut, int isGlobal){
123599 char *pCsr = *pp;
123600 while( *pCsr ){
123601 int nHit;
123602 sqlite3_int64 iCol = 0;
123603 if( *pCsr==0x01 ){
123604 pCsr++;
123605 pCsr += sqlite3Fts3GetVarint(pCsr, &iCol);
123607 nHit = fts3ColumnlistCount(&pCsr);
123608 assert( nHit>0 );
123609 if( isGlobal ){
123610 aOut[iCol*3+1]++;
123612 aOut[iCol*3] += nHit;
123614 pCsr++;
123615 *pp = pCsr;
123619 ** fts3ExprIterate() callback used to collect the "global" matchinfo stats
123620 ** for a single query.
123622 ** fts3ExprIterate() callback to load the 'global' elements of a
123623 ** FTS3_MATCHINFO_HITS matchinfo array. The global stats are those elements
123624 ** of the matchinfo array that are constant for all rows returned by the
123625 ** current query.
123627 ** Argument pCtx is actually a pointer to a struct of type MatchInfo. This
123628 ** function populates Matchinfo.aMatchinfo[] as follows:
123630 ** for(iCol=0; iCol<nCol; iCol++){
123631 ** aMatchinfo[3*iPhrase*nCol + 3*iCol + 1] = X;
123632 ** aMatchinfo[3*iPhrase*nCol + 3*iCol + 2] = Y;
123635 ** where X is the number of matches for phrase iPhrase is column iCol of all
123636 ** rows of the table. Y is the number of rows for which column iCol contains
123637 ** at least one instance of phrase iPhrase.
123639 ** If the phrase pExpr consists entirely of deferred tokens, then all X and
123640 ** Y values are set to nDoc, where nDoc is the number of documents in the
123641 ** file system. This is done because the full-text index doclist is required
123642 ** to calculate these values properly, and the full-text index doclist is
123643 ** not available for deferred tokens.
123645 static int fts3ExprGlobalHitsCb(
123646 Fts3Expr *pExpr, /* Phrase expression node */
123647 int iPhrase, /* Phrase number (numbered from zero) */
123648 void *pCtx /* Pointer to MatchInfo structure */
123650 MatchInfo *p = (MatchInfo *)pCtx;
123651 Fts3Cursor *pCsr = p->pCursor;
123652 char *pIter;
123653 char *pEnd;
123654 char *pFree = 0;
123655 u32 *aOut = &p->aMatchinfo[3*iPhrase*p->nCol];
123657 assert( pExpr->isLoaded );
123658 assert( pExpr->eType==FTSQUERY_PHRASE );
123660 if( pCsr->pDeferred ){
123661 Fts3Phrase *pPhrase = pExpr->pPhrase;
123662 int ii;
123663 for(ii=0; ii<pPhrase->nToken; ii++){
123664 if( pPhrase->aToken[ii].bFulltext ) break;
123666 if( ii<pPhrase->nToken ){
123667 int nFree = 0;
123668 int rc = sqlite3Fts3ExprLoadFtDoclist(pCsr, pExpr, &pFree, &nFree);
123669 if( rc!=SQLITE_OK ) return rc;
123670 pIter = pFree;
123671 pEnd = &pFree[nFree];
123672 }else{
123673 int iCol; /* Column index */
123674 for(iCol=0; iCol<p->nCol; iCol++){
123675 aOut[iCol*3 + 1] = (u32)p->nDoc;
123676 aOut[iCol*3 + 2] = (u32)p->nDoc;
123678 return SQLITE_OK;
123680 }else{
123681 pIter = pExpr->aDoclist;
123682 pEnd = &pExpr->aDoclist[pExpr->nDoclist];
123685 /* Fill in the global hit count matrix row for this phrase. */
123686 while( pIter<pEnd ){
123687 while( *pIter++ & 0x80 ); /* Skip past docid. */
123688 fts3LoadColumnlistCounts(&pIter, &aOut[1], 1);
123691 sqlite3_free(pFree);
123692 return SQLITE_OK;
123696 ** fts3ExprIterate() callback used to collect the "local" part of the
123697 ** FTS3_MATCHINFO_HITS array. The local stats are those elements of the
123698 ** array that are different for each row returned by the query.
123700 static int fts3ExprLocalHitsCb(
123701 Fts3Expr *pExpr, /* Phrase expression node */
123702 int iPhrase, /* Phrase number */
123703 void *pCtx /* Pointer to MatchInfo structure */
123705 MatchInfo *p = (MatchInfo *)pCtx;
123706 int iStart = iPhrase * p->nCol * 3;
123707 int i;
123709 for(i=0; i<p->nCol; i++) p->aMatchinfo[iStart+i*3] = 0;
123711 if( pExpr->aDoclist ){
123712 char *pCsr;
123714 pCsr = sqlite3Fts3FindPositions(pExpr, p->pCursor->iPrevId, -1);
123715 if( pCsr ){
123716 fts3LoadColumnlistCounts(&pCsr, &p->aMatchinfo[iStart], 0);
123720 return SQLITE_OK;
123723 static int fts3MatchinfoCheck(
123724 Fts3Table *pTab,
123725 char cArg,
123726 char **pzErr
123728 if( (cArg==FTS3_MATCHINFO_NPHRASE)
123729 || (cArg==FTS3_MATCHINFO_NCOL)
123730 || (cArg==FTS3_MATCHINFO_NDOC && pTab->bHasStat)
123731 || (cArg==FTS3_MATCHINFO_AVGLENGTH && pTab->bHasStat)
123732 || (cArg==FTS3_MATCHINFO_LENGTH && pTab->bHasDocsize)
123733 || (cArg==FTS3_MATCHINFO_LCS)
123734 || (cArg==FTS3_MATCHINFO_HITS)
123736 return SQLITE_OK;
123738 *pzErr = sqlite3_mprintf("unrecognized matchinfo request: %c", cArg);
123739 return SQLITE_ERROR;
123742 static int fts3MatchinfoSize(MatchInfo *pInfo, char cArg){
123743 int nVal; /* Number of integers output by cArg */
123745 switch( cArg ){
123746 case FTS3_MATCHINFO_NDOC:
123747 case FTS3_MATCHINFO_NPHRASE:
123748 case FTS3_MATCHINFO_NCOL:
123749 nVal = 1;
123750 break;
123752 case FTS3_MATCHINFO_AVGLENGTH:
123753 case FTS3_MATCHINFO_LENGTH:
123754 case FTS3_MATCHINFO_LCS:
123755 nVal = pInfo->nCol;
123756 break;
123758 default:
123759 assert( cArg==FTS3_MATCHINFO_HITS );
123760 nVal = pInfo->nCol * pInfo->nPhrase * 3;
123761 break;
123764 return nVal;
123767 static int fts3MatchinfoSelectDoctotal(
123768 Fts3Table *pTab,
123769 sqlite3_stmt **ppStmt,
123770 sqlite3_int64 *pnDoc,
123771 const char **paLen
123773 sqlite3_stmt *pStmt;
123774 const char *a;
123775 sqlite3_int64 nDoc;
123777 if( !*ppStmt ){
123778 int rc = sqlite3Fts3SelectDoctotal(pTab, ppStmt);
123779 if( rc!=SQLITE_OK ) return rc;
123781 pStmt = *ppStmt;
123782 assert( sqlite3_data_count(pStmt)==1 );
123784 a = sqlite3_column_blob(pStmt, 0);
123785 a += sqlite3Fts3GetVarint(a, &nDoc);
123786 if( nDoc==0 ) return SQLITE_CORRUPT;
123787 *pnDoc = (u32)nDoc;
123789 if( paLen ) *paLen = a;
123790 return SQLITE_OK;
123794 ** An instance of the following structure is used to store state while
123795 ** iterating through a multi-column position-list corresponding to the
123796 ** hits for a single phrase on a single row in order to calculate the
123797 ** values for a matchinfo() FTS3_MATCHINFO_LCS request.
123799 typedef struct LcsIterator LcsIterator;
123800 struct LcsIterator {
123801 Fts3Expr *pExpr; /* Pointer to phrase expression */
123802 char *pRead; /* Cursor used to iterate through aDoclist */
123803 int iPosOffset; /* Tokens count up to end of this phrase */
123804 int iCol; /* Current column number */
123805 int iPos; /* Current position */
123809 ** If LcsIterator.iCol is set to the following value, the iterator has
123810 ** finished iterating through all offsets for all columns.
123812 #define LCS_ITERATOR_FINISHED 0x7FFFFFFF;
123814 static int fts3MatchinfoLcsCb(
123815 Fts3Expr *pExpr, /* Phrase expression node */
123816 int iPhrase, /* Phrase number (numbered from zero) */
123817 void *pCtx /* Pointer to MatchInfo structure */
123819 LcsIterator *aIter = (LcsIterator *)pCtx;
123820 aIter[iPhrase].pExpr = pExpr;
123821 return SQLITE_OK;
123825 ** Advance the iterator passed as an argument to the next position. Return
123826 ** 1 if the iterator is at EOF or if it now points to the start of the
123827 ** position list for the next column.
123829 static int fts3LcsIteratorAdvance(LcsIterator *pIter){
123830 char *pRead = pIter->pRead;
123831 sqlite3_int64 iRead;
123832 int rc = 0;
123834 pRead += sqlite3Fts3GetVarint(pRead, &iRead);
123835 if( iRead==0 ){
123836 pIter->iCol = LCS_ITERATOR_FINISHED;
123837 rc = 1;
123838 }else{
123839 if( iRead==1 ){
123840 pRead += sqlite3Fts3GetVarint(pRead, &iRead);
123841 pIter->iCol = (int)iRead;
123842 pIter->iPos = pIter->iPosOffset;
123843 pRead += sqlite3Fts3GetVarint(pRead, &iRead);
123844 rc = 1;
123846 pIter->iPos += (int)(iRead-2);
123849 pIter->pRead = pRead;
123850 return rc;
123854 ** This function implements the FTS3_MATCHINFO_LCS matchinfo() flag.
123856 ** If the call is successful, the longest-common-substring lengths for each
123857 ** column are written into the first nCol elements of the pInfo->aMatchinfo[]
123858 ** array before returning. SQLITE_OK is returned in this case.
123860 ** Otherwise, if an error occurs, an SQLite error code is returned and the
123861 ** data written to the first nCol elements of pInfo->aMatchinfo[] is
123862 ** undefined.
123864 static int fts3MatchinfoLcs(Fts3Cursor *pCsr, MatchInfo *pInfo){
123865 LcsIterator *aIter;
123866 int i;
123867 int iCol;
123868 int nToken = 0;
123870 /* Allocate and populate the array of LcsIterator objects. The array
123871 ** contains one element for each matchable phrase in the query.
123873 aIter = sqlite3_malloc(sizeof(LcsIterator) * pCsr->nPhrase);
123874 if( !aIter ) return SQLITE_NOMEM;
123875 memset(aIter, 0, sizeof(LcsIterator) * pCsr->nPhrase);
123876 (void)fts3ExprIterate(pCsr->pExpr, fts3MatchinfoLcsCb, (void*)aIter);
123877 for(i=0; i<pInfo->nPhrase; i++){
123878 LcsIterator *pIter = &aIter[i];
123879 nToken -= pIter->pExpr->pPhrase->nToken;
123880 pIter->iPosOffset = nToken;
123881 pIter->pRead = sqlite3Fts3FindPositions(pIter->pExpr, pCsr->iPrevId, -1);
123882 if( pIter->pRead ){
123883 pIter->iPos = pIter->iPosOffset;
123884 fts3LcsIteratorAdvance(&aIter[i]);
123885 }else{
123886 pIter->iCol = LCS_ITERATOR_FINISHED;
123890 for(iCol=0; iCol<pInfo->nCol; iCol++){
123891 int nLcs = 0; /* LCS value for this column */
123892 int nLive = 0; /* Number of iterators in aIter not at EOF */
123894 /* Loop through the iterators in aIter[]. Set nLive to the number of
123895 ** iterators that point to a position-list corresponding to column iCol.
123897 for(i=0; i<pInfo->nPhrase; i++){
123898 assert( aIter[i].iCol>=iCol );
123899 if( aIter[i].iCol==iCol ) nLive++;
123902 /* The following loop runs until all iterators in aIter[] have finished
123903 ** iterating through positions in column iCol. Exactly one of the
123904 ** iterators is advanced each time the body of the loop is run.
123906 while( nLive>0 ){
123907 LcsIterator *pAdv = 0; /* The iterator to advance by one position */
123908 int nThisLcs = 0; /* LCS for the current iterator positions */
123910 for(i=0; i<pInfo->nPhrase; i++){
123911 LcsIterator *pIter = &aIter[i];
123912 if( iCol!=pIter->iCol ){
123913 /* This iterator is already at EOF for this column. */
123914 nThisLcs = 0;
123915 }else{
123916 if( pAdv==0 || pIter->iPos<pAdv->iPos ){
123917 pAdv = pIter;
123919 if( nThisLcs==0 || pIter->iPos==pIter[-1].iPos ){
123920 nThisLcs++;
123921 }else{
123922 nThisLcs = 1;
123924 if( nThisLcs>nLcs ) nLcs = nThisLcs;
123927 if( fts3LcsIteratorAdvance(pAdv) ) nLive--;
123930 pInfo->aMatchinfo[iCol] = nLcs;
123933 sqlite3_free(aIter);
123934 return SQLITE_OK;
123938 ** Populate the buffer pInfo->aMatchinfo[] with an array of integers to
123939 ** be returned by the matchinfo() function. Argument zArg contains the
123940 ** format string passed as the second argument to matchinfo (or the
123941 ** default value "pcx" if no second argument was specified). The format
123942 ** string has already been validated and the pInfo->aMatchinfo[] array
123943 ** is guaranteed to be large enough for the output.
123945 ** If bGlobal is true, then populate all fields of the matchinfo() output.
123946 ** If it is false, then assume that those fields that do not change between
123947 ** rows (i.e. FTS3_MATCHINFO_NPHRASE, NCOL, NDOC, AVGLENGTH and part of HITS)
123948 ** have already been populated.
123950 ** Return SQLITE_OK if successful, or an SQLite error code if an error
123951 ** occurs. If a value other than SQLITE_OK is returned, the state the
123952 ** pInfo->aMatchinfo[] buffer is left in is undefined.
123954 static int fts3MatchinfoValues(
123955 Fts3Cursor *pCsr, /* FTS3 cursor object */
123956 int bGlobal, /* True to grab the global stats */
123957 MatchInfo *pInfo, /* Matchinfo context object */
123958 const char *zArg /* Matchinfo format string */
123960 int rc = SQLITE_OK;
123961 int i;
123962 Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
123963 sqlite3_stmt *pSelect = 0;
123965 for(i=0; rc==SQLITE_OK && zArg[i]; i++){
123967 switch( zArg[i] ){
123968 case FTS3_MATCHINFO_NPHRASE:
123969 if( bGlobal ) pInfo->aMatchinfo[0] = pInfo->nPhrase;
123970 break;
123972 case FTS3_MATCHINFO_NCOL:
123973 if( bGlobal ) pInfo->aMatchinfo[0] = pInfo->nCol;
123974 break;
123976 case FTS3_MATCHINFO_NDOC:
123977 if( bGlobal ){
123978 sqlite3_int64 nDoc;
123979 rc = fts3MatchinfoSelectDoctotal(pTab, &pSelect, &nDoc, 0);
123980 pInfo->aMatchinfo[0] = (u32)nDoc;
123982 break;
123984 case FTS3_MATCHINFO_AVGLENGTH:
123985 if( bGlobal ){
123986 sqlite3_int64 nDoc; /* Number of rows in table */
123987 const char *a; /* Aggregate column length array */
123989 rc = fts3MatchinfoSelectDoctotal(pTab, &pSelect, &nDoc, &a);
123990 if( rc==SQLITE_OK ){
123991 int iCol;
123992 for(iCol=0; iCol<pInfo->nCol; iCol++){
123993 u32 iVal;
123994 sqlite3_int64 nToken;
123995 a += sqlite3Fts3GetVarint(a, &nToken);
123996 iVal = (u32)(((u32)(nToken&0xffffffff)+nDoc/2)/nDoc);
123997 pInfo->aMatchinfo[iCol] = iVal;
124001 break;
124003 case FTS3_MATCHINFO_LENGTH: {
124004 sqlite3_stmt *pSelectDocsize = 0;
124005 rc = sqlite3Fts3SelectDocsize(pTab, pCsr->iPrevId, &pSelectDocsize);
124006 if( rc==SQLITE_OK ){
124007 int iCol;
124008 const char *a = sqlite3_column_blob(pSelectDocsize, 0);
124009 for(iCol=0; iCol<pInfo->nCol; iCol++){
124010 sqlite3_int64 nToken;
124011 a += sqlite3Fts3GetVarint(a, &nToken);
124012 pInfo->aMatchinfo[iCol] = (u32)nToken;
124015 sqlite3_reset(pSelectDocsize);
124016 break;
124019 case FTS3_MATCHINFO_LCS:
124020 rc = fts3ExprLoadDoclists(pCsr, 0, 0);
124021 if( rc==SQLITE_OK ){
124022 rc = fts3MatchinfoLcs(pCsr, pInfo);
124024 break;
124026 default: {
124027 Fts3Expr *pExpr;
124028 assert( zArg[i]==FTS3_MATCHINFO_HITS );
124029 pExpr = pCsr->pExpr;
124030 rc = fts3ExprLoadDoclists(pCsr, 0, 0);
124031 if( rc!=SQLITE_OK ) break;
124032 if( bGlobal ){
124033 if( pCsr->pDeferred ){
124034 rc = fts3MatchinfoSelectDoctotal(pTab, &pSelect, &pInfo->nDoc, 0);
124035 if( rc!=SQLITE_OK ) break;
124037 rc = fts3ExprIterate(pExpr, fts3ExprGlobalHitsCb,(void*)pInfo);
124038 if( rc!=SQLITE_OK ) break;
124040 (void)fts3ExprIterate(pExpr, fts3ExprLocalHitsCb,(void*)pInfo);
124041 break;
124045 pInfo->aMatchinfo += fts3MatchinfoSize(pInfo, zArg[i]);
124048 sqlite3_reset(pSelect);
124049 return rc;
124054 ** Populate pCsr->aMatchinfo[] with data for the current row. The
124055 ** 'matchinfo' data is an array of 32-bit unsigned integers (C type u32).
124057 static int fts3GetMatchinfo(
124058 Fts3Cursor *pCsr, /* FTS3 Cursor object */
124059 const char *zArg /* Second argument to matchinfo() function */
124061 MatchInfo sInfo;
124062 Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
124063 int rc = SQLITE_OK;
124064 int bGlobal = 0; /* Collect 'global' stats as well as local */
124066 memset(&sInfo, 0, sizeof(MatchInfo));
124067 sInfo.pCursor = pCsr;
124068 sInfo.nCol = pTab->nColumn;
124070 /* If there is cached matchinfo() data, but the format string for the
124071 ** cache does not match the format string for this request, discard
124072 ** the cached data. */
124073 if( pCsr->zMatchinfo && strcmp(pCsr->zMatchinfo, zArg) ){
124074 assert( pCsr->aMatchinfo );
124075 sqlite3_free(pCsr->aMatchinfo);
124076 pCsr->zMatchinfo = 0;
124077 pCsr->aMatchinfo = 0;
124080 /* If Fts3Cursor.aMatchinfo[] is NULL, then this is the first time the
124081 ** matchinfo function has been called for this query. In this case
124082 ** allocate the array used to accumulate the matchinfo data and
124083 ** initialize those elements that are constant for every row.
124085 if( pCsr->aMatchinfo==0 ){
124086 int nMatchinfo = 0; /* Number of u32 elements in match-info */
124087 int nArg; /* Bytes in zArg */
124088 int i; /* Used to iterate through zArg */
124090 /* Determine the number of phrases in the query */
124091 pCsr->nPhrase = fts3ExprPhraseCount(pCsr->pExpr);
124092 sInfo.nPhrase = pCsr->nPhrase;
124094 /* Determine the number of integers in the buffer returned by this call. */
124095 for(i=0; zArg[i]; i++){
124096 nMatchinfo += fts3MatchinfoSize(&sInfo, zArg[i]);
124099 /* Allocate space for Fts3Cursor.aMatchinfo[] and Fts3Cursor.zMatchinfo. */
124100 nArg = (int)strlen(zArg);
124101 pCsr->aMatchinfo = (u32 *)sqlite3_malloc(sizeof(u32)*nMatchinfo + nArg + 1);
124102 if( !pCsr->aMatchinfo ) return SQLITE_NOMEM;
124104 pCsr->zMatchinfo = (char *)&pCsr->aMatchinfo[nMatchinfo];
124105 pCsr->nMatchinfo = nMatchinfo;
124106 memcpy(pCsr->zMatchinfo, zArg, nArg+1);
124107 memset(pCsr->aMatchinfo, 0, sizeof(u32)*nMatchinfo);
124108 pCsr->isMatchinfoNeeded = 1;
124109 bGlobal = 1;
124112 sInfo.aMatchinfo = pCsr->aMatchinfo;
124113 sInfo.nPhrase = pCsr->nPhrase;
124114 if( pCsr->isMatchinfoNeeded ){
124115 rc = fts3MatchinfoValues(pCsr, bGlobal, &sInfo, zArg);
124116 pCsr->isMatchinfoNeeded = 0;
124119 return rc;
124123 ** Implementation of snippet() function.
124125 SQLITE_PRIVATE void sqlite3Fts3Snippet(
124126 sqlite3_context *pCtx, /* SQLite function call context */
124127 Fts3Cursor *pCsr, /* Cursor object */
124128 const char *zStart, /* Snippet start text - "<b>" */
124129 const char *zEnd, /* Snippet end text - "</b>" */
124130 const char *zEllipsis, /* Snippet ellipsis text - "<b>...</b>" */
124131 int iCol, /* Extract snippet from this column */
124132 int nToken /* Approximate number of tokens in snippet */
124134 Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
124135 int rc = SQLITE_OK;
124136 int i;
124137 StrBuffer res = {0, 0, 0};
124139 /* The returned text includes up to four fragments of text extracted from
124140 ** the data in the current row. The first iteration of the for(...) loop
124141 ** below attempts to locate a single fragment of text nToken tokens in
124142 ** size that contains at least one instance of all phrases in the query
124143 ** expression that appear in the current row. If such a fragment of text
124144 ** cannot be found, the second iteration of the loop attempts to locate
124145 ** a pair of fragments, and so on.
124147 int nSnippet = 0; /* Number of fragments in this snippet */
124148 SnippetFragment aSnippet[4]; /* Maximum of 4 fragments per snippet */
124149 int nFToken = -1; /* Number of tokens in each fragment */
124151 if( !pCsr->pExpr ){
124152 sqlite3_result_text(pCtx, "", 0, SQLITE_STATIC);
124153 return;
124156 for(nSnippet=1; 1; nSnippet++){
124158 int iSnip; /* Loop counter 0..nSnippet-1 */
124159 u64 mCovered = 0; /* Bitmask of phrases covered by snippet */
124160 u64 mSeen = 0; /* Bitmask of phrases seen by BestSnippet() */
124162 if( nToken>=0 ){
124163 nFToken = (nToken+nSnippet-1) / nSnippet;
124164 }else{
124165 nFToken = -1 * nToken;
124168 for(iSnip=0; iSnip<nSnippet; iSnip++){
124169 int iBestScore = -1; /* Best score of columns checked so far */
124170 int iRead; /* Used to iterate through columns */
124171 SnippetFragment *pFragment = &aSnippet[iSnip];
124173 memset(pFragment, 0, sizeof(*pFragment));
124175 /* Loop through all columns of the table being considered for snippets.
124176 ** If the iCol argument to this function was negative, this means all
124177 ** columns of the FTS3 table. Otherwise, only column iCol is considered.
124179 for(iRead=0; iRead<pTab->nColumn; iRead++){
124180 SnippetFragment sF = {0, 0, 0, 0};
124181 int iS;
124182 if( iCol>=0 && iRead!=iCol ) continue;
124184 /* Find the best snippet of nFToken tokens in column iRead. */
124185 rc = fts3BestSnippet(nFToken, pCsr, iRead, mCovered, &mSeen, &sF, &iS);
124186 if( rc!=SQLITE_OK ){
124187 goto snippet_out;
124189 if( iS>iBestScore ){
124190 *pFragment = sF;
124191 iBestScore = iS;
124195 mCovered |= pFragment->covered;
124198 /* If all query phrases seen by fts3BestSnippet() are present in at least
124199 ** one of the nSnippet snippet fragments, break out of the loop.
124201 assert( (mCovered&mSeen)==mCovered );
124202 if( mSeen==mCovered || nSnippet==SizeofArray(aSnippet) ) break;
124205 assert( nFToken>0 );
124207 for(i=0; i<nSnippet && rc==SQLITE_OK; i++){
124208 rc = fts3SnippetText(pCsr, &aSnippet[i],
124209 i, (i==nSnippet-1), nFToken, zStart, zEnd, zEllipsis, &res
124213 snippet_out:
124214 sqlite3Fts3SegmentsClose(pTab);
124215 if( rc!=SQLITE_OK ){
124216 sqlite3_result_error_code(pCtx, rc);
124217 sqlite3_free(res.z);
124218 }else{
124219 sqlite3_result_text(pCtx, res.z, -1, sqlite3_free);
124224 typedef struct TermOffset TermOffset;
124225 typedef struct TermOffsetCtx TermOffsetCtx;
124227 struct TermOffset {
124228 char *pList; /* Position-list */
124229 int iPos; /* Position just read from pList */
124230 int iOff; /* Offset of this term from read positions */
124233 struct TermOffsetCtx {
124234 int iCol; /* Column of table to populate aTerm for */
124235 int iTerm;
124236 sqlite3_int64 iDocid;
124237 TermOffset *aTerm;
124241 ** This function is an fts3ExprIterate() callback used by sqlite3Fts3Offsets().
124243 static int fts3ExprTermOffsetInit(Fts3Expr *pExpr, int iPhrase, void *ctx){
124244 TermOffsetCtx *p = (TermOffsetCtx *)ctx;
124245 int nTerm; /* Number of tokens in phrase */
124246 int iTerm; /* For looping through nTerm phrase terms */
124247 char *pList; /* Pointer to position list for phrase */
124248 int iPos = 0; /* First position in position-list */
124250 UNUSED_PARAMETER(iPhrase);
124251 pList = sqlite3Fts3FindPositions(pExpr, p->iDocid, p->iCol);
124252 nTerm = pExpr->pPhrase->nToken;
124253 if( pList ){
124254 fts3GetDeltaPosition(&pList, &iPos);
124255 assert( iPos>=0 );
124258 for(iTerm=0; iTerm<nTerm; iTerm++){
124259 TermOffset *pT = &p->aTerm[p->iTerm++];
124260 pT->iOff = nTerm-iTerm-1;
124261 pT->pList = pList;
124262 pT->iPos = iPos;
124265 return SQLITE_OK;
124269 ** Implementation of offsets() function.
124271 SQLITE_PRIVATE void sqlite3Fts3Offsets(
124272 sqlite3_context *pCtx, /* SQLite function call context */
124273 Fts3Cursor *pCsr /* Cursor object */
124275 Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
124276 sqlite3_tokenizer_module const *pMod = pTab->pTokenizer->pModule;
124277 const char *ZDUMMY; /* Dummy argument used with xNext() */
124278 int NDUMMY; /* Dummy argument used with xNext() */
124279 int rc; /* Return Code */
124280 int nToken; /* Number of tokens in query */
124281 int iCol; /* Column currently being processed */
124282 StrBuffer res = {0, 0, 0}; /* Result string */
124283 TermOffsetCtx sCtx; /* Context for fts3ExprTermOffsetInit() */
124285 if( !pCsr->pExpr ){
124286 sqlite3_result_text(pCtx, "", 0, SQLITE_STATIC);
124287 return;
124290 memset(&sCtx, 0, sizeof(sCtx));
124291 assert( pCsr->isRequireSeek==0 );
124293 /* Count the number of terms in the query */
124294 rc = fts3ExprLoadDoclists(pCsr, 0, &nToken);
124295 if( rc!=SQLITE_OK ) goto offsets_out;
124297 /* Allocate the array of TermOffset iterators. */
124298 sCtx.aTerm = (TermOffset *)sqlite3_malloc(sizeof(TermOffset)*nToken);
124299 if( 0==sCtx.aTerm ){
124300 rc = SQLITE_NOMEM;
124301 goto offsets_out;
124303 sCtx.iDocid = pCsr->iPrevId;
124305 /* Loop through the table columns, appending offset information to
124306 ** string-buffer res for each column.
124308 for(iCol=0; iCol<pTab->nColumn; iCol++){
124309 sqlite3_tokenizer_cursor *pC; /* Tokenizer cursor */
124310 int iStart;
124311 int iEnd;
124312 int iCurrent;
124313 const char *zDoc;
124314 int nDoc;
124316 /* Initialize the contents of sCtx.aTerm[] for column iCol. There is
124317 ** no way that this operation can fail, so the return code from
124318 ** fts3ExprIterate() can be discarded.
124320 sCtx.iCol = iCol;
124321 sCtx.iTerm = 0;
124322 (void)fts3ExprIterate(pCsr->pExpr, fts3ExprTermOffsetInit, (void *)&sCtx);
124324 /* Retreive the text stored in column iCol. If an SQL NULL is stored
124325 ** in column iCol, jump immediately to the next iteration of the loop.
124326 ** If an OOM occurs while retrieving the data (this can happen if SQLite
124327 ** needs to transform the data from utf-16 to utf-8), return SQLITE_NOMEM
124328 ** to the caller.
124330 zDoc = (const char *)sqlite3_column_text(pCsr->pStmt, iCol+1);
124331 nDoc = sqlite3_column_bytes(pCsr->pStmt, iCol+1);
124332 if( zDoc==0 ){
124333 if( sqlite3_column_type(pCsr->pStmt, iCol+1)==SQLITE_NULL ){
124334 continue;
124336 rc = SQLITE_NOMEM;
124337 goto offsets_out;
124340 /* Initialize a tokenizer iterator to iterate through column iCol. */
124341 rc = pMod->xOpen(pTab->pTokenizer, zDoc, nDoc, &pC);
124342 if( rc!=SQLITE_OK ) goto offsets_out;
124343 pC->pTokenizer = pTab->pTokenizer;
124345 rc = pMod->xNext(pC, &ZDUMMY, &NDUMMY, &iStart, &iEnd, &iCurrent);
124346 while( rc==SQLITE_OK ){
124347 int i; /* Used to loop through terms */
124348 int iMinPos = 0x7FFFFFFF; /* Position of next token */
124349 TermOffset *pTerm = 0; /* TermOffset associated with next token */
124351 for(i=0; i<nToken; i++){
124352 TermOffset *pT = &sCtx.aTerm[i];
124353 if( pT->pList && (pT->iPos-pT->iOff)<iMinPos ){
124354 iMinPos = pT->iPos-pT->iOff;
124355 pTerm = pT;
124359 if( !pTerm ){
124360 /* All offsets for this column have been gathered. */
124361 break;
124362 }else{
124363 assert( iCurrent<=iMinPos );
124364 if( 0==(0xFE&*pTerm->pList) ){
124365 pTerm->pList = 0;
124366 }else{
124367 fts3GetDeltaPosition(&pTerm->pList, &pTerm->iPos);
124369 while( rc==SQLITE_OK && iCurrent<iMinPos ){
124370 rc = pMod->xNext(pC, &ZDUMMY, &NDUMMY, &iStart, &iEnd, &iCurrent);
124372 if( rc==SQLITE_OK ){
124373 char aBuffer[64];
124374 sqlite3_snprintf(sizeof(aBuffer), aBuffer,
124375 "%d %d %d %d ", iCol, pTerm-sCtx.aTerm, iStart, iEnd-iStart
124377 rc = fts3StringAppend(&res, aBuffer, -1);
124378 }else if( rc==SQLITE_DONE ){
124379 rc = SQLITE_CORRUPT;
124383 if( rc==SQLITE_DONE ){
124384 rc = SQLITE_OK;
124387 pMod->xClose(pC);
124388 if( rc!=SQLITE_OK ) goto offsets_out;
124391 offsets_out:
124392 sqlite3_free(sCtx.aTerm);
124393 assert( rc!=SQLITE_DONE );
124394 sqlite3Fts3SegmentsClose(pTab);
124395 if( rc!=SQLITE_OK ){
124396 sqlite3_result_error_code(pCtx, rc);
124397 sqlite3_free(res.z);
124398 }else{
124399 sqlite3_result_text(pCtx, res.z, res.n-1, sqlite3_free);
124401 return;
124405 ** Implementation of matchinfo() function.
124407 SQLITE_PRIVATE void sqlite3Fts3Matchinfo(
124408 sqlite3_context *pContext, /* Function call context */
124409 Fts3Cursor *pCsr, /* FTS3 table cursor */
124410 const char *zArg /* Second arg to matchinfo() function */
124412 Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
124413 int rc;
124414 int i;
124415 const char *zFormat;
124417 if( zArg ){
124418 for(i=0; zArg[i]; i++){
124419 char *zErr = 0;
124420 if( fts3MatchinfoCheck(pTab, zArg[i], &zErr) ){
124421 sqlite3_result_error(pContext, zErr, -1);
124422 sqlite3_free(zErr);
124423 return;
124426 zFormat = zArg;
124427 }else{
124428 zFormat = FTS3_MATCHINFO_DEFAULT;
124431 if( !pCsr->pExpr ){
124432 sqlite3_result_blob(pContext, "", 0, SQLITE_STATIC);
124433 return;
124436 /* Retrieve matchinfo() data. */
124437 rc = fts3GetMatchinfo(pCsr, zFormat);
124438 sqlite3Fts3SegmentsClose(pTab);
124440 if( rc!=SQLITE_OK ){
124441 sqlite3_result_error_code(pContext, rc);
124442 }else{
124443 int n = pCsr->nMatchinfo * sizeof(u32);
124444 sqlite3_result_blob(pContext, pCsr->aMatchinfo, n, SQLITE_TRANSIENT);
124448 #endif
124450 /************** End of fts3_snippet.c ****************************************/
124451 /************** Begin file rtree.c *******************************************/
124453 ** 2001 September 15
124455 ** The author disclaims copyright to this source code. In place of
124456 ** a legal notice, here is a blessing:
124458 ** May you do good and not evil.
124459 ** May you find forgiveness for yourself and forgive others.
124460 ** May you share freely, never taking more than you give.
124462 *************************************************************************
124463 ** This file contains code for implementations of the r-tree and r*-tree
124464 ** algorithms packaged as an SQLite virtual table module.
124468 ** Database Format of R-Tree Tables
124469 ** --------------------------------
124471 ** The data structure for a single virtual r-tree table is stored in three
124472 ** native SQLite tables declared as follows. In each case, the '%' character
124473 ** in the table name is replaced with the user-supplied name of the r-tree
124474 ** table.
124476 ** CREATE TABLE %_node(nodeno INTEGER PRIMARY KEY, data BLOB)
124477 ** CREATE TABLE %_parent(nodeno INTEGER PRIMARY KEY, parentnode INTEGER)
124478 ** CREATE TABLE %_rowid(rowid INTEGER PRIMARY KEY, nodeno INTEGER)
124480 ** The data for each node of the r-tree structure is stored in the %_node
124481 ** table. For each node that is not the root node of the r-tree, there is
124482 ** an entry in the %_parent table associating the node with its parent.
124483 ** And for each row of data in the table, there is an entry in the %_rowid
124484 ** table that maps from the entries rowid to the id of the node that it
124485 ** is stored on.
124487 ** The root node of an r-tree always exists, even if the r-tree table is
124488 ** empty. The nodeno of the root node is always 1. All other nodes in the
124489 ** table must be the same size as the root node. The content of each node
124490 ** is formatted as follows:
124492 ** 1. If the node is the root node (node 1), then the first 2 bytes
124493 ** of the node contain the tree depth as a big-endian integer.
124494 ** For non-root nodes, the first 2 bytes are left unused.
124496 ** 2. The next 2 bytes contain the number of entries currently
124497 ** stored in the node.
124499 ** 3. The remainder of the node contains the node entries. Each entry
124500 ** consists of a single 8-byte integer followed by an even number
124501 ** of 4-byte coordinates. For leaf nodes the integer is the rowid
124502 ** of a record. For internal nodes it is the node number of a
124503 ** child page.
124506 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_RTREE)
124509 ** This file contains an implementation of a couple of different variants
124510 ** of the r-tree algorithm. See the README file for further details. The
124511 ** same data-structure is used for all, but the algorithms for insert and
124512 ** delete operations vary. The variants used are selected at compile time
124513 ** by defining the following symbols:
124516 /* Either, both or none of the following may be set to activate
124517 ** r*tree variant algorithms.
124519 #define VARIANT_RSTARTREE_CHOOSESUBTREE 0
124520 #define VARIANT_RSTARTREE_REINSERT 1
124523 ** Exactly one of the following must be set to 1.
124525 #define VARIANT_GUTTMAN_QUADRATIC_SPLIT 0
124526 #define VARIANT_GUTTMAN_LINEAR_SPLIT 0
124527 #define VARIANT_RSTARTREE_SPLIT 1
124529 #define VARIANT_GUTTMAN_SPLIT \
124530 (VARIANT_GUTTMAN_LINEAR_SPLIT||VARIANT_GUTTMAN_QUADRATIC_SPLIT)
124532 #if VARIANT_GUTTMAN_QUADRATIC_SPLIT
124533 #define PickNext QuadraticPickNext
124534 #define PickSeeds QuadraticPickSeeds
124535 #define AssignCells splitNodeGuttman
124536 #endif
124537 #if VARIANT_GUTTMAN_LINEAR_SPLIT
124538 #define PickNext LinearPickNext
124539 #define PickSeeds LinearPickSeeds
124540 #define AssignCells splitNodeGuttman
124541 #endif
124542 #if VARIANT_RSTARTREE_SPLIT
124543 #define AssignCells splitNodeStartree
124544 #endif
124546 #if !defined(NDEBUG) && !defined(SQLITE_DEBUG)
124547 # define NDEBUG 1
124548 #endif
124550 #ifndef SQLITE_CORE
124551 SQLITE_EXTENSION_INIT1
124552 #else
124553 #endif
124556 #ifndef SQLITE_AMALGAMATION
124557 #include "sqlite3rtree.h"
124558 typedef sqlite3_int64 i64;
124559 typedef unsigned char u8;
124560 typedef unsigned int u32;
124561 #endif
124563 /* The following macro is used to suppress compiler warnings.
124565 #ifndef UNUSED_PARAMETER
124566 # define UNUSED_PARAMETER(x) (void)(x)
124567 #endif
124569 typedef struct Rtree Rtree;
124570 typedef struct RtreeCursor RtreeCursor;
124571 typedef struct RtreeNode RtreeNode;
124572 typedef struct RtreeCell RtreeCell;
124573 typedef struct RtreeConstraint RtreeConstraint;
124574 typedef struct RtreeMatchArg RtreeMatchArg;
124575 typedef struct RtreeGeomCallback RtreeGeomCallback;
124576 typedef union RtreeCoord RtreeCoord;
124578 /* The rtree may have between 1 and RTREE_MAX_DIMENSIONS dimensions. */
124579 #define RTREE_MAX_DIMENSIONS 5
124581 /* Size of hash table Rtree.aHash. This hash table is not expected to
124582 ** ever contain very many entries, so a fixed number of buckets is
124583 ** used.
124585 #define HASHSIZE 128
124588 ** An rtree virtual-table object.
124590 struct Rtree {
124591 sqlite3_vtab base;
124592 sqlite3 *db; /* Host database connection */
124593 int iNodeSize; /* Size in bytes of each node in the node table */
124594 int nDim; /* Number of dimensions */
124595 int nBytesPerCell; /* Bytes consumed per cell */
124596 int iDepth; /* Current depth of the r-tree structure */
124597 char *zDb; /* Name of database containing r-tree table */
124598 char *zName; /* Name of r-tree table */
124599 RtreeNode *aHash[HASHSIZE]; /* Hash table of in-memory nodes. */
124600 int nBusy; /* Current number of users of this structure */
124602 /* List of nodes removed during a CondenseTree operation. List is
124603 ** linked together via the pointer normally used for hash chains -
124604 ** RtreeNode.pNext. RtreeNode.iNode stores the depth of the sub-tree
124605 ** headed by the node (leaf nodes have RtreeNode.iNode==0).
124607 RtreeNode *pDeleted;
124608 int iReinsertHeight; /* Height of sub-trees Reinsert() has run on */
124610 /* Statements to read/write/delete a record from xxx_node */
124611 sqlite3_stmt *pReadNode;
124612 sqlite3_stmt *pWriteNode;
124613 sqlite3_stmt *pDeleteNode;
124615 /* Statements to read/write/delete a record from xxx_rowid */
124616 sqlite3_stmt *pReadRowid;
124617 sqlite3_stmt *pWriteRowid;
124618 sqlite3_stmt *pDeleteRowid;
124620 /* Statements to read/write/delete a record from xxx_parent */
124621 sqlite3_stmt *pReadParent;
124622 sqlite3_stmt *pWriteParent;
124623 sqlite3_stmt *pDeleteParent;
124625 int eCoordType;
124628 /* Possible values for eCoordType: */
124629 #define RTREE_COORD_REAL32 0
124630 #define RTREE_COORD_INT32 1
124633 ** The minimum number of cells allowed for a node is a third of the
124634 ** maximum. In Gutman's notation:
124636 ** m = M/3
124638 ** If an R*-tree "Reinsert" operation is required, the same number of
124639 ** cells are removed from the overfull node and reinserted into the tree.
124641 #define RTREE_MINCELLS(p) ((((p)->iNodeSize-4)/(p)->nBytesPerCell)/3)
124642 #define RTREE_REINSERT(p) RTREE_MINCELLS(p)
124643 #define RTREE_MAXCELLS 51
124646 ** The smallest possible node-size is (512-64)==448 bytes. And the largest
124647 ** supported cell size is 48 bytes (8 byte rowid + ten 4 byte coordinates).
124648 ** Therefore all non-root nodes must contain at least 3 entries. Since
124649 ** 2^40 is greater than 2^64, an r-tree structure always has a depth of
124650 ** 40 or less.
124652 #define RTREE_MAX_DEPTH 40
124655 ** An rtree cursor object.
124657 struct RtreeCursor {
124658 sqlite3_vtab_cursor base;
124659 RtreeNode *pNode; /* Node cursor is currently pointing at */
124660 int iCell; /* Index of current cell in pNode */
124661 int iStrategy; /* Copy of idxNum search parameter */
124662 int nConstraint; /* Number of entries in aConstraint */
124663 RtreeConstraint *aConstraint; /* Search constraints. */
124666 union RtreeCoord {
124667 float f;
124668 int i;
124672 ** The argument is an RtreeCoord. Return the value stored within the RtreeCoord
124673 ** formatted as a double. This macro assumes that local variable pRtree points
124674 ** to the Rtree structure associated with the RtreeCoord.
124676 #define DCOORD(coord) ( \
124677 (pRtree->eCoordType==RTREE_COORD_REAL32) ? \
124678 ((double)coord.f) : \
124679 ((double)coord.i) \
124683 ** A search constraint.
124685 struct RtreeConstraint {
124686 int iCoord; /* Index of constrained coordinate */
124687 int op; /* Constraining operation */
124688 double rValue; /* Constraint value. */
124689 int (*xGeom)(sqlite3_rtree_geometry *, int, double *, int *);
124690 sqlite3_rtree_geometry *pGeom; /* Constraint callback argument for a MATCH */
124693 /* Possible values for RtreeConstraint.op */
124694 #define RTREE_EQ 0x41
124695 #define RTREE_LE 0x42
124696 #define RTREE_LT 0x43
124697 #define RTREE_GE 0x44
124698 #define RTREE_GT 0x45
124699 #define RTREE_MATCH 0x46
124702 ** An rtree structure node.
124704 struct RtreeNode {
124705 RtreeNode *pParent; /* Parent node */
124706 i64 iNode;
124707 int nRef;
124708 int isDirty;
124709 u8 *zData;
124710 RtreeNode *pNext; /* Next node in this hash chain */
124712 #define NCELL(pNode) readInt16(&(pNode)->zData[2])
124715 ** Structure to store a deserialized rtree record.
124717 struct RtreeCell {
124718 i64 iRowid;
124719 RtreeCoord aCoord[RTREE_MAX_DIMENSIONS*2];
124724 ** Value for the first field of every RtreeMatchArg object. The MATCH
124725 ** operator tests that the first field of a blob operand matches this
124726 ** value to avoid operating on invalid blobs (which could cause a segfault).
124728 #define RTREE_GEOMETRY_MAGIC 0x891245AB
124731 ** An instance of this structure must be supplied as a blob argument to
124732 ** the right-hand-side of an SQL MATCH operator used to constrain an
124733 ** r-tree query.
124735 struct RtreeMatchArg {
124736 u32 magic; /* Always RTREE_GEOMETRY_MAGIC */
124737 int (*xGeom)(sqlite3_rtree_geometry *, int, double *, int *);
124738 void *pContext;
124739 int nParam;
124740 double aParam[1];
124744 ** When a geometry callback is created (see sqlite3_rtree_geometry_callback),
124745 ** a single instance of the following structure is allocated. It is used
124746 ** as the context for the user-function created by by s_r_g_c(). The object
124747 ** is eventually deleted by the destructor mechanism provided by
124748 ** sqlite3_create_function_v2() (which is called by s_r_g_c() to create
124749 ** the geometry callback function).
124751 struct RtreeGeomCallback {
124752 int (*xGeom)(sqlite3_rtree_geometry *, int, double *, int *);
124753 void *pContext;
124756 #ifndef MAX
124757 # define MAX(x,y) ((x) < (y) ? (y) : (x))
124758 #endif
124759 #ifndef MIN
124760 # define MIN(x,y) ((x) > (y) ? (y) : (x))
124761 #endif
124764 ** Functions to deserialize a 16 bit integer, 32 bit real number and
124765 ** 64 bit integer. The deserialized value is returned.
124767 static int readInt16(u8 *p){
124768 return (p[0]<<8) + p[1];
124770 static void readCoord(u8 *p, RtreeCoord *pCoord){
124771 u32 i = (
124772 (((u32)p[0]) << 24) +
124773 (((u32)p[1]) << 16) +
124774 (((u32)p[2]) << 8) +
124775 (((u32)p[3]) << 0)
124777 *(u32 *)pCoord = i;
124779 static i64 readInt64(u8 *p){
124780 return (
124781 (((i64)p[0]) << 56) +
124782 (((i64)p[1]) << 48) +
124783 (((i64)p[2]) << 40) +
124784 (((i64)p[3]) << 32) +
124785 (((i64)p[4]) << 24) +
124786 (((i64)p[5]) << 16) +
124787 (((i64)p[6]) << 8) +
124788 (((i64)p[7]) << 0)
124793 ** Functions to serialize a 16 bit integer, 32 bit real number and
124794 ** 64 bit integer. The value returned is the number of bytes written
124795 ** to the argument buffer (always 2, 4 and 8 respectively).
124797 static int writeInt16(u8 *p, int i){
124798 p[0] = (i>> 8)&0xFF;
124799 p[1] = (i>> 0)&0xFF;
124800 return 2;
124802 static int writeCoord(u8 *p, RtreeCoord *pCoord){
124803 u32 i;
124804 assert( sizeof(RtreeCoord)==4 );
124805 assert( sizeof(u32)==4 );
124806 i = *(u32 *)pCoord;
124807 p[0] = (i>>24)&0xFF;
124808 p[1] = (i>>16)&0xFF;
124809 p[2] = (i>> 8)&0xFF;
124810 p[3] = (i>> 0)&0xFF;
124811 return 4;
124813 static int writeInt64(u8 *p, i64 i){
124814 p[0] = (i>>56)&0xFF;
124815 p[1] = (i>>48)&0xFF;
124816 p[2] = (i>>40)&0xFF;
124817 p[3] = (i>>32)&0xFF;
124818 p[4] = (i>>24)&0xFF;
124819 p[5] = (i>>16)&0xFF;
124820 p[6] = (i>> 8)&0xFF;
124821 p[7] = (i>> 0)&0xFF;
124822 return 8;
124826 ** Increment the reference count of node p.
124828 static void nodeReference(RtreeNode *p){
124829 if( p ){
124830 p->nRef++;
124835 ** Clear the content of node p (set all bytes to 0x00).
124837 static void nodeZero(Rtree *pRtree, RtreeNode *p){
124838 memset(&p->zData[2], 0, pRtree->iNodeSize-2);
124839 p->isDirty = 1;
124843 ** Given a node number iNode, return the corresponding key to use
124844 ** in the Rtree.aHash table.
124846 static int nodeHash(i64 iNode){
124847 return (
124848 (iNode>>56) ^ (iNode>>48) ^ (iNode>>40) ^ (iNode>>32) ^
124849 (iNode>>24) ^ (iNode>>16) ^ (iNode>> 8) ^ (iNode>> 0)
124850 ) % HASHSIZE;
124854 ** Search the node hash table for node iNode. If found, return a pointer
124855 ** to it. Otherwise, return 0.
124857 static RtreeNode *nodeHashLookup(Rtree *pRtree, i64 iNode){
124858 RtreeNode *p;
124859 for(p=pRtree->aHash[nodeHash(iNode)]; p && p->iNode!=iNode; p=p->pNext);
124860 return p;
124864 ** Add node pNode to the node hash table.
124866 static void nodeHashInsert(Rtree *pRtree, RtreeNode *pNode){
124867 int iHash;
124868 assert( pNode->pNext==0 );
124869 iHash = nodeHash(pNode->iNode);
124870 pNode->pNext = pRtree->aHash[iHash];
124871 pRtree->aHash[iHash] = pNode;
124875 ** Remove node pNode from the node hash table.
124877 static void nodeHashDelete(Rtree *pRtree, RtreeNode *pNode){
124878 RtreeNode **pp;
124879 if( pNode->iNode!=0 ){
124880 pp = &pRtree->aHash[nodeHash(pNode->iNode)];
124881 for( ; (*pp)!=pNode; pp = &(*pp)->pNext){ assert(*pp); }
124882 *pp = pNode->pNext;
124883 pNode->pNext = 0;
124888 ** Allocate and return new r-tree node. Initially, (RtreeNode.iNode==0),
124889 ** indicating that node has not yet been assigned a node number. It is
124890 ** assigned a node number when nodeWrite() is called to write the
124891 ** node contents out to the database.
124893 static RtreeNode *nodeNew(Rtree *pRtree, RtreeNode *pParent){
124894 RtreeNode *pNode;
124895 pNode = (RtreeNode *)sqlite3_malloc(sizeof(RtreeNode) + pRtree->iNodeSize);
124896 if( pNode ){
124897 memset(pNode, 0, sizeof(RtreeNode) + pRtree->iNodeSize);
124898 pNode->zData = (u8 *)&pNode[1];
124899 pNode->nRef = 1;
124900 pNode->pParent = pParent;
124901 pNode->isDirty = 1;
124902 nodeReference(pParent);
124904 return pNode;
124908 ** Obtain a reference to an r-tree node.
124910 static int
124911 nodeAcquire(
124912 Rtree *pRtree, /* R-tree structure */
124913 i64 iNode, /* Node number to load */
124914 RtreeNode *pParent, /* Either the parent node or NULL */
124915 RtreeNode **ppNode /* OUT: Acquired node */
124917 int rc;
124918 int rc2 = SQLITE_OK;
124919 RtreeNode *pNode;
124921 /* Check if the requested node is already in the hash table. If so,
124922 ** increase its reference count and return it.
124924 if( (pNode = nodeHashLookup(pRtree, iNode)) ){
124925 assert( !pParent || !pNode->pParent || pNode->pParent==pParent );
124926 if( pParent && !pNode->pParent ){
124927 nodeReference(pParent);
124928 pNode->pParent = pParent;
124930 pNode->nRef++;
124931 *ppNode = pNode;
124932 return SQLITE_OK;
124935 sqlite3_bind_int64(pRtree->pReadNode, 1, iNode);
124936 rc = sqlite3_step(pRtree->pReadNode);
124937 if( rc==SQLITE_ROW ){
124938 const u8 *zBlob = sqlite3_column_blob(pRtree->pReadNode, 0);
124939 if( pRtree->iNodeSize==sqlite3_column_bytes(pRtree->pReadNode, 0) ){
124940 pNode = (RtreeNode *)sqlite3_malloc(sizeof(RtreeNode)+pRtree->iNodeSize);
124941 if( !pNode ){
124942 rc2 = SQLITE_NOMEM;
124943 }else{
124944 pNode->pParent = pParent;
124945 pNode->zData = (u8 *)&pNode[1];
124946 pNode->nRef = 1;
124947 pNode->iNode = iNode;
124948 pNode->isDirty = 0;
124949 pNode->pNext = 0;
124950 memcpy(pNode->zData, zBlob, pRtree->iNodeSize);
124951 nodeReference(pParent);
124955 rc = sqlite3_reset(pRtree->pReadNode);
124956 if( rc==SQLITE_OK ) rc = rc2;
124958 /* If the root node was just loaded, set pRtree->iDepth to the height
124959 ** of the r-tree structure. A height of zero means all data is stored on
124960 ** the root node. A height of one means the children of the root node
124961 ** are the leaves, and so on. If the depth as specified on the root node
124962 ** is greater than RTREE_MAX_DEPTH, the r-tree structure must be corrupt.
124964 if( pNode && iNode==1 ){
124965 pRtree->iDepth = readInt16(pNode->zData);
124966 if( pRtree->iDepth>RTREE_MAX_DEPTH ){
124967 rc = SQLITE_CORRUPT;
124971 /* If no error has occurred so far, check if the "number of entries"
124972 ** field on the node is too large. If so, set the return code to
124973 ** SQLITE_CORRUPT.
124975 if( pNode && rc==SQLITE_OK ){
124976 if( NCELL(pNode)>((pRtree->iNodeSize-4)/pRtree->nBytesPerCell) ){
124977 rc = SQLITE_CORRUPT;
124981 if( rc==SQLITE_OK ){
124982 if( pNode!=0 ){
124983 nodeHashInsert(pRtree, pNode);
124984 }else{
124985 rc = SQLITE_CORRUPT;
124987 *ppNode = pNode;
124988 }else{
124989 sqlite3_free(pNode);
124990 *ppNode = 0;
124993 return rc;
124997 ** Overwrite cell iCell of node pNode with the contents of pCell.
124999 static void nodeOverwriteCell(
125000 Rtree *pRtree,
125001 RtreeNode *pNode,
125002 RtreeCell *pCell,
125003 int iCell
125005 int ii;
125006 u8 *p = &pNode->zData[4 + pRtree->nBytesPerCell*iCell];
125007 p += writeInt64(p, pCell->iRowid);
125008 for(ii=0; ii<(pRtree->nDim*2); ii++){
125009 p += writeCoord(p, &pCell->aCoord[ii]);
125011 pNode->isDirty = 1;
125015 ** Remove cell the cell with index iCell from node pNode.
125017 static void nodeDeleteCell(Rtree *pRtree, RtreeNode *pNode, int iCell){
125018 u8 *pDst = &pNode->zData[4 + pRtree->nBytesPerCell*iCell];
125019 u8 *pSrc = &pDst[pRtree->nBytesPerCell];
125020 int nByte = (NCELL(pNode) - iCell - 1) * pRtree->nBytesPerCell;
125021 memmove(pDst, pSrc, nByte);
125022 writeInt16(&pNode->zData[2], NCELL(pNode)-1);
125023 pNode->isDirty = 1;
125027 ** Insert the contents of cell pCell into node pNode. If the insert
125028 ** is successful, return SQLITE_OK.
125030 ** If there is not enough free space in pNode, return SQLITE_FULL.
125032 static int
125033 nodeInsertCell(
125034 Rtree *pRtree,
125035 RtreeNode *pNode,
125036 RtreeCell *pCell
125038 int nCell; /* Current number of cells in pNode */
125039 int nMaxCell; /* Maximum number of cells for pNode */
125041 nMaxCell = (pRtree->iNodeSize-4)/pRtree->nBytesPerCell;
125042 nCell = NCELL(pNode);
125044 assert( nCell<=nMaxCell );
125045 if( nCell<nMaxCell ){
125046 nodeOverwriteCell(pRtree, pNode, pCell, nCell);
125047 writeInt16(&pNode->zData[2], nCell+1);
125048 pNode->isDirty = 1;
125051 return (nCell==nMaxCell);
125055 ** If the node is dirty, write it out to the database.
125057 static int
125058 nodeWrite(Rtree *pRtree, RtreeNode *pNode){
125059 int rc = SQLITE_OK;
125060 if( pNode->isDirty ){
125061 sqlite3_stmt *p = pRtree->pWriteNode;
125062 if( pNode->iNode ){
125063 sqlite3_bind_int64(p, 1, pNode->iNode);
125064 }else{
125065 sqlite3_bind_null(p, 1);
125067 sqlite3_bind_blob(p, 2, pNode->zData, pRtree->iNodeSize, SQLITE_STATIC);
125068 sqlite3_step(p);
125069 pNode->isDirty = 0;
125070 rc = sqlite3_reset(p);
125071 if( pNode->iNode==0 && rc==SQLITE_OK ){
125072 pNode->iNode = sqlite3_last_insert_rowid(pRtree->db);
125073 nodeHashInsert(pRtree, pNode);
125076 return rc;
125080 ** Release a reference to a node. If the node is dirty and the reference
125081 ** count drops to zero, the node data is written to the database.
125083 static int
125084 nodeRelease(Rtree *pRtree, RtreeNode *pNode){
125085 int rc = SQLITE_OK;
125086 if( pNode ){
125087 assert( pNode->nRef>0 );
125088 pNode->nRef--;
125089 if( pNode->nRef==0 ){
125090 if( pNode->iNode==1 ){
125091 pRtree->iDepth = -1;
125093 if( pNode->pParent ){
125094 rc = nodeRelease(pRtree, pNode->pParent);
125096 if( rc==SQLITE_OK ){
125097 rc = nodeWrite(pRtree, pNode);
125099 nodeHashDelete(pRtree, pNode);
125100 sqlite3_free(pNode);
125103 return rc;
125107 ** Return the 64-bit integer value associated with cell iCell of
125108 ** node pNode. If pNode is a leaf node, this is a rowid. If it is
125109 ** an internal node, then the 64-bit integer is a child page number.
125111 static i64 nodeGetRowid(
125112 Rtree *pRtree,
125113 RtreeNode *pNode,
125114 int iCell
125116 assert( iCell<NCELL(pNode) );
125117 return readInt64(&pNode->zData[4 + pRtree->nBytesPerCell*iCell]);
125121 ** Return coordinate iCoord from cell iCell in node pNode.
125123 static void nodeGetCoord(
125124 Rtree *pRtree,
125125 RtreeNode *pNode,
125126 int iCell,
125127 int iCoord,
125128 RtreeCoord *pCoord /* Space to write result to */
125130 readCoord(&pNode->zData[12 + pRtree->nBytesPerCell*iCell + 4*iCoord], pCoord);
125134 ** Deserialize cell iCell of node pNode. Populate the structure pointed
125135 ** to by pCell with the results.
125137 static void nodeGetCell(
125138 Rtree *pRtree,
125139 RtreeNode *pNode,
125140 int iCell,
125141 RtreeCell *pCell
125143 int ii;
125144 pCell->iRowid = nodeGetRowid(pRtree, pNode, iCell);
125145 for(ii=0; ii<pRtree->nDim*2; ii++){
125146 nodeGetCoord(pRtree, pNode, iCell, ii, &pCell->aCoord[ii]);
125151 /* Forward declaration for the function that does the work of
125152 ** the virtual table module xCreate() and xConnect() methods.
125154 static int rtreeInit(
125155 sqlite3 *, void *, int, const char *const*, sqlite3_vtab **, char **, int
125159 ** Rtree virtual table module xCreate method.
125161 static int rtreeCreate(
125162 sqlite3 *db,
125163 void *pAux,
125164 int argc, const char *const*argv,
125165 sqlite3_vtab **ppVtab,
125166 char **pzErr
125168 return rtreeInit(db, pAux, argc, argv, ppVtab, pzErr, 1);
125172 ** Rtree virtual table module xConnect method.
125174 static int rtreeConnect(
125175 sqlite3 *db,
125176 void *pAux,
125177 int argc, const char *const*argv,
125178 sqlite3_vtab **ppVtab,
125179 char **pzErr
125181 return rtreeInit(db, pAux, argc, argv, ppVtab, pzErr, 0);
125185 ** Increment the r-tree reference count.
125187 static void rtreeReference(Rtree *pRtree){
125188 pRtree->nBusy++;
125192 ** Decrement the r-tree reference count. When the reference count reaches
125193 ** zero the structure is deleted.
125195 static void rtreeRelease(Rtree *pRtree){
125196 pRtree->nBusy--;
125197 if( pRtree->nBusy==0 ){
125198 sqlite3_finalize(pRtree->pReadNode);
125199 sqlite3_finalize(pRtree->pWriteNode);
125200 sqlite3_finalize(pRtree->pDeleteNode);
125201 sqlite3_finalize(pRtree->pReadRowid);
125202 sqlite3_finalize(pRtree->pWriteRowid);
125203 sqlite3_finalize(pRtree->pDeleteRowid);
125204 sqlite3_finalize(pRtree->pReadParent);
125205 sqlite3_finalize(pRtree->pWriteParent);
125206 sqlite3_finalize(pRtree->pDeleteParent);
125207 sqlite3_free(pRtree);
125212 ** Rtree virtual table module xDisconnect method.
125214 static int rtreeDisconnect(sqlite3_vtab *pVtab){
125215 rtreeRelease((Rtree *)pVtab);
125216 return SQLITE_OK;
125220 ** Rtree virtual table module xDestroy method.
125222 static int rtreeDestroy(sqlite3_vtab *pVtab){
125223 Rtree *pRtree = (Rtree *)pVtab;
125224 int rc;
125225 char *zCreate = sqlite3_mprintf(
125226 "DROP TABLE '%q'.'%q_node';"
125227 "DROP TABLE '%q'.'%q_rowid';"
125228 "DROP TABLE '%q'.'%q_parent';",
125229 pRtree->zDb, pRtree->zName,
125230 pRtree->zDb, pRtree->zName,
125231 pRtree->zDb, pRtree->zName
125233 if( !zCreate ){
125234 rc = SQLITE_NOMEM;
125235 }else{
125236 rc = sqlite3_exec(pRtree->db, zCreate, 0, 0, 0);
125237 sqlite3_free(zCreate);
125239 if( rc==SQLITE_OK ){
125240 rtreeRelease(pRtree);
125243 return rc;
125247 ** Rtree virtual table module xOpen method.
125249 static int rtreeOpen(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor){
125250 int rc = SQLITE_NOMEM;
125251 RtreeCursor *pCsr;
125253 pCsr = (RtreeCursor *)sqlite3_malloc(sizeof(RtreeCursor));
125254 if( pCsr ){
125255 memset(pCsr, 0, sizeof(RtreeCursor));
125256 pCsr->base.pVtab = pVTab;
125257 rc = SQLITE_OK;
125259 *ppCursor = (sqlite3_vtab_cursor *)pCsr;
125261 return rc;
125266 ** Free the RtreeCursor.aConstraint[] array and its contents.
125268 static void freeCursorConstraints(RtreeCursor *pCsr){
125269 if( pCsr->aConstraint ){
125270 int i; /* Used to iterate through constraint array */
125271 for(i=0; i<pCsr->nConstraint; i++){
125272 sqlite3_rtree_geometry *pGeom = pCsr->aConstraint[i].pGeom;
125273 if( pGeom ){
125274 if( pGeom->xDelUser ) pGeom->xDelUser(pGeom->pUser);
125275 sqlite3_free(pGeom);
125278 sqlite3_free(pCsr->aConstraint);
125279 pCsr->aConstraint = 0;
125284 ** Rtree virtual table module xClose method.
125286 static int rtreeClose(sqlite3_vtab_cursor *cur){
125287 Rtree *pRtree = (Rtree *)(cur->pVtab);
125288 int rc;
125289 RtreeCursor *pCsr = (RtreeCursor *)cur;
125290 freeCursorConstraints(pCsr);
125291 rc = nodeRelease(pRtree, pCsr->pNode);
125292 sqlite3_free(pCsr);
125293 return rc;
125297 ** Rtree virtual table module xEof method.
125299 ** Return non-zero if the cursor does not currently point to a valid
125300 ** record (i.e if the scan has finished), or zero otherwise.
125302 static int rtreeEof(sqlite3_vtab_cursor *cur){
125303 RtreeCursor *pCsr = (RtreeCursor *)cur;
125304 return (pCsr->pNode==0);
125308 ** The r-tree constraint passed as the second argument to this function is
125309 ** guaranteed to be a MATCH constraint.
125311 static int testRtreeGeom(
125312 Rtree *pRtree, /* R-Tree object */
125313 RtreeConstraint *pConstraint, /* MATCH constraint to test */
125314 RtreeCell *pCell, /* Cell to test */
125315 int *pbRes /* OUT: Test result */
125317 int i;
125318 double aCoord[RTREE_MAX_DIMENSIONS*2];
125319 int nCoord = pRtree->nDim*2;
125321 assert( pConstraint->op==RTREE_MATCH );
125322 assert( pConstraint->pGeom );
125324 for(i=0; i<nCoord; i++){
125325 aCoord[i] = DCOORD(pCell->aCoord[i]);
125327 return pConstraint->xGeom(pConstraint->pGeom, nCoord, aCoord, pbRes);
125331 ** Cursor pCursor currently points to a cell in a non-leaf page.
125332 ** Set *pbEof to true if the sub-tree headed by the cell is filtered
125333 ** (excluded) by the constraints in the pCursor->aConstraint[]
125334 ** array, or false otherwise.
125336 ** Return SQLITE_OK if successful or an SQLite error code if an error
125337 ** occurs within a geometry callback.
125339 static int testRtreeCell(Rtree *pRtree, RtreeCursor *pCursor, int *pbEof){
125340 RtreeCell cell;
125341 int ii;
125342 int bRes = 0;
125343 int rc = SQLITE_OK;
125345 nodeGetCell(pRtree, pCursor->pNode, pCursor->iCell, &cell);
125346 for(ii=0; bRes==0 && ii<pCursor->nConstraint; ii++){
125347 RtreeConstraint *p = &pCursor->aConstraint[ii];
125348 double cell_min = DCOORD(cell.aCoord[(p->iCoord>>1)*2]);
125349 double cell_max = DCOORD(cell.aCoord[(p->iCoord>>1)*2+1]);
125351 assert(p->op==RTREE_LE || p->op==RTREE_LT || p->op==RTREE_GE
125352 || p->op==RTREE_GT || p->op==RTREE_EQ || p->op==RTREE_MATCH
125355 switch( p->op ){
125356 case RTREE_LE: case RTREE_LT:
125357 bRes = p->rValue<cell_min;
125358 break;
125360 case RTREE_GE: case RTREE_GT:
125361 bRes = p->rValue>cell_max;
125362 break;
125364 case RTREE_EQ:
125365 bRes = (p->rValue>cell_max || p->rValue<cell_min);
125366 break;
125368 default: {
125369 assert( p->op==RTREE_MATCH );
125370 rc = testRtreeGeom(pRtree, p, &cell, &bRes);
125371 bRes = !bRes;
125372 break;
125377 *pbEof = bRes;
125378 return rc;
125382 ** Test if the cell that cursor pCursor currently points to
125383 ** would be filtered (excluded) by the constraints in the
125384 ** pCursor->aConstraint[] array. If so, set *pbEof to true before
125385 ** returning. If the cell is not filtered (excluded) by the constraints,
125386 ** set pbEof to zero.
125388 ** Return SQLITE_OK if successful or an SQLite error code if an error
125389 ** occurs within a geometry callback.
125391 ** This function assumes that the cell is part of a leaf node.
125393 static int testRtreeEntry(Rtree *pRtree, RtreeCursor *pCursor, int *pbEof){
125394 RtreeCell cell;
125395 int ii;
125396 *pbEof = 0;
125398 nodeGetCell(pRtree, pCursor->pNode, pCursor->iCell, &cell);
125399 for(ii=0; ii<pCursor->nConstraint; ii++){
125400 RtreeConstraint *p = &pCursor->aConstraint[ii];
125401 double coord = DCOORD(cell.aCoord[p->iCoord]);
125402 int res;
125403 assert(p->op==RTREE_LE || p->op==RTREE_LT || p->op==RTREE_GE
125404 || p->op==RTREE_GT || p->op==RTREE_EQ || p->op==RTREE_MATCH
125406 switch( p->op ){
125407 case RTREE_LE: res = (coord<=p->rValue); break;
125408 case RTREE_LT: res = (coord<p->rValue); break;
125409 case RTREE_GE: res = (coord>=p->rValue); break;
125410 case RTREE_GT: res = (coord>p->rValue); break;
125411 case RTREE_EQ: res = (coord==p->rValue); break;
125412 default: {
125413 int rc;
125414 assert( p->op==RTREE_MATCH );
125415 rc = testRtreeGeom(pRtree, p, &cell, &res);
125416 if( rc!=SQLITE_OK ){
125417 return rc;
125419 break;
125423 if( !res ){
125424 *pbEof = 1;
125425 return SQLITE_OK;
125429 return SQLITE_OK;
125433 ** Cursor pCursor currently points at a node that heads a sub-tree of
125434 ** height iHeight (if iHeight==0, then the node is a leaf). Descend
125435 ** to point to the left-most cell of the sub-tree that matches the
125436 ** configured constraints.
125438 static int descendToCell(
125439 Rtree *pRtree,
125440 RtreeCursor *pCursor,
125441 int iHeight,
125442 int *pEof /* OUT: Set to true if cannot descend */
125444 int isEof;
125445 int rc;
125446 int ii;
125447 RtreeNode *pChild;
125448 sqlite3_int64 iRowid;
125450 RtreeNode *pSavedNode = pCursor->pNode;
125451 int iSavedCell = pCursor->iCell;
125453 assert( iHeight>=0 );
125455 if( iHeight==0 ){
125456 rc = testRtreeEntry(pRtree, pCursor, &isEof);
125457 }else{
125458 rc = testRtreeCell(pRtree, pCursor, &isEof);
125460 if( rc!=SQLITE_OK || isEof || iHeight==0 ){
125461 goto descend_to_cell_out;
125464 iRowid = nodeGetRowid(pRtree, pCursor->pNode, pCursor->iCell);
125465 rc = nodeAcquire(pRtree, iRowid, pCursor->pNode, &pChild);
125466 if( rc!=SQLITE_OK ){
125467 goto descend_to_cell_out;
125470 nodeRelease(pRtree, pCursor->pNode);
125471 pCursor->pNode = pChild;
125472 isEof = 1;
125473 for(ii=0; isEof && ii<NCELL(pChild); ii++){
125474 pCursor->iCell = ii;
125475 rc = descendToCell(pRtree, pCursor, iHeight-1, &isEof);
125476 if( rc!=SQLITE_OK ){
125477 goto descend_to_cell_out;
125481 if( isEof ){
125482 assert( pCursor->pNode==pChild );
125483 nodeReference(pSavedNode);
125484 nodeRelease(pRtree, pChild);
125485 pCursor->pNode = pSavedNode;
125486 pCursor->iCell = iSavedCell;
125489 descend_to_cell_out:
125490 *pEof = isEof;
125491 return rc;
125495 ** One of the cells in node pNode is guaranteed to have a 64-bit
125496 ** integer value equal to iRowid. Return the index of this cell.
125498 static int nodeRowidIndex(
125499 Rtree *pRtree,
125500 RtreeNode *pNode,
125501 i64 iRowid,
125502 int *piIndex
125504 int ii;
125505 int nCell = NCELL(pNode);
125506 for(ii=0; ii<nCell; ii++){
125507 if( nodeGetRowid(pRtree, pNode, ii)==iRowid ){
125508 *piIndex = ii;
125509 return SQLITE_OK;
125512 return SQLITE_CORRUPT;
125516 ** Return the index of the cell containing a pointer to node pNode
125517 ** in its parent. If pNode is the root node, return -1.
125519 static int nodeParentIndex(Rtree *pRtree, RtreeNode *pNode, int *piIndex){
125520 RtreeNode *pParent = pNode->pParent;
125521 if( pParent ){
125522 return nodeRowidIndex(pRtree, pParent, pNode->iNode, piIndex);
125524 *piIndex = -1;
125525 return SQLITE_OK;
125529 ** Rtree virtual table module xNext method.
125531 static int rtreeNext(sqlite3_vtab_cursor *pVtabCursor){
125532 Rtree *pRtree = (Rtree *)(pVtabCursor->pVtab);
125533 RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor;
125534 int rc = SQLITE_OK;
125536 /* RtreeCursor.pNode must not be NULL. If is is NULL, then this cursor is
125537 ** already at EOF. It is against the rules to call the xNext() method of
125538 ** a cursor that has already reached EOF.
125540 assert( pCsr->pNode );
125542 if( pCsr->iStrategy==1 ){
125543 /* This "scan" is a direct lookup by rowid. There is no next entry. */
125544 nodeRelease(pRtree, pCsr->pNode);
125545 pCsr->pNode = 0;
125546 }else{
125547 /* Move to the next entry that matches the configured constraints. */
125548 int iHeight = 0;
125549 while( pCsr->pNode ){
125550 RtreeNode *pNode = pCsr->pNode;
125551 int nCell = NCELL(pNode);
125552 for(pCsr->iCell++; pCsr->iCell<nCell; pCsr->iCell++){
125553 int isEof;
125554 rc = descendToCell(pRtree, pCsr, iHeight, &isEof);
125555 if( rc!=SQLITE_OK || !isEof ){
125556 return rc;
125559 pCsr->pNode = pNode->pParent;
125560 rc = nodeParentIndex(pRtree, pNode, &pCsr->iCell);
125561 if( rc!=SQLITE_OK ){
125562 return rc;
125564 nodeReference(pCsr->pNode);
125565 nodeRelease(pRtree, pNode);
125566 iHeight++;
125570 return rc;
125574 ** Rtree virtual table module xRowid method.
125576 static int rtreeRowid(sqlite3_vtab_cursor *pVtabCursor, sqlite_int64 *pRowid){
125577 Rtree *pRtree = (Rtree *)pVtabCursor->pVtab;
125578 RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor;
125580 assert(pCsr->pNode);
125581 *pRowid = nodeGetRowid(pRtree, pCsr->pNode, pCsr->iCell);
125583 return SQLITE_OK;
125587 ** Rtree virtual table module xColumn method.
125589 static int rtreeColumn(sqlite3_vtab_cursor *cur, sqlite3_context *ctx, int i){
125590 Rtree *pRtree = (Rtree *)cur->pVtab;
125591 RtreeCursor *pCsr = (RtreeCursor *)cur;
125593 if( i==0 ){
125594 i64 iRowid = nodeGetRowid(pRtree, pCsr->pNode, pCsr->iCell);
125595 sqlite3_result_int64(ctx, iRowid);
125596 }else{
125597 RtreeCoord c;
125598 nodeGetCoord(pRtree, pCsr->pNode, pCsr->iCell, i-1, &c);
125599 if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
125600 sqlite3_result_double(ctx, c.f);
125601 }else{
125602 assert( pRtree->eCoordType==RTREE_COORD_INT32 );
125603 sqlite3_result_int(ctx, c.i);
125607 return SQLITE_OK;
125611 ** Use nodeAcquire() to obtain the leaf node containing the record with
125612 ** rowid iRowid. If successful, set *ppLeaf to point to the node and
125613 ** return SQLITE_OK. If there is no such record in the table, set
125614 ** *ppLeaf to 0 and return SQLITE_OK. If an error occurs, set *ppLeaf
125615 ** to zero and return an SQLite error code.
125617 static int findLeafNode(Rtree *pRtree, i64 iRowid, RtreeNode **ppLeaf){
125618 int rc;
125619 *ppLeaf = 0;
125620 sqlite3_bind_int64(pRtree->pReadRowid, 1, iRowid);
125621 if( sqlite3_step(pRtree->pReadRowid)==SQLITE_ROW ){
125622 i64 iNode = sqlite3_column_int64(pRtree->pReadRowid, 0);
125623 rc = nodeAcquire(pRtree, iNode, 0, ppLeaf);
125624 sqlite3_reset(pRtree->pReadRowid);
125625 }else{
125626 rc = sqlite3_reset(pRtree->pReadRowid);
125628 return rc;
125632 ** This function is called to configure the RtreeConstraint object passed
125633 ** as the second argument for a MATCH constraint. The value passed as the
125634 ** first argument to this function is the right-hand operand to the MATCH
125635 ** operator.
125637 static int deserializeGeometry(sqlite3_value *pValue, RtreeConstraint *pCons){
125638 RtreeMatchArg *p;
125639 sqlite3_rtree_geometry *pGeom;
125640 int nBlob;
125642 /* Check that value is actually a blob. */
125643 if( !sqlite3_value_type(pValue)==SQLITE_BLOB ) return SQLITE_ERROR;
125645 /* Check that the blob is roughly the right size. */
125646 nBlob = sqlite3_value_bytes(pValue);
125647 if( nBlob<(int)sizeof(RtreeMatchArg)
125648 || ((nBlob-sizeof(RtreeMatchArg))%sizeof(double))!=0
125650 return SQLITE_ERROR;
125653 pGeom = (sqlite3_rtree_geometry *)sqlite3_malloc(
125654 sizeof(sqlite3_rtree_geometry) + nBlob
125656 if( !pGeom ) return SQLITE_NOMEM;
125657 memset(pGeom, 0, sizeof(sqlite3_rtree_geometry));
125658 p = (RtreeMatchArg *)&pGeom[1];
125660 memcpy(p, sqlite3_value_blob(pValue), nBlob);
125661 if( p->magic!=RTREE_GEOMETRY_MAGIC
125662 || nBlob!=(int)(sizeof(RtreeMatchArg) + (p->nParam-1)*sizeof(double))
125664 sqlite3_free(pGeom);
125665 return SQLITE_ERROR;
125668 pGeom->pContext = p->pContext;
125669 pGeom->nParam = p->nParam;
125670 pGeom->aParam = p->aParam;
125672 pCons->xGeom = p->xGeom;
125673 pCons->pGeom = pGeom;
125674 return SQLITE_OK;
125678 ** Rtree virtual table module xFilter method.
125680 static int rtreeFilter(
125681 sqlite3_vtab_cursor *pVtabCursor,
125682 int idxNum, const char *idxStr,
125683 int argc, sqlite3_value **argv
125685 Rtree *pRtree = (Rtree *)pVtabCursor->pVtab;
125686 RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor;
125688 RtreeNode *pRoot = 0;
125689 int ii;
125690 int rc = SQLITE_OK;
125692 rtreeReference(pRtree);
125694 freeCursorConstraints(pCsr);
125695 pCsr->iStrategy = idxNum;
125697 if( idxNum==1 ){
125698 /* Special case - lookup by rowid. */
125699 RtreeNode *pLeaf; /* Leaf on which the required cell resides */
125700 i64 iRowid = sqlite3_value_int64(argv[0]);
125701 rc = findLeafNode(pRtree, iRowid, &pLeaf);
125702 pCsr->pNode = pLeaf;
125703 if( pLeaf ){
125704 assert( rc==SQLITE_OK );
125705 rc = nodeRowidIndex(pRtree, pLeaf, iRowid, &pCsr->iCell);
125707 }else{
125708 /* Normal case - r-tree scan. Set up the RtreeCursor.aConstraint array
125709 ** with the configured constraints.
125711 if( argc>0 ){
125712 pCsr->aConstraint = sqlite3_malloc(sizeof(RtreeConstraint)*argc);
125713 pCsr->nConstraint = argc;
125714 if( !pCsr->aConstraint ){
125715 rc = SQLITE_NOMEM;
125716 }else{
125717 memset(pCsr->aConstraint, 0, sizeof(RtreeConstraint)*argc);
125718 assert( (idxStr==0 && argc==0) || (int)strlen(idxStr)==argc*2 );
125719 for(ii=0; ii<argc; ii++){
125720 RtreeConstraint *p = &pCsr->aConstraint[ii];
125721 p->op = idxStr[ii*2];
125722 p->iCoord = idxStr[ii*2+1]-'a';
125723 if( p->op==RTREE_MATCH ){
125724 /* A MATCH operator. The right-hand-side must be a blob that
125725 ** can be cast into an RtreeMatchArg object. One created using
125726 ** an sqlite3_rtree_geometry_callback() SQL user function.
125728 rc = deserializeGeometry(argv[ii], p);
125729 if( rc!=SQLITE_OK ){
125730 break;
125732 }else{
125733 p->rValue = sqlite3_value_double(argv[ii]);
125739 if( rc==SQLITE_OK ){
125740 pCsr->pNode = 0;
125741 rc = nodeAcquire(pRtree, 1, 0, &pRoot);
125743 if( rc==SQLITE_OK ){
125744 int isEof = 1;
125745 int nCell = NCELL(pRoot);
125746 pCsr->pNode = pRoot;
125747 for(pCsr->iCell=0; rc==SQLITE_OK && pCsr->iCell<nCell; pCsr->iCell++){
125748 assert( pCsr->pNode==pRoot );
125749 rc = descendToCell(pRtree, pCsr, pRtree->iDepth, &isEof);
125750 if( !isEof ){
125751 break;
125754 if( rc==SQLITE_OK && isEof ){
125755 assert( pCsr->pNode==pRoot );
125756 nodeRelease(pRtree, pRoot);
125757 pCsr->pNode = 0;
125759 assert( rc!=SQLITE_OK || !pCsr->pNode || pCsr->iCell<NCELL(pCsr->pNode) );
125763 rtreeRelease(pRtree);
125764 return rc;
125768 ** Rtree virtual table module xBestIndex method. There are three
125769 ** table scan strategies to choose from (in order from most to
125770 ** least desirable):
125772 ** idxNum idxStr Strategy
125773 ** ------------------------------------------------
125774 ** 1 Unused Direct lookup by rowid.
125775 ** 2 See below R-tree query or full-table scan.
125776 ** ------------------------------------------------
125778 ** If strategy 1 is used, then idxStr is not meaningful. If strategy
125779 ** 2 is used, idxStr is formatted to contain 2 bytes for each
125780 ** constraint used. The first two bytes of idxStr correspond to
125781 ** the constraint in sqlite3_index_info.aConstraintUsage[] with
125782 ** (argvIndex==1) etc.
125784 ** The first of each pair of bytes in idxStr identifies the constraint
125785 ** operator as follows:
125787 ** Operator Byte Value
125788 ** ----------------------
125789 ** = 0x41 ('A')
125790 ** <= 0x42 ('B')
125791 ** < 0x43 ('C')
125792 ** >= 0x44 ('D')
125793 ** > 0x45 ('E')
125794 ** MATCH 0x46 ('F')
125795 ** ----------------------
125797 ** The second of each pair of bytes identifies the coordinate column
125798 ** to which the constraint applies. The leftmost coordinate column
125799 ** is 'a', the second from the left 'b' etc.
125801 static int rtreeBestIndex(sqlite3_vtab *tab, sqlite3_index_info *pIdxInfo){
125802 int rc = SQLITE_OK;
125803 int ii;
125805 int iIdx = 0;
125806 char zIdxStr[RTREE_MAX_DIMENSIONS*8+1];
125807 memset(zIdxStr, 0, sizeof(zIdxStr));
125808 UNUSED_PARAMETER(tab);
125810 assert( pIdxInfo->idxStr==0 );
125811 for(ii=0; ii<pIdxInfo->nConstraint && iIdx<(int)(sizeof(zIdxStr)-1); ii++){
125812 struct sqlite3_index_constraint *p = &pIdxInfo->aConstraint[ii];
125814 if( p->usable && p->iColumn==0 && p->op==SQLITE_INDEX_CONSTRAINT_EQ ){
125815 /* We have an equality constraint on the rowid. Use strategy 1. */
125816 int jj;
125817 for(jj=0; jj<ii; jj++){
125818 pIdxInfo->aConstraintUsage[jj].argvIndex = 0;
125819 pIdxInfo->aConstraintUsage[jj].omit = 0;
125821 pIdxInfo->idxNum = 1;
125822 pIdxInfo->aConstraintUsage[ii].argvIndex = 1;
125823 pIdxInfo->aConstraintUsage[jj].omit = 1;
125825 /* This strategy involves a two rowid lookups on an B-Tree structures
125826 ** and then a linear search of an R-Tree node. This should be
125827 ** considered almost as quick as a direct rowid lookup (for which
125828 ** sqlite uses an internal cost of 0.0).
125830 pIdxInfo->estimatedCost = 10.0;
125831 return SQLITE_OK;
125834 if( p->usable && (p->iColumn>0 || p->op==SQLITE_INDEX_CONSTRAINT_MATCH) ){
125835 u8 op;
125836 switch( p->op ){
125837 case SQLITE_INDEX_CONSTRAINT_EQ: op = RTREE_EQ; break;
125838 case SQLITE_INDEX_CONSTRAINT_GT: op = RTREE_GT; break;
125839 case SQLITE_INDEX_CONSTRAINT_LE: op = RTREE_LE; break;
125840 case SQLITE_INDEX_CONSTRAINT_LT: op = RTREE_LT; break;
125841 case SQLITE_INDEX_CONSTRAINT_GE: op = RTREE_GE; break;
125842 default:
125843 assert( p->op==SQLITE_INDEX_CONSTRAINT_MATCH );
125844 op = RTREE_MATCH;
125845 break;
125847 zIdxStr[iIdx++] = op;
125848 zIdxStr[iIdx++] = p->iColumn - 1 + 'a';
125849 pIdxInfo->aConstraintUsage[ii].argvIndex = (iIdx/2);
125850 pIdxInfo->aConstraintUsage[ii].omit = 1;
125854 pIdxInfo->idxNum = 2;
125855 pIdxInfo->needToFreeIdxStr = 1;
125856 if( iIdx>0 && 0==(pIdxInfo->idxStr = sqlite3_mprintf("%s", zIdxStr)) ){
125857 return SQLITE_NOMEM;
125859 assert( iIdx>=0 );
125860 pIdxInfo->estimatedCost = (2000000.0 / (double)(iIdx + 1));
125861 return rc;
125865 ** Return the N-dimensional volumn of the cell stored in *p.
125867 static float cellArea(Rtree *pRtree, RtreeCell *p){
125868 float area = 1.0;
125869 int ii;
125870 for(ii=0; ii<(pRtree->nDim*2); ii+=2){
125871 area = area * (DCOORD(p->aCoord[ii+1]) - DCOORD(p->aCoord[ii]));
125873 return area;
125877 ** Return the margin length of cell p. The margin length is the sum
125878 ** of the objects size in each dimension.
125880 static float cellMargin(Rtree *pRtree, RtreeCell *p){
125881 float margin = 0.0;
125882 int ii;
125883 for(ii=0; ii<(pRtree->nDim*2); ii+=2){
125884 margin += (DCOORD(p->aCoord[ii+1]) - DCOORD(p->aCoord[ii]));
125886 return margin;
125890 ** Store the union of cells p1 and p2 in p1.
125892 static void cellUnion(Rtree *pRtree, RtreeCell *p1, RtreeCell *p2){
125893 int ii;
125894 if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
125895 for(ii=0; ii<(pRtree->nDim*2); ii+=2){
125896 p1->aCoord[ii].f = MIN(p1->aCoord[ii].f, p2->aCoord[ii].f);
125897 p1->aCoord[ii+1].f = MAX(p1->aCoord[ii+1].f, p2->aCoord[ii+1].f);
125899 }else{
125900 for(ii=0; ii<(pRtree->nDim*2); ii+=2){
125901 p1->aCoord[ii].i = MIN(p1->aCoord[ii].i, p2->aCoord[ii].i);
125902 p1->aCoord[ii+1].i = MAX(p1->aCoord[ii+1].i, p2->aCoord[ii+1].i);
125908 ** Return true if the area covered by p2 is a subset of the area covered
125909 ** by p1. False otherwise.
125911 static int cellContains(Rtree *pRtree, RtreeCell *p1, RtreeCell *p2){
125912 int ii;
125913 int isInt = (pRtree->eCoordType==RTREE_COORD_INT32);
125914 for(ii=0; ii<(pRtree->nDim*2); ii+=2){
125915 RtreeCoord *a1 = &p1->aCoord[ii];
125916 RtreeCoord *a2 = &p2->aCoord[ii];
125917 if( (!isInt && (a2[0].f<a1[0].f || a2[1].f>a1[1].f))
125918 || ( isInt && (a2[0].i<a1[0].i || a2[1].i>a1[1].i))
125920 return 0;
125923 return 1;
125927 ** Return the amount cell p would grow by if it were unioned with pCell.
125929 static float cellGrowth(Rtree *pRtree, RtreeCell *p, RtreeCell *pCell){
125930 float area;
125931 RtreeCell cell;
125932 memcpy(&cell, p, sizeof(RtreeCell));
125933 area = cellArea(pRtree, &cell);
125934 cellUnion(pRtree, &cell, pCell);
125935 return (cellArea(pRtree, &cell)-area);
125938 #if VARIANT_RSTARTREE_CHOOSESUBTREE || VARIANT_RSTARTREE_SPLIT
125939 static float cellOverlap(
125940 Rtree *pRtree,
125941 RtreeCell *p,
125942 RtreeCell *aCell,
125943 int nCell,
125944 int iExclude
125946 int ii;
125947 float overlap = 0.0;
125948 for(ii=0; ii<nCell; ii++){
125949 #if VARIANT_RSTARTREE_CHOOSESUBTREE
125950 if( ii!=iExclude )
125951 #else
125952 assert( iExclude==-1 );
125953 UNUSED_PARAMETER(iExclude);
125954 #endif
125956 int jj;
125957 float o = 1.0;
125958 for(jj=0; jj<(pRtree->nDim*2); jj+=2){
125959 double x1;
125960 double x2;
125962 x1 = MAX(DCOORD(p->aCoord[jj]), DCOORD(aCell[ii].aCoord[jj]));
125963 x2 = MIN(DCOORD(p->aCoord[jj+1]), DCOORD(aCell[ii].aCoord[jj+1]));
125965 if( x2<x1 ){
125966 o = 0.0;
125967 break;
125968 }else{
125969 o = o * (x2-x1);
125972 overlap += o;
125975 return overlap;
125977 #endif
125979 #if VARIANT_RSTARTREE_CHOOSESUBTREE
125980 static float cellOverlapEnlargement(
125981 Rtree *pRtree,
125982 RtreeCell *p,
125983 RtreeCell *pInsert,
125984 RtreeCell *aCell,
125985 int nCell,
125986 int iExclude
125988 float before;
125989 float after;
125990 before = cellOverlap(pRtree, p, aCell, nCell, iExclude);
125991 cellUnion(pRtree, p, pInsert);
125992 after = cellOverlap(pRtree, p, aCell, nCell, iExclude);
125993 return after-before;
125995 #endif
125999 ** This function implements the ChooseLeaf algorithm from Gutman[84].
126000 ** ChooseSubTree in r*tree terminology.
126002 static int ChooseLeaf(
126003 Rtree *pRtree, /* Rtree table */
126004 RtreeCell *pCell, /* Cell to insert into rtree */
126005 int iHeight, /* Height of sub-tree rooted at pCell */
126006 RtreeNode **ppLeaf /* OUT: Selected leaf page */
126008 int rc;
126009 int ii;
126010 RtreeNode *pNode;
126011 rc = nodeAcquire(pRtree, 1, 0, &pNode);
126013 for(ii=0; rc==SQLITE_OK && ii<(pRtree->iDepth-iHeight); ii++){
126014 int iCell;
126015 sqlite3_int64 iBest;
126017 float fMinGrowth;
126018 float fMinArea;
126019 float fMinOverlap;
126021 int nCell = NCELL(pNode);
126022 RtreeCell cell;
126023 RtreeNode *pChild;
126025 RtreeCell *aCell = 0;
126027 #if VARIANT_RSTARTREE_CHOOSESUBTREE
126028 if( ii==(pRtree->iDepth-1) ){
126029 int jj;
126030 aCell = sqlite3_malloc(sizeof(RtreeCell)*nCell);
126031 if( !aCell ){
126032 rc = SQLITE_NOMEM;
126033 nodeRelease(pRtree, pNode);
126034 pNode = 0;
126035 continue;
126037 for(jj=0; jj<nCell; jj++){
126038 nodeGetCell(pRtree, pNode, jj, &aCell[jj]);
126041 #endif
126043 /* Select the child node which will be enlarged the least if pCell
126044 ** is inserted into it. Resolve ties by choosing the entry with
126045 ** the smallest area.
126047 for(iCell=0; iCell<nCell; iCell++){
126048 int bBest = 0;
126049 float growth;
126050 float area;
126051 float overlap = 0.0;
126052 nodeGetCell(pRtree, pNode, iCell, &cell);
126053 growth = cellGrowth(pRtree, &cell, pCell);
126054 area = cellArea(pRtree, &cell);
126056 #if VARIANT_RSTARTREE_CHOOSESUBTREE
126057 if( ii==(pRtree->iDepth-1) ){
126058 overlap = cellOverlapEnlargement(pRtree,&cell,pCell,aCell,nCell,iCell);
126060 if( (iCell==0)
126061 || (overlap<fMinOverlap)
126062 || (overlap==fMinOverlap && growth<fMinGrowth)
126063 || (overlap==fMinOverlap && growth==fMinGrowth && area<fMinArea)
126065 bBest = 1;
126067 #else
126068 if( iCell==0||growth<fMinGrowth||(growth==fMinGrowth && area<fMinArea) ){
126069 bBest = 1;
126071 #endif
126072 if( bBest ){
126073 fMinOverlap = overlap;
126074 fMinGrowth = growth;
126075 fMinArea = area;
126076 iBest = cell.iRowid;
126080 sqlite3_free(aCell);
126081 rc = nodeAcquire(pRtree, iBest, pNode, &pChild);
126082 nodeRelease(pRtree, pNode);
126083 pNode = pChild;
126086 *ppLeaf = pNode;
126087 return rc;
126091 ** A cell with the same content as pCell has just been inserted into
126092 ** the node pNode. This function updates the bounding box cells in
126093 ** all ancestor elements.
126095 static int AdjustTree(
126096 Rtree *pRtree, /* Rtree table */
126097 RtreeNode *pNode, /* Adjust ancestry of this node. */
126098 RtreeCell *pCell /* This cell was just inserted */
126100 RtreeNode *p = pNode;
126101 while( p->pParent ){
126102 RtreeNode *pParent = p->pParent;
126103 RtreeCell cell;
126104 int iCell;
126106 if( nodeParentIndex(pRtree, p, &iCell) ){
126107 return SQLITE_CORRUPT;
126110 nodeGetCell(pRtree, pParent, iCell, &cell);
126111 if( !cellContains(pRtree, &cell, pCell) ){
126112 cellUnion(pRtree, &cell, pCell);
126113 nodeOverwriteCell(pRtree, pParent, &cell, iCell);
126116 p = pParent;
126118 return SQLITE_OK;
126122 ** Write mapping (iRowid->iNode) to the <rtree>_rowid table.
126124 static int rowidWrite(Rtree *pRtree, sqlite3_int64 iRowid, sqlite3_int64 iNode){
126125 sqlite3_bind_int64(pRtree->pWriteRowid, 1, iRowid);
126126 sqlite3_bind_int64(pRtree->pWriteRowid, 2, iNode);
126127 sqlite3_step(pRtree->pWriteRowid);
126128 return sqlite3_reset(pRtree->pWriteRowid);
126132 ** Write mapping (iNode->iPar) to the <rtree>_parent table.
126134 static int parentWrite(Rtree *pRtree, sqlite3_int64 iNode, sqlite3_int64 iPar){
126135 sqlite3_bind_int64(pRtree->pWriteParent, 1, iNode);
126136 sqlite3_bind_int64(pRtree->pWriteParent, 2, iPar);
126137 sqlite3_step(pRtree->pWriteParent);
126138 return sqlite3_reset(pRtree->pWriteParent);
126141 static int rtreeInsertCell(Rtree *, RtreeNode *, RtreeCell *, int);
126143 #if VARIANT_GUTTMAN_LINEAR_SPLIT
126145 ** Implementation of the linear variant of the PickNext() function from
126146 ** Guttman[84].
126148 static RtreeCell *LinearPickNext(
126149 Rtree *pRtree,
126150 RtreeCell *aCell,
126151 int nCell,
126152 RtreeCell *pLeftBox,
126153 RtreeCell *pRightBox,
126154 int *aiUsed
126156 int ii;
126157 for(ii=0; aiUsed[ii]; ii++);
126158 aiUsed[ii] = 1;
126159 return &aCell[ii];
126163 ** Implementation of the linear variant of the PickSeeds() function from
126164 ** Guttman[84].
126166 static void LinearPickSeeds(
126167 Rtree *pRtree,
126168 RtreeCell *aCell,
126169 int nCell,
126170 int *piLeftSeed,
126171 int *piRightSeed
126173 int i;
126174 int iLeftSeed = 0;
126175 int iRightSeed = 1;
126176 float maxNormalInnerWidth = 0.0;
126178 /* Pick two "seed" cells from the array of cells. The algorithm used
126179 ** here is the LinearPickSeeds algorithm from Gutman[1984]. The
126180 ** indices of the two seed cells in the array are stored in local
126181 ** variables iLeftSeek and iRightSeed.
126183 for(i=0; i<pRtree->nDim; i++){
126184 float x1 = DCOORD(aCell[0].aCoord[i*2]);
126185 float x2 = DCOORD(aCell[0].aCoord[i*2+1]);
126186 float x3 = x1;
126187 float x4 = x2;
126188 int jj;
126190 int iCellLeft = 0;
126191 int iCellRight = 0;
126193 for(jj=1; jj<nCell; jj++){
126194 float left = DCOORD(aCell[jj].aCoord[i*2]);
126195 float right = DCOORD(aCell[jj].aCoord[i*2+1]);
126197 if( left<x1 ) x1 = left;
126198 if( right>x4 ) x4 = right;
126199 if( left>x3 ){
126200 x3 = left;
126201 iCellRight = jj;
126203 if( right<x2 ){
126204 x2 = right;
126205 iCellLeft = jj;
126209 if( x4!=x1 ){
126210 float normalwidth = (x3 - x2) / (x4 - x1);
126211 if( normalwidth>maxNormalInnerWidth ){
126212 iLeftSeed = iCellLeft;
126213 iRightSeed = iCellRight;
126218 *piLeftSeed = iLeftSeed;
126219 *piRightSeed = iRightSeed;
126221 #endif /* VARIANT_GUTTMAN_LINEAR_SPLIT */
126223 #if VARIANT_GUTTMAN_QUADRATIC_SPLIT
126225 ** Implementation of the quadratic variant of the PickNext() function from
126226 ** Guttman[84].
126228 static RtreeCell *QuadraticPickNext(
126229 Rtree *pRtree,
126230 RtreeCell *aCell,
126231 int nCell,
126232 RtreeCell *pLeftBox,
126233 RtreeCell *pRightBox,
126234 int *aiUsed
126236 #define FABS(a) ((a)<0.0?-1.0*(a):(a))
126238 int iSelect = -1;
126239 float fDiff;
126240 int ii;
126241 for(ii=0; ii<nCell; ii++){
126242 if( aiUsed[ii]==0 ){
126243 float left = cellGrowth(pRtree, pLeftBox, &aCell[ii]);
126244 float right = cellGrowth(pRtree, pLeftBox, &aCell[ii]);
126245 float diff = FABS(right-left);
126246 if( iSelect<0 || diff>fDiff ){
126247 fDiff = diff;
126248 iSelect = ii;
126252 aiUsed[iSelect] = 1;
126253 return &aCell[iSelect];
126257 ** Implementation of the quadratic variant of the PickSeeds() function from
126258 ** Guttman[84].
126260 static void QuadraticPickSeeds(
126261 Rtree *pRtree,
126262 RtreeCell *aCell,
126263 int nCell,
126264 int *piLeftSeed,
126265 int *piRightSeed
126267 int ii;
126268 int jj;
126270 int iLeftSeed = 0;
126271 int iRightSeed = 1;
126272 float fWaste = 0.0;
126274 for(ii=0; ii<nCell; ii++){
126275 for(jj=ii+1; jj<nCell; jj++){
126276 float right = cellArea(pRtree, &aCell[jj]);
126277 float growth = cellGrowth(pRtree, &aCell[ii], &aCell[jj]);
126278 float waste = growth - right;
126280 if( waste>fWaste ){
126281 iLeftSeed = ii;
126282 iRightSeed = jj;
126283 fWaste = waste;
126288 *piLeftSeed = iLeftSeed;
126289 *piRightSeed = iRightSeed;
126291 #endif /* VARIANT_GUTTMAN_QUADRATIC_SPLIT */
126294 ** Arguments aIdx, aDistance and aSpare all point to arrays of size
126295 ** nIdx. The aIdx array contains the set of integers from 0 to
126296 ** (nIdx-1) in no particular order. This function sorts the values
126297 ** in aIdx according to the indexed values in aDistance. For
126298 ** example, assuming the inputs:
126300 ** aIdx = { 0, 1, 2, 3 }
126301 ** aDistance = { 5.0, 2.0, 7.0, 6.0 }
126303 ** this function sets the aIdx array to contain:
126305 ** aIdx = { 0, 1, 2, 3 }
126307 ** The aSpare array is used as temporary working space by the
126308 ** sorting algorithm.
126310 static void SortByDistance(
126311 int *aIdx,
126312 int nIdx,
126313 float *aDistance,
126314 int *aSpare
126316 if( nIdx>1 ){
126317 int iLeft = 0;
126318 int iRight = 0;
126320 int nLeft = nIdx/2;
126321 int nRight = nIdx-nLeft;
126322 int *aLeft = aIdx;
126323 int *aRight = &aIdx[nLeft];
126325 SortByDistance(aLeft, nLeft, aDistance, aSpare);
126326 SortByDistance(aRight, nRight, aDistance, aSpare);
126328 memcpy(aSpare, aLeft, sizeof(int)*nLeft);
126329 aLeft = aSpare;
126331 while( iLeft<nLeft || iRight<nRight ){
126332 if( iLeft==nLeft ){
126333 aIdx[iLeft+iRight] = aRight[iRight];
126334 iRight++;
126335 }else if( iRight==nRight ){
126336 aIdx[iLeft+iRight] = aLeft[iLeft];
126337 iLeft++;
126338 }else{
126339 float fLeft = aDistance[aLeft[iLeft]];
126340 float fRight = aDistance[aRight[iRight]];
126341 if( fLeft<fRight ){
126342 aIdx[iLeft+iRight] = aLeft[iLeft];
126343 iLeft++;
126344 }else{
126345 aIdx[iLeft+iRight] = aRight[iRight];
126346 iRight++;
126351 #if 0
126352 /* Check that the sort worked */
126354 int jj;
126355 for(jj=1; jj<nIdx; jj++){
126356 float left = aDistance[aIdx[jj-1]];
126357 float right = aDistance[aIdx[jj]];
126358 assert( left<=right );
126361 #endif
126366 ** Arguments aIdx, aCell and aSpare all point to arrays of size
126367 ** nIdx. The aIdx array contains the set of integers from 0 to
126368 ** (nIdx-1) in no particular order. This function sorts the values
126369 ** in aIdx according to dimension iDim of the cells in aCell. The
126370 ** minimum value of dimension iDim is considered first, the
126371 ** maximum used to break ties.
126373 ** The aSpare array is used as temporary working space by the
126374 ** sorting algorithm.
126376 static void SortByDimension(
126377 Rtree *pRtree,
126378 int *aIdx,
126379 int nIdx,
126380 int iDim,
126381 RtreeCell *aCell,
126382 int *aSpare
126384 if( nIdx>1 ){
126386 int iLeft = 0;
126387 int iRight = 0;
126389 int nLeft = nIdx/2;
126390 int nRight = nIdx-nLeft;
126391 int *aLeft = aIdx;
126392 int *aRight = &aIdx[nLeft];
126394 SortByDimension(pRtree, aLeft, nLeft, iDim, aCell, aSpare);
126395 SortByDimension(pRtree, aRight, nRight, iDim, aCell, aSpare);
126397 memcpy(aSpare, aLeft, sizeof(int)*nLeft);
126398 aLeft = aSpare;
126399 while( iLeft<nLeft || iRight<nRight ){
126400 double xleft1 = DCOORD(aCell[aLeft[iLeft]].aCoord[iDim*2]);
126401 double xleft2 = DCOORD(aCell[aLeft[iLeft]].aCoord[iDim*2+1]);
126402 double xright1 = DCOORD(aCell[aRight[iRight]].aCoord[iDim*2]);
126403 double xright2 = DCOORD(aCell[aRight[iRight]].aCoord[iDim*2+1]);
126404 if( (iLeft!=nLeft) && ((iRight==nRight)
126405 || (xleft1<xright1)
126406 || (xleft1==xright1 && xleft2<xright2)
126408 aIdx[iLeft+iRight] = aLeft[iLeft];
126409 iLeft++;
126410 }else{
126411 aIdx[iLeft+iRight] = aRight[iRight];
126412 iRight++;
126416 #if 0
126417 /* Check that the sort worked */
126419 int jj;
126420 for(jj=1; jj<nIdx; jj++){
126421 float xleft1 = aCell[aIdx[jj-1]].aCoord[iDim*2];
126422 float xleft2 = aCell[aIdx[jj-1]].aCoord[iDim*2+1];
126423 float xright1 = aCell[aIdx[jj]].aCoord[iDim*2];
126424 float xright2 = aCell[aIdx[jj]].aCoord[iDim*2+1];
126425 assert( xleft1<=xright1 && (xleft1<xright1 || xleft2<=xright2) );
126428 #endif
126432 #if VARIANT_RSTARTREE_SPLIT
126434 ** Implementation of the R*-tree variant of SplitNode from Beckman[1990].
126436 static int splitNodeStartree(
126437 Rtree *pRtree,
126438 RtreeCell *aCell,
126439 int nCell,
126440 RtreeNode *pLeft,
126441 RtreeNode *pRight,
126442 RtreeCell *pBboxLeft,
126443 RtreeCell *pBboxRight
126445 int **aaSorted;
126446 int *aSpare;
126447 int ii;
126449 int iBestDim;
126450 int iBestSplit;
126451 float fBestMargin;
126453 int nByte = (pRtree->nDim+1)*(sizeof(int*)+nCell*sizeof(int));
126455 aaSorted = (int **)sqlite3_malloc(nByte);
126456 if( !aaSorted ){
126457 return SQLITE_NOMEM;
126460 aSpare = &((int *)&aaSorted[pRtree->nDim])[pRtree->nDim*nCell];
126461 memset(aaSorted, 0, nByte);
126462 for(ii=0; ii<pRtree->nDim; ii++){
126463 int jj;
126464 aaSorted[ii] = &((int *)&aaSorted[pRtree->nDim])[ii*nCell];
126465 for(jj=0; jj<nCell; jj++){
126466 aaSorted[ii][jj] = jj;
126468 SortByDimension(pRtree, aaSorted[ii], nCell, ii, aCell, aSpare);
126471 for(ii=0; ii<pRtree->nDim; ii++){
126472 float margin = 0.0;
126473 float fBestOverlap;
126474 float fBestArea;
126475 int iBestLeft;
126476 int nLeft;
126479 nLeft=RTREE_MINCELLS(pRtree);
126480 nLeft<=(nCell-RTREE_MINCELLS(pRtree));
126481 nLeft++
126483 RtreeCell left;
126484 RtreeCell right;
126485 int kk;
126486 float overlap;
126487 float area;
126489 memcpy(&left, &aCell[aaSorted[ii][0]], sizeof(RtreeCell));
126490 memcpy(&right, &aCell[aaSorted[ii][nCell-1]], sizeof(RtreeCell));
126491 for(kk=1; kk<(nCell-1); kk++){
126492 if( kk<nLeft ){
126493 cellUnion(pRtree, &left, &aCell[aaSorted[ii][kk]]);
126494 }else{
126495 cellUnion(pRtree, &right, &aCell[aaSorted[ii][kk]]);
126498 margin += cellMargin(pRtree, &left);
126499 margin += cellMargin(pRtree, &right);
126500 overlap = cellOverlap(pRtree, &left, &right, 1, -1);
126501 area = cellArea(pRtree, &left) + cellArea(pRtree, &right);
126502 if( (nLeft==RTREE_MINCELLS(pRtree))
126503 || (overlap<fBestOverlap)
126504 || (overlap==fBestOverlap && area<fBestArea)
126506 iBestLeft = nLeft;
126507 fBestOverlap = overlap;
126508 fBestArea = area;
126512 if( ii==0 || margin<fBestMargin ){
126513 iBestDim = ii;
126514 fBestMargin = margin;
126515 iBestSplit = iBestLeft;
126519 memcpy(pBboxLeft, &aCell[aaSorted[iBestDim][0]], sizeof(RtreeCell));
126520 memcpy(pBboxRight, &aCell[aaSorted[iBestDim][iBestSplit]], sizeof(RtreeCell));
126521 for(ii=0; ii<nCell; ii++){
126522 RtreeNode *pTarget = (ii<iBestSplit)?pLeft:pRight;
126523 RtreeCell *pBbox = (ii<iBestSplit)?pBboxLeft:pBboxRight;
126524 RtreeCell *pCell = &aCell[aaSorted[iBestDim][ii]];
126525 nodeInsertCell(pRtree, pTarget, pCell);
126526 cellUnion(pRtree, pBbox, pCell);
126529 sqlite3_free(aaSorted);
126530 return SQLITE_OK;
126532 #endif
126534 #if VARIANT_GUTTMAN_SPLIT
126536 ** Implementation of the regular R-tree SplitNode from Guttman[1984].
126538 static int splitNodeGuttman(
126539 Rtree *pRtree,
126540 RtreeCell *aCell,
126541 int nCell,
126542 RtreeNode *pLeft,
126543 RtreeNode *pRight,
126544 RtreeCell *pBboxLeft,
126545 RtreeCell *pBboxRight
126547 int iLeftSeed = 0;
126548 int iRightSeed = 1;
126549 int *aiUsed;
126550 int i;
126552 aiUsed = sqlite3_malloc(sizeof(int)*nCell);
126553 if( !aiUsed ){
126554 return SQLITE_NOMEM;
126556 memset(aiUsed, 0, sizeof(int)*nCell);
126558 PickSeeds(pRtree, aCell, nCell, &iLeftSeed, &iRightSeed);
126560 memcpy(pBboxLeft, &aCell[iLeftSeed], sizeof(RtreeCell));
126561 memcpy(pBboxRight, &aCell[iRightSeed], sizeof(RtreeCell));
126562 nodeInsertCell(pRtree, pLeft, &aCell[iLeftSeed]);
126563 nodeInsertCell(pRtree, pRight, &aCell[iRightSeed]);
126564 aiUsed[iLeftSeed] = 1;
126565 aiUsed[iRightSeed] = 1;
126567 for(i=nCell-2; i>0; i--){
126568 RtreeCell *pNext;
126569 pNext = PickNext(pRtree, aCell, nCell, pBboxLeft, pBboxRight, aiUsed);
126570 float diff =
126571 cellGrowth(pRtree, pBboxLeft, pNext) -
126572 cellGrowth(pRtree, pBboxRight, pNext)
126574 if( (RTREE_MINCELLS(pRtree)-NCELL(pRight)==i)
126575 || (diff>0.0 && (RTREE_MINCELLS(pRtree)-NCELL(pLeft)!=i))
126577 nodeInsertCell(pRtree, pRight, pNext);
126578 cellUnion(pRtree, pBboxRight, pNext);
126579 }else{
126580 nodeInsertCell(pRtree, pLeft, pNext);
126581 cellUnion(pRtree, pBboxLeft, pNext);
126585 sqlite3_free(aiUsed);
126586 return SQLITE_OK;
126588 #endif
126590 static int updateMapping(
126591 Rtree *pRtree,
126592 i64 iRowid,
126593 RtreeNode *pNode,
126594 int iHeight
126596 int (*xSetMapping)(Rtree *, sqlite3_int64, sqlite3_int64);
126597 xSetMapping = ((iHeight==0)?rowidWrite:parentWrite);
126598 if( iHeight>0 ){
126599 RtreeNode *pChild = nodeHashLookup(pRtree, iRowid);
126600 if( pChild ){
126601 nodeRelease(pRtree, pChild->pParent);
126602 nodeReference(pNode);
126603 pChild->pParent = pNode;
126606 return xSetMapping(pRtree, iRowid, pNode->iNode);
126609 static int SplitNode(
126610 Rtree *pRtree,
126611 RtreeNode *pNode,
126612 RtreeCell *pCell,
126613 int iHeight
126615 int i;
126616 int newCellIsRight = 0;
126618 int rc = SQLITE_OK;
126619 int nCell = NCELL(pNode);
126620 RtreeCell *aCell;
126621 int *aiUsed;
126623 RtreeNode *pLeft = 0;
126624 RtreeNode *pRight = 0;
126626 RtreeCell leftbbox;
126627 RtreeCell rightbbox;
126629 /* Allocate an array and populate it with a copy of pCell and
126630 ** all cells from node pLeft. Then zero the original node.
126632 aCell = sqlite3_malloc((sizeof(RtreeCell)+sizeof(int))*(nCell+1));
126633 if( !aCell ){
126634 rc = SQLITE_NOMEM;
126635 goto splitnode_out;
126637 aiUsed = (int *)&aCell[nCell+1];
126638 memset(aiUsed, 0, sizeof(int)*(nCell+1));
126639 for(i=0; i<nCell; i++){
126640 nodeGetCell(pRtree, pNode, i, &aCell[i]);
126642 nodeZero(pRtree, pNode);
126643 memcpy(&aCell[nCell], pCell, sizeof(RtreeCell));
126644 nCell++;
126646 if( pNode->iNode==1 ){
126647 pRight = nodeNew(pRtree, pNode);
126648 pLeft = nodeNew(pRtree, pNode);
126649 pRtree->iDepth++;
126650 pNode->isDirty = 1;
126651 writeInt16(pNode->zData, pRtree->iDepth);
126652 }else{
126653 pLeft = pNode;
126654 pRight = nodeNew(pRtree, pLeft->pParent);
126655 nodeReference(pLeft);
126658 if( !pLeft || !pRight ){
126659 rc = SQLITE_NOMEM;
126660 goto splitnode_out;
126663 memset(pLeft->zData, 0, pRtree->iNodeSize);
126664 memset(pRight->zData, 0, pRtree->iNodeSize);
126666 rc = AssignCells(pRtree, aCell, nCell, pLeft, pRight, &leftbbox, &rightbbox);
126667 if( rc!=SQLITE_OK ){
126668 goto splitnode_out;
126671 /* Ensure both child nodes have node numbers assigned to them by calling
126672 ** nodeWrite(). Node pRight always needs a node number, as it was created
126673 ** by nodeNew() above. But node pLeft sometimes already has a node number.
126674 ** In this case avoid the all to nodeWrite().
126676 if( SQLITE_OK!=(rc = nodeWrite(pRtree, pRight))
126677 || (0==pLeft->iNode && SQLITE_OK!=(rc = nodeWrite(pRtree, pLeft)))
126679 goto splitnode_out;
126682 rightbbox.iRowid = pRight->iNode;
126683 leftbbox.iRowid = pLeft->iNode;
126685 if( pNode->iNode==1 ){
126686 rc = rtreeInsertCell(pRtree, pLeft->pParent, &leftbbox, iHeight+1);
126687 if( rc!=SQLITE_OK ){
126688 goto splitnode_out;
126690 }else{
126691 RtreeNode *pParent = pLeft->pParent;
126692 int iCell;
126693 rc = nodeParentIndex(pRtree, pLeft, &iCell);
126694 if( rc==SQLITE_OK ){
126695 nodeOverwriteCell(pRtree, pParent, &leftbbox, iCell);
126696 rc = AdjustTree(pRtree, pParent, &leftbbox);
126698 if( rc!=SQLITE_OK ){
126699 goto splitnode_out;
126702 if( (rc = rtreeInsertCell(pRtree, pRight->pParent, &rightbbox, iHeight+1)) ){
126703 goto splitnode_out;
126706 for(i=0; i<NCELL(pRight); i++){
126707 i64 iRowid = nodeGetRowid(pRtree, pRight, i);
126708 rc = updateMapping(pRtree, iRowid, pRight, iHeight);
126709 if( iRowid==pCell->iRowid ){
126710 newCellIsRight = 1;
126712 if( rc!=SQLITE_OK ){
126713 goto splitnode_out;
126716 if( pNode->iNode==1 ){
126717 for(i=0; i<NCELL(pLeft); i++){
126718 i64 iRowid = nodeGetRowid(pRtree, pLeft, i);
126719 rc = updateMapping(pRtree, iRowid, pLeft, iHeight);
126720 if( rc!=SQLITE_OK ){
126721 goto splitnode_out;
126724 }else if( newCellIsRight==0 ){
126725 rc = updateMapping(pRtree, pCell->iRowid, pLeft, iHeight);
126728 if( rc==SQLITE_OK ){
126729 rc = nodeRelease(pRtree, pRight);
126730 pRight = 0;
126732 if( rc==SQLITE_OK ){
126733 rc = nodeRelease(pRtree, pLeft);
126734 pLeft = 0;
126737 splitnode_out:
126738 nodeRelease(pRtree, pRight);
126739 nodeRelease(pRtree, pLeft);
126740 sqlite3_free(aCell);
126741 return rc;
126745 ** If node pLeaf is not the root of the r-tree and its pParent pointer is
126746 ** still NULL, load all ancestor nodes of pLeaf into memory and populate
126747 ** the pLeaf->pParent chain all the way up to the root node.
126749 ** This operation is required when a row is deleted (or updated - an update
126750 ** is implemented as a delete followed by an insert). SQLite provides the
126751 ** rowid of the row to delete, which can be used to find the leaf on which
126752 ** the entry resides (argument pLeaf). Once the leaf is located, this
126753 ** function is called to determine its ancestry.
126755 static int fixLeafParent(Rtree *pRtree, RtreeNode *pLeaf){
126756 int rc = SQLITE_OK;
126757 RtreeNode *pChild = pLeaf;
126758 while( rc==SQLITE_OK && pChild->iNode!=1 && pChild->pParent==0 ){
126759 int rc2 = SQLITE_OK; /* sqlite3_reset() return code */
126760 sqlite3_bind_int64(pRtree->pReadParent, 1, pChild->iNode);
126761 rc = sqlite3_step(pRtree->pReadParent);
126762 if( rc==SQLITE_ROW ){
126763 RtreeNode *pTest; /* Used to test for reference loops */
126764 i64 iNode; /* Node number of parent node */
126766 /* Before setting pChild->pParent, test that we are not creating a
126767 ** loop of references (as we would if, say, pChild==pParent). We don't
126768 ** want to do this as it leads to a memory leak when trying to delete
126769 ** the referenced counted node structures.
126771 iNode = sqlite3_column_int64(pRtree->pReadParent, 0);
126772 for(pTest=pLeaf; pTest && pTest->iNode!=iNode; pTest=pTest->pParent);
126773 if( !pTest ){
126774 rc2 = nodeAcquire(pRtree, iNode, 0, &pChild->pParent);
126777 rc = sqlite3_reset(pRtree->pReadParent);
126778 if( rc==SQLITE_OK ) rc = rc2;
126779 if( rc==SQLITE_OK && !pChild->pParent ) rc = SQLITE_CORRUPT;
126780 pChild = pChild->pParent;
126782 return rc;
126785 static int deleteCell(Rtree *, RtreeNode *, int, int);
126787 static int removeNode(Rtree *pRtree, RtreeNode *pNode, int iHeight){
126788 int rc;
126789 int rc2;
126790 RtreeNode *pParent;
126791 int iCell;
126793 assert( pNode->nRef==1 );
126795 /* Remove the entry in the parent cell. */
126796 rc = nodeParentIndex(pRtree, pNode, &iCell);
126797 if( rc==SQLITE_OK ){
126798 pParent = pNode->pParent;
126799 pNode->pParent = 0;
126800 rc = deleteCell(pRtree, pParent, iCell, iHeight+1);
126802 rc2 = nodeRelease(pRtree, pParent);
126803 if( rc==SQLITE_OK ){
126804 rc = rc2;
126806 if( rc!=SQLITE_OK ){
126807 return rc;
126810 /* Remove the xxx_node entry. */
126811 sqlite3_bind_int64(pRtree->pDeleteNode, 1, pNode->iNode);
126812 sqlite3_step(pRtree->pDeleteNode);
126813 if( SQLITE_OK!=(rc = sqlite3_reset(pRtree->pDeleteNode)) ){
126814 return rc;
126817 /* Remove the xxx_parent entry. */
126818 sqlite3_bind_int64(pRtree->pDeleteParent, 1, pNode->iNode);
126819 sqlite3_step(pRtree->pDeleteParent);
126820 if( SQLITE_OK!=(rc = sqlite3_reset(pRtree->pDeleteParent)) ){
126821 return rc;
126824 /* Remove the node from the in-memory hash table and link it into
126825 ** the Rtree.pDeleted list. Its contents will be re-inserted later on.
126827 nodeHashDelete(pRtree, pNode);
126828 pNode->iNode = iHeight;
126829 pNode->pNext = pRtree->pDeleted;
126830 pNode->nRef++;
126831 pRtree->pDeleted = pNode;
126833 return SQLITE_OK;
126836 static int fixBoundingBox(Rtree *pRtree, RtreeNode *pNode){
126837 RtreeNode *pParent = pNode->pParent;
126838 int rc = SQLITE_OK;
126839 if( pParent ){
126840 int ii;
126841 int nCell = NCELL(pNode);
126842 RtreeCell box; /* Bounding box for pNode */
126843 nodeGetCell(pRtree, pNode, 0, &box);
126844 for(ii=1; ii<nCell; ii++){
126845 RtreeCell cell;
126846 nodeGetCell(pRtree, pNode, ii, &cell);
126847 cellUnion(pRtree, &box, &cell);
126849 box.iRowid = pNode->iNode;
126850 rc = nodeParentIndex(pRtree, pNode, &ii);
126851 if( rc==SQLITE_OK ){
126852 nodeOverwriteCell(pRtree, pParent, &box, ii);
126853 rc = fixBoundingBox(pRtree, pParent);
126856 return rc;
126860 ** Delete the cell at index iCell of node pNode. After removing the
126861 ** cell, adjust the r-tree data structure if required.
126863 static int deleteCell(Rtree *pRtree, RtreeNode *pNode, int iCell, int iHeight){
126864 RtreeNode *pParent;
126865 int rc;
126867 if( SQLITE_OK!=(rc = fixLeafParent(pRtree, pNode)) ){
126868 return rc;
126871 /* Remove the cell from the node. This call just moves bytes around
126872 ** the in-memory node image, so it cannot fail.
126874 nodeDeleteCell(pRtree, pNode, iCell);
126876 /* If the node is not the tree root and now has less than the minimum
126877 ** number of cells, remove it from the tree. Otherwise, update the
126878 ** cell in the parent node so that it tightly contains the updated
126879 ** node.
126881 pParent = pNode->pParent;
126882 assert( pParent || pNode->iNode==1 );
126883 if( pParent ){
126884 if( NCELL(pNode)<RTREE_MINCELLS(pRtree) ){
126885 rc = removeNode(pRtree, pNode, iHeight);
126886 }else{
126887 rc = fixBoundingBox(pRtree, pNode);
126891 return rc;
126894 static int Reinsert(
126895 Rtree *pRtree,
126896 RtreeNode *pNode,
126897 RtreeCell *pCell,
126898 int iHeight
126900 int *aOrder;
126901 int *aSpare;
126902 RtreeCell *aCell;
126903 float *aDistance;
126904 int nCell;
126905 float aCenterCoord[RTREE_MAX_DIMENSIONS];
126906 int iDim;
126907 int ii;
126908 int rc = SQLITE_OK;
126910 memset(aCenterCoord, 0, sizeof(float)*RTREE_MAX_DIMENSIONS);
126912 nCell = NCELL(pNode)+1;
126914 /* Allocate the buffers used by this operation. The allocation is
126915 ** relinquished before this function returns.
126917 aCell = (RtreeCell *)sqlite3_malloc(nCell * (
126918 sizeof(RtreeCell) + /* aCell array */
126919 sizeof(int) + /* aOrder array */
126920 sizeof(int) + /* aSpare array */
126921 sizeof(float) /* aDistance array */
126923 if( !aCell ){
126924 return SQLITE_NOMEM;
126926 aOrder = (int *)&aCell[nCell];
126927 aSpare = (int *)&aOrder[nCell];
126928 aDistance = (float *)&aSpare[nCell];
126930 for(ii=0; ii<nCell; ii++){
126931 if( ii==(nCell-1) ){
126932 memcpy(&aCell[ii], pCell, sizeof(RtreeCell));
126933 }else{
126934 nodeGetCell(pRtree, pNode, ii, &aCell[ii]);
126936 aOrder[ii] = ii;
126937 for(iDim=0; iDim<pRtree->nDim; iDim++){
126938 aCenterCoord[iDim] += DCOORD(aCell[ii].aCoord[iDim*2]);
126939 aCenterCoord[iDim] += DCOORD(aCell[ii].aCoord[iDim*2+1]);
126942 for(iDim=0; iDim<pRtree->nDim; iDim++){
126943 aCenterCoord[iDim] = aCenterCoord[iDim]/((float)nCell*2.0);
126946 for(ii=0; ii<nCell; ii++){
126947 aDistance[ii] = 0.0;
126948 for(iDim=0; iDim<pRtree->nDim; iDim++){
126949 float coord = DCOORD(aCell[ii].aCoord[iDim*2+1]) -
126950 DCOORD(aCell[ii].aCoord[iDim*2]);
126951 aDistance[ii] += (coord-aCenterCoord[iDim])*(coord-aCenterCoord[iDim]);
126955 SortByDistance(aOrder, nCell, aDistance, aSpare);
126956 nodeZero(pRtree, pNode);
126958 for(ii=0; rc==SQLITE_OK && ii<(nCell-(RTREE_MINCELLS(pRtree)+1)); ii++){
126959 RtreeCell *p = &aCell[aOrder[ii]];
126960 nodeInsertCell(pRtree, pNode, p);
126961 if( p->iRowid==pCell->iRowid ){
126962 if( iHeight==0 ){
126963 rc = rowidWrite(pRtree, p->iRowid, pNode->iNode);
126964 }else{
126965 rc = parentWrite(pRtree, p->iRowid, pNode->iNode);
126969 if( rc==SQLITE_OK ){
126970 rc = fixBoundingBox(pRtree, pNode);
126972 for(; rc==SQLITE_OK && ii<nCell; ii++){
126973 /* Find a node to store this cell in. pNode->iNode currently contains
126974 ** the height of the sub-tree headed by the cell.
126976 RtreeNode *pInsert;
126977 RtreeCell *p = &aCell[aOrder[ii]];
126978 rc = ChooseLeaf(pRtree, p, iHeight, &pInsert);
126979 if( rc==SQLITE_OK ){
126980 int rc2;
126981 rc = rtreeInsertCell(pRtree, pInsert, p, iHeight);
126982 rc2 = nodeRelease(pRtree, pInsert);
126983 if( rc==SQLITE_OK ){
126984 rc = rc2;
126989 sqlite3_free(aCell);
126990 return rc;
126994 ** Insert cell pCell into node pNode. Node pNode is the head of a
126995 ** subtree iHeight high (leaf nodes have iHeight==0).
126997 static int rtreeInsertCell(
126998 Rtree *pRtree,
126999 RtreeNode *pNode,
127000 RtreeCell *pCell,
127001 int iHeight
127003 int rc = SQLITE_OK;
127004 if( iHeight>0 ){
127005 RtreeNode *pChild = nodeHashLookup(pRtree, pCell->iRowid);
127006 if( pChild ){
127007 nodeRelease(pRtree, pChild->pParent);
127008 nodeReference(pNode);
127009 pChild->pParent = pNode;
127012 if( nodeInsertCell(pRtree, pNode, pCell) ){
127013 #if VARIANT_RSTARTREE_REINSERT
127014 if( iHeight<=pRtree->iReinsertHeight || pNode->iNode==1){
127015 rc = SplitNode(pRtree, pNode, pCell, iHeight);
127016 }else{
127017 pRtree->iReinsertHeight = iHeight;
127018 rc = Reinsert(pRtree, pNode, pCell, iHeight);
127020 #else
127021 rc = SplitNode(pRtree, pNode, pCell, iHeight);
127022 #endif
127023 }else{
127024 rc = AdjustTree(pRtree, pNode, pCell);
127025 if( rc==SQLITE_OK ){
127026 if( iHeight==0 ){
127027 rc = rowidWrite(pRtree, pCell->iRowid, pNode->iNode);
127028 }else{
127029 rc = parentWrite(pRtree, pCell->iRowid, pNode->iNode);
127033 return rc;
127036 static int reinsertNodeContent(Rtree *pRtree, RtreeNode *pNode){
127037 int ii;
127038 int rc = SQLITE_OK;
127039 int nCell = NCELL(pNode);
127041 for(ii=0; rc==SQLITE_OK && ii<nCell; ii++){
127042 RtreeNode *pInsert;
127043 RtreeCell cell;
127044 nodeGetCell(pRtree, pNode, ii, &cell);
127046 /* Find a node to store this cell in. pNode->iNode currently contains
127047 ** the height of the sub-tree headed by the cell.
127049 rc = ChooseLeaf(pRtree, &cell, pNode->iNode, &pInsert);
127050 if( rc==SQLITE_OK ){
127051 int rc2;
127052 rc = rtreeInsertCell(pRtree, pInsert, &cell, pNode->iNode);
127053 rc2 = nodeRelease(pRtree, pInsert);
127054 if( rc==SQLITE_OK ){
127055 rc = rc2;
127059 return rc;
127063 ** Select a currently unused rowid for a new r-tree record.
127065 static int newRowid(Rtree *pRtree, i64 *piRowid){
127066 int rc;
127067 sqlite3_bind_null(pRtree->pWriteRowid, 1);
127068 sqlite3_bind_null(pRtree->pWriteRowid, 2);
127069 sqlite3_step(pRtree->pWriteRowid);
127070 rc = sqlite3_reset(pRtree->pWriteRowid);
127071 *piRowid = sqlite3_last_insert_rowid(pRtree->db);
127072 return rc;
127076 ** The xUpdate method for rtree module virtual tables.
127078 static int rtreeUpdate(
127079 sqlite3_vtab *pVtab,
127080 int nData,
127081 sqlite3_value **azData,
127082 sqlite_int64 *pRowid
127084 Rtree *pRtree = (Rtree *)pVtab;
127085 int rc = SQLITE_OK;
127087 rtreeReference(pRtree);
127089 assert(nData>=1);
127091 /* If azData[0] is not an SQL NULL value, it is the rowid of a
127092 ** record to delete from the r-tree table. The following block does
127093 ** just that.
127095 if( sqlite3_value_type(azData[0])!=SQLITE_NULL ){
127096 i64 iDelete; /* The rowid to delete */
127097 RtreeNode *pLeaf; /* Leaf node containing record iDelete */
127098 int iCell; /* Index of iDelete cell in pLeaf */
127099 RtreeNode *pRoot;
127101 /* Obtain a reference to the root node to initialise Rtree.iDepth */
127102 rc = nodeAcquire(pRtree, 1, 0, &pRoot);
127104 /* Obtain a reference to the leaf node that contains the entry
127105 ** about to be deleted.
127107 if( rc==SQLITE_OK ){
127108 iDelete = sqlite3_value_int64(azData[0]);
127109 rc = findLeafNode(pRtree, iDelete, &pLeaf);
127112 /* Delete the cell in question from the leaf node. */
127113 if( rc==SQLITE_OK ){
127114 int rc2;
127115 rc = nodeRowidIndex(pRtree, pLeaf, iDelete, &iCell);
127116 if( rc==SQLITE_OK ){
127117 rc = deleteCell(pRtree, pLeaf, iCell, 0);
127119 rc2 = nodeRelease(pRtree, pLeaf);
127120 if( rc==SQLITE_OK ){
127121 rc = rc2;
127125 /* Delete the corresponding entry in the <rtree>_rowid table. */
127126 if( rc==SQLITE_OK ){
127127 sqlite3_bind_int64(pRtree->pDeleteRowid, 1, iDelete);
127128 sqlite3_step(pRtree->pDeleteRowid);
127129 rc = sqlite3_reset(pRtree->pDeleteRowid);
127132 /* Check if the root node now has exactly one child. If so, remove
127133 ** it, schedule the contents of the child for reinsertion and
127134 ** reduce the tree height by one.
127136 ** This is equivalent to copying the contents of the child into
127137 ** the root node (the operation that Gutman's paper says to perform
127138 ** in this scenario).
127140 if( rc==SQLITE_OK && pRtree->iDepth>0 && NCELL(pRoot)==1 ){
127141 int rc2;
127142 RtreeNode *pChild;
127143 i64 iChild = nodeGetRowid(pRtree, pRoot, 0);
127144 rc = nodeAcquire(pRtree, iChild, pRoot, &pChild);
127145 if( rc==SQLITE_OK ){
127146 rc = removeNode(pRtree, pChild, pRtree->iDepth-1);
127148 rc2 = nodeRelease(pRtree, pChild);
127149 if( rc==SQLITE_OK ) rc = rc2;
127150 if( rc==SQLITE_OK ){
127151 pRtree->iDepth--;
127152 writeInt16(pRoot->zData, pRtree->iDepth);
127153 pRoot->isDirty = 1;
127157 /* Re-insert the contents of any underfull nodes removed from the tree. */
127158 for(pLeaf=pRtree->pDeleted; pLeaf; pLeaf=pRtree->pDeleted){
127159 if( rc==SQLITE_OK ){
127160 rc = reinsertNodeContent(pRtree, pLeaf);
127162 pRtree->pDeleted = pLeaf->pNext;
127163 sqlite3_free(pLeaf);
127166 /* Release the reference to the root node. */
127167 if( rc==SQLITE_OK ){
127168 rc = nodeRelease(pRtree, pRoot);
127169 }else{
127170 nodeRelease(pRtree, pRoot);
127174 /* If the azData[] array contains more than one element, elements
127175 ** (azData[2]..azData[argc-1]) contain a new record to insert into
127176 ** the r-tree structure.
127178 if( rc==SQLITE_OK && nData>1 ){
127179 /* Insert a new record into the r-tree */
127180 RtreeCell cell;
127181 int ii;
127182 RtreeNode *pLeaf;
127184 /* Populate the cell.aCoord[] array. The first coordinate is azData[3]. */
127185 assert( nData==(pRtree->nDim*2 + 3) );
127186 if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
127187 for(ii=0; ii<(pRtree->nDim*2); ii+=2){
127188 cell.aCoord[ii].f = (float)sqlite3_value_double(azData[ii+3]);
127189 cell.aCoord[ii+1].f = (float)sqlite3_value_double(azData[ii+4]);
127190 if( cell.aCoord[ii].f>cell.aCoord[ii+1].f ){
127191 rc = SQLITE_CONSTRAINT;
127192 goto constraint;
127195 }else{
127196 for(ii=0; ii<(pRtree->nDim*2); ii+=2){
127197 cell.aCoord[ii].i = sqlite3_value_int(azData[ii+3]);
127198 cell.aCoord[ii+1].i = sqlite3_value_int(azData[ii+4]);
127199 if( cell.aCoord[ii].i>cell.aCoord[ii+1].i ){
127200 rc = SQLITE_CONSTRAINT;
127201 goto constraint;
127206 /* Figure out the rowid of the new row. */
127207 if( sqlite3_value_type(azData[2])==SQLITE_NULL ){
127208 rc = newRowid(pRtree, &cell.iRowid);
127209 }else{
127210 cell.iRowid = sqlite3_value_int64(azData[2]);
127211 sqlite3_bind_int64(pRtree->pReadRowid, 1, cell.iRowid);
127212 if( SQLITE_ROW==sqlite3_step(pRtree->pReadRowid) ){
127213 sqlite3_reset(pRtree->pReadRowid);
127214 rc = SQLITE_CONSTRAINT;
127215 goto constraint;
127217 rc = sqlite3_reset(pRtree->pReadRowid);
127219 *pRowid = cell.iRowid;
127221 if( rc==SQLITE_OK ){
127222 rc = ChooseLeaf(pRtree, &cell, 0, &pLeaf);
127224 if( rc==SQLITE_OK ){
127225 int rc2;
127226 pRtree->iReinsertHeight = -1;
127227 rc = rtreeInsertCell(pRtree, pLeaf, &cell, 0);
127228 rc2 = nodeRelease(pRtree, pLeaf);
127229 if( rc==SQLITE_OK ){
127230 rc = rc2;
127235 constraint:
127236 rtreeRelease(pRtree);
127237 return rc;
127241 ** The xRename method for rtree module virtual tables.
127243 static int rtreeRename(sqlite3_vtab *pVtab, const char *zNewName){
127244 Rtree *pRtree = (Rtree *)pVtab;
127245 int rc = SQLITE_NOMEM;
127246 char *zSql = sqlite3_mprintf(
127247 "ALTER TABLE %Q.'%q_node' RENAME TO \"%w_node\";"
127248 "ALTER TABLE %Q.'%q_parent' RENAME TO \"%w_parent\";"
127249 "ALTER TABLE %Q.'%q_rowid' RENAME TO \"%w_rowid\";"
127250 , pRtree->zDb, pRtree->zName, zNewName
127251 , pRtree->zDb, pRtree->zName, zNewName
127252 , pRtree->zDb, pRtree->zName, zNewName
127254 if( zSql ){
127255 rc = sqlite3_exec(pRtree->db, zSql, 0, 0, 0);
127256 sqlite3_free(zSql);
127258 return rc;
127261 static sqlite3_module rtreeModule = {
127262 0, /* iVersion */
127263 rtreeCreate, /* xCreate - create a table */
127264 rtreeConnect, /* xConnect - connect to an existing table */
127265 rtreeBestIndex, /* xBestIndex - Determine search strategy */
127266 rtreeDisconnect, /* xDisconnect - Disconnect from a table */
127267 rtreeDestroy, /* xDestroy - Drop a table */
127268 rtreeOpen, /* xOpen - open a cursor */
127269 rtreeClose, /* xClose - close a cursor */
127270 rtreeFilter, /* xFilter - configure scan constraints */
127271 rtreeNext, /* xNext - advance a cursor */
127272 rtreeEof, /* xEof */
127273 rtreeColumn, /* xColumn - read data */
127274 rtreeRowid, /* xRowid - read data */
127275 rtreeUpdate, /* xUpdate - write data */
127276 0, /* xBegin - begin transaction */
127277 0, /* xSync - sync transaction */
127278 0, /* xCommit - commit transaction */
127279 0, /* xRollback - rollback transaction */
127280 0, /* xFindFunction - function overloading */
127281 rtreeRename /* xRename - rename the table */
127284 static int rtreeSqlInit(
127285 Rtree *pRtree,
127286 sqlite3 *db,
127287 const char *zDb,
127288 const char *zPrefix,
127289 int isCreate
127291 int rc = SQLITE_OK;
127293 #define N_STATEMENT 9
127294 static const char *azSql[N_STATEMENT] = {
127295 /* Read and write the xxx_node table */
127296 "SELECT data FROM '%q'.'%q_node' WHERE nodeno = :1",
127297 "INSERT OR REPLACE INTO '%q'.'%q_node' VALUES(:1, :2)",
127298 "DELETE FROM '%q'.'%q_node' WHERE nodeno = :1",
127300 /* Read and write the xxx_rowid table */
127301 "SELECT nodeno FROM '%q'.'%q_rowid' WHERE rowid = :1",
127302 "INSERT OR REPLACE INTO '%q'.'%q_rowid' VALUES(:1, :2)",
127303 "DELETE FROM '%q'.'%q_rowid' WHERE rowid = :1",
127305 /* Read and write the xxx_parent table */
127306 "SELECT parentnode FROM '%q'.'%q_parent' WHERE nodeno = :1",
127307 "INSERT OR REPLACE INTO '%q'.'%q_parent' VALUES(:1, :2)",
127308 "DELETE FROM '%q'.'%q_parent' WHERE nodeno = :1"
127310 sqlite3_stmt **appStmt[N_STATEMENT];
127311 int i;
127313 pRtree->db = db;
127315 if( isCreate ){
127316 char *zCreate = sqlite3_mprintf(
127317 "CREATE TABLE \"%w\".\"%w_node\"(nodeno INTEGER PRIMARY KEY, data BLOB);"
127318 "CREATE TABLE \"%w\".\"%w_rowid\"(rowid INTEGER PRIMARY KEY, nodeno INTEGER);"
127319 "CREATE TABLE \"%w\".\"%w_parent\"(nodeno INTEGER PRIMARY KEY, parentnode INTEGER);"
127320 "INSERT INTO '%q'.'%q_node' VALUES(1, zeroblob(%d))",
127321 zDb, zPrefix, zDb, zPrefix, zDb, zPrefix, zDb, zPrefix, pRtree->iNodeSize
127323 if( !zCreate ){
127324 return SQLITE_NOMEM;
127326 rc = sqlite3_exec(db, zCreate, 0, 0, 0);
127327 sqlite3_free(zCreate);
127328 if( rc!=SQLITE_OK ){
127329 return rc;
127333 appStmt[0] = &pRtree->pReadNode;
127334 appStmt[1] = &pRtree->pWriteNode;
127335 appStmt[2] = &pRtree->pDeleteNode;
127336 appStmt[3] = &pRtree->pReadRowid;
127337 appStmt[4] = &pRtree->pWriteRowid;
127338 appStmt[5] = &pRtree->pDeleteRowid;
127339 appStmt[6] = &pRtree->pReadParent;
127340 appStmt[7] = &pRtree->pWriteParent;
127341 appStmt[8] = &pRtree->pDeleteParent;
127343 for(i=0; i<N_STATEMENT && rc==SQLITE_OK; i++){
127344 char *zSql = sqlite3_mprintf(azSql[i], zDb, zPrefix);
127345 if( zSql ){
127346 rc = sqlite3_prepare_v2(db, zSql, -1, appStmt[i], 0);
127347 }else{
127348 rc = SQLITE_NOMEM;
127350 sqlite3_free(zSql);
127353 return rc;
127357 ** The second argument to this function contains the text of an SQL statement
127358 ** that returns a single integer value. The statement is compiled and executed
127359 ** using database connection db. If successful, the integer value returned
127360 ** is written to *piVal and SQLITE_OK returned. Otherwise, an SQLite error
127361 ** code is returned and the value of *piVal after returning is not defined.
127363 static int getIntFromStmt(sqlite3 *db, const char *zSql, int *piVal){
127364 int rc = SQLITE_NOMEM;
127365 if( zSql ){
127366 sqlite3_stmt *pStmt = 0;
127367 rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
127368 if( rc==SQLITE_OK ){
127369 if( SQLITE_ROW==sqlite3_step(pStmt) ){
127370 *piVal = sqlite3_column_int(pStmt, 0);
127372 rc = sqlite3_finalize(pStmt);
127375 return rc;
127379 ** This function is called from within the xConnect() or xCreate() method to
127380 ** determine the node-size used by the rtree table being created or connected
127381 ** to. If successful, pRtree->iNodeSize is populated and SQLITE_OK returned.
127382 ** Otherwise, an SQLite error code is returned.
127384 ** If this function is being called as part of an xConnect(), then the rtree
127385 ** table already exists. In this case the node-size is determined by inspecting
127386 ** the root node of the tree.
127388 ** Otherwise, for an xCreate(), use 64 bytes less than the database page-size.
127389 ** This ensures that each node is stored on a single database page. If the
127390 ** database page-size is so large that more than RTREE_MAXCELLS entries
127391 ** would fit in a single node, use a smaller node-size.
127393 static int getNodeSize(
127394 sqlite3 *db, /* Database handle */
127395 Rtree *pRtree, /* Rtree handle */
127396 int isCreate /* True for xCreate, false for xConnect */
127398 int rc;
127399 char *zSql;
127400 if( isCreate ){
127401 int iPageSize;
127402 zSql = sqlite3_mprintf("PRAGMA %Q.page_size", pRtree->zDb);
127403 rc = getIntFromStmt(db, zSql, &iPageSize);
127404 if( rc==SQLITE_OK ){
127405 pRtree->iNodeSize = iPageSize-64;
127406 if( (4+pRtree->nBytesPerCell*RTREE_MAXCELLS)<pRtree->iNodeSize ){
127407 pRtree->iNodeSize = 4+pRtree->nBytesPerCell*RTREE_MAXCELLS;
127410 }else{
127411 zSql = sqlite3_mprintf(
127412 "SELECT length(data) FROM '%q'.'%q_node' WHERE nodeno = 1",
127413 pRtree->zDb, pRtree->zName
127415 rc = getIntFromStmt(db, zSql, &pRtree->iNodeSize);
127418 sqlite3_free(zSql);
127419 return rc;
127423 ** This function is the implementation of both the xConnect and xCreate
127424 ** methods of the r-tree virtual table.
127426 ** argv[0] -> module name
127427 ** argv[1] -> database name
127428 ** argv[2] -> table name
127429 ** argv[...] -> column names...
127431 static int rtreeInit(
127432 sqlite3 *db, /* Database connection */
127433 void *pAux, /* One of the RTREE_COORD_* constants */
127434 int argc, const char *const*argv, /* Parameters to CREATE TABLE statement */
127435 sqlite3_vtab **ppVtab, /* OUT: New virtual table */
127436 char **pzErr, /* OUT: Error message, if any */
127437 int isCreate /* True for xCreate, false for xConnect */
127439 int rc = SQLITE_OK;
127440 Rtree *pRtree;
127441 int nDb; /* Length of string argv[1] */
127442 int nName; /* Length of string argv[2] */
127443 int eCoordType = (pAux ? RTREE_COORD_INT32 : RTREE_COORD_REAL32);
127445 const char *aErrMsg[] = {
127446 0, /* 0 */
127447 "Wrong number of columns for an rtree table", /* 1 */
127448 "Too few columns for an rtree table", /* 2 */
127449 "Too many columns for an rtree table" /* 3 */
127452 int iErr = (argc<6) ? 2 : argc>(RTREE_MAX_DIMENSIONS*2+4) ? 3 : argc%2;
127453 if( aErrMsg[iErr] ){
127454 *pzErr = sqlite3_mprintf("%s", aErrMsg[iErr]);
127455 return SQLITE_ERROR;
127458 /* Allocate the sqlite3_vtab structure */
127459 nDb = strlen(argv[1]);
127460 nName = strlen(argv[2]);
127461 pRtree = (Rtree *)sqlite3_malloc(sizeof(Rtree)+nDb+nName+2);
127462 if( !pRtree ){
127463 return SQLITE_NOMEM;
127465 memset(pRtree, 0, sizeof(Rtree)+nDb+nName+2);
127466 pRtree->nBusy = 1;
127467 pRtree->base.pModule = &rtreeModule;
127468 pRtree->zDb = (char *)&pRtree[1];
127469 pRtree->zName = &pRtree->zDb[nDb+1];
127470 pRtree->nDim = (argc-4)/2;
127471 pRtree->nBytesPerCell = 8 + pRtree->nDim*4*2;
127472 pRtree->eCoordType = eCoordType;
127473 memcpy(pRtree->zDb, argv[1], nDb);
127474 memcpy(pRtree->zName, argv[2], nName);
127476 /* Figure out the node size to use. */
127477 rc = getNodeSize(db, pRtree, isCreate);
127479 /* Create/Connect to the underlying relational database schema. If
127480 ** that is successful, call sqlite3_declare_vtab() to configure
127481 ** the r-tree table schema.
127483 if( rc==SQLITE_OK ){
127484 if( (rc = rtreeSqlInit(pRtree, db, argv[1], argv[2], isCreate)) ){
127485 *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
127486 }else{
127487 char *zSql = sqlite3_mprintf("CREATE TABLE x(%s", argv[3]);
127488 char *zTmp;
127489 int ii;
127490 for(ii=4; zSql && ii<argc; ii++){
127491 zTmp = zSql;
127492 zSql = sqlite3_mprintf("%s, %s", zTmp, argv[ii]);
127493 sqlite3_free(zTmp);
127495 if( zSql ){
127496 zTmp = zSql;
127497 zSql = sqlite3_mprintf("%s);", zTmp);
127498 sqlite3_free(zTmp);
127500 if( !zSql ){
127501 rc = SQLITE_NOMEM;
127502 }else if( SQLITE_OK!=(rc = sqlite3_declare_vtab(db, zSql)) ){
127503 *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
127505 sqlite3_free(zSql);
127509 if( rc==SQLITE_OK ){
127510 *ppVtab = (sqlite3_vtab *)pRtree;
127511 }else{
127512 rtreeRelease(pRtree);
127514 return rc;
127519 ** Implementation of a scalar function that decodes r-tree nodes to
127520 ** human readable strings. This can be used for debugging and analysis.
127522 ** The scalar function takes two arguments, a blob of data containing
127523 ** an r-tree node, and the number of dimensions the r-tree indexes.
127524 ** For a two-dimensional r-tree structure called "rt", to deserialize
127525 ** all nodes, a statement like:
127527 ** SELECT rtreenode(2, data) FROM rt_node;
127529 ** The human readable string takes the form of a Tcl list with one
127530 ** entry for each cell in the r-tree node. Each entry is itself a
127531 ** list, containing the 8-byte rowid/pageno followed by the
127532 ** <num-dimension>*2 coordinates.
127534 static void rtreenode(sqlite3_context *ctx, int nArg, sqlite3_value **apArg){
127535 char *zText = 0;
127536 RtreeNode node;
127537 Rtree tree;
127538 int ii;
127540 UNUSED_PARAMETER(nArg);
127541 memset(&node, 0, sizeof(RtreeNode));
127542 memset(&tree, 0, sizeof(Rtree));
127543 tree.nDim = sqlite3_value_int(apArg[0]);
127544 tree.nBytesPerCell = 8 + 8 * tree.nDim;
127545 node.zData = (u8 *)sqlite3_value_blob(apArg[1]);
127547 for(ii=0; ii<NCELL(&node); ii++){
127548 char zCell[512];
127549 int nCell = 0;
127550 RtreeCell cell;
127551 int jj;
127553 nodeGetCell(&tree, &node, ii, &cell);
127554 sqlite3_snprintf(512-nCell,&zCell[nCell],"%lld", cell.iRowid);
127555 nCell = strlen(zCell);
127556 for(jj=0; jj<tree.nDim*2; jj++){
127557 sqlite3_snprintf(512-nCell,&zCell[nCell]," %f",(double)cell.aCoord[jj].f);
127558 nCell = strlen(zCell);
127561 if( zText ){
127562 char *zTextNew = sqlite3_mprintf("%s {%s}", zText, zCell);
127563 sqlite3_free(zText);
127564 zText = zTextNew;
127565 }else{
127566 zText = sqlite3_mprintf("{%s}", zCell);
127570 sqlite3_result_text(ctx, zText, -1, sqlite3_free);
127573 static void rtreedepth(sqlite3_context *ctx, int nArg, sqlite3_value **apArg){
127574 UNUSED_PARAMETER(nArg);
127575 if( sqlite3_value_type(apArg[0])!=SQLITE_BLOB
127576 || sqlite3_value_bytes(apArg[0])<2
127578 sqlite3_result_error(ctx, "Invalid argument to rtreedepth()", -1);
127579 }else{
127580 u8 *zBlob = (u8 *)sqlite3_value_blob(apArg[0]);
127581 sqlite3_result_int(ctx, readInt16(zBlob));
127586 ** Register the r-tree module with database handle db. This creates the
127587 ** virtual table module "rtree" and the debugging/analysis scalar
127588 ** function "rtreenode".
127590 SQLITE_PRIVATE int sqlite3RtreeInit(sqlite3 *db){
127591 const int utf8 = SQLITE_UTF8;
127592 int rc;
127594 rc = sqlite3_create_function(db, "rtreenode", 2, utf8, 0, rtreenode, 0, 0);
127595 if( rc==SQLITE_OK ){
127596 rc = sqlite3_create_function(db, "rtreedepth", 1, utf8, 0,rtreedepth, 0, 0);
127598 if( rc==SQLITE_OK ){
127599 void *c = (void *)RTREE_COORD_REAL32;
127600 rc = sqlite3_create_module_v2(db, "rtree", &rtreeModule, c, 0);
127602 if( rc==SQLITE_OK ){
127603 void *c = (void *)RTREE_COORD_INT32;
127604 rc = sqlite3_create_module_v2(db, "rtree_i32", &rtreeModule, c, 0);
127607 return rc;
127611 ** A version of sqlite3_free() that can be used as a callback. This is used
127612 ** in two places - as the destructor for the blob value returned by the
127613 ** invocation of a geometry function, and as the destructor for the geometry
127614 ** functions themselves.
127616 static void doSqlite3Free(void *p){
127617 sqlite3_free(p);
127621 ** Each call to sqlite3_rtree_geometry_callback() creates an ordinary SQLite
127622 ** scalar user function. This C function is the callback used for all such
127623 ** registered SQL functions.
127625 ** The scalar user functions return a blob that is interpreted by r-tree
127626 ** table MATCH operators.
127628 static void geomCallback(sqlite3_context *ctx, int nArg, sqlite3_value **aArg){
127629 RtreeGeomCallback *pGeomCtx = (RtreeGeomCallback *)sqlite3_user_data(ctx);
127630 RtreeMatchArg *pBlob;
127631 int nBlob;
127633 nBlob = sizeof(RtreeMatchArg) + (nArg-1)*sizeof(double);
127634 pBlob = (RtreeMatchArg *)sqlite3_malloc(nBlob);
127635 if( !pBlob ){
127636 sqlite3_result_error_nomem(ctx);
127637 }else{
127638 int i;
127639 pBlob->magic = RTREE_GEOMETRY_MAGIC;
127640 pBlob->xGeom = pGeomCtx->xGeom;
127641 pBlob->pContext = pGeomCtx->pContext;
127642 pBlob->nParam = nArg;
127643 for(i=0; i<nArg; i++){
127644 pBlob->aParam[i] = sqlite3_value_double(aArg[i]);
127646 sqlite3_result_blob(ctx, pBlob, nBlob, doSqlite3Free);
127651 ** Register a new geometry function for use with the r-tree MATCH operator.
127653 SQLITE_API int sqlite3_rtree_geometry_callback(
127654 sqlite3 *db,
127655 const char *zGeom,
127656 int (*xGeom)(sqlite3_rtree_geometry *, int, double *, int *),
127657 void *pContext
127659 RtreeGeomCallback *pGeomCtx; /* Context object for new user-function */
127661 /* Allocate and populate the context object. */
127662 pGeomCtx = (RtreeGeomCallback *)sqlite3_malloc(sizeof(RtreeGeomCallback));
127663 if( !pGeomCtx ) return SQLITE_NOMEM;
127664 pGeomCtx->xGeom = xGeom;
127665 pGeomCtx->pContext = pContext;
127667 /* Create the new user-function. Register a destructor function to delete
127668 ** the context object when it is no longer required. */
127669 return sqlite3_create_function_v2(db, zGeom, -1, SQLITE_ANY,
127670 (void *)pGeomCtx, geomCallback, 0, 0, doSqlite3Free
127674 #if !SQLITE_CORE
127675 SQLITE_API int sqlite3_extension_init(
127676 sqlite3 *db,
127677 char **pzErrMsg,
127678 const sqlite3_api_routines *pApi
127680 SQLITE_EXTENSION_INIT2(pApi)
127681 return sqlite3RtreeInit(db);
127683 #endif
127685 #endif
127687 /************** End of rtree.c ***********************************************/
127688 /************** Begin file icu.c *********************************************/
127690 ** 2007 May 6
127692 ** The author disclaims copyright to this source code. In place of
127693 ** a legal notice, here is a blessing:
127695 ** May you do good and not evil.
127696 ** May you find forgiveness for yourself and forgive others.
127697 ** May you share freely, never taking more than you give.
127699 *************************************************************************
127700 ** $Id: icu.c,v 1.7 2007/12/13 21:54:11 drh Exp $
127702 ** This file implements an integration between the ICU library
127703 ** ("International Components for Unicode", an open-source library
127704 ** for handling unicode data) and SQLite. The integration uses
127705 ** ICU to provide the following to SQLite:
127707 ** * An implementation of the SQL regexp() function (and hence REGEXP
127708 ** operator) using the ICU uregex_XX() APIs.
127710 ** * Implementations of the SQL scalar upper() and lower() functions
127711 ** for case mapping.
127713 ** * Integration of ICU and SQLite collation seqences.
127715 ** * An implementation of the LIKE operator that uses ICU to
127716 ** provide case-independent matching.
127719 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_ICU)
127721 /* Include ICU headers */
127722 #include <unicode/utypes.h>
127723 #include <unicode/uregex.h>
127724 #include <unicode/ustring.h>
127725 #include <unicode/ucol.h>
127728 #ifndef SQLITE_CORE
127729 SQLITE_EXTENSION_INIT1
127730 #else
127731 #endif
127734 ** Maximum length (in bytes) of the pattern in a LIKE or GLOB
127735 ** operator.
127737 #ifndef SQLITE_MAX_LIKE_PATTERN_LENGTH
127738 # define SQLITE_MAX_LIKE_PATTERN_LENGTH 50000
127739 #endif
127742 ** Version of sqlite3_free() that is always a function, never a macro.
127744 static void xFree(void *p){
127745 sqlite3_free(p);
127749 ** Compare two UTF-8 strings for equality where the first string is
127750 ** a "LIKE" expression. Return true (1) if they are the same and
127751 ** false (0) if they are different.
127753 static int icuLikeCompare(
127754 const uint8_t *zPattern, /* LIKE pattern */
127755 const uint8_t *zString, /* The UTF-8 string to compare against */
127756 const UChar32 uEsc /* The escape character */
127758 static const int MATCH_ONE = (UChar32)'_';
127759 static const int MATCH_ALL = (UChar32)'%';
127761 int iPattern = 0; /* Current byte index in zPattern */
127762 int iString = 0; /* Current byte index in zString */
127764 int prevEscape = 0; /* True if the previous character was uEsc */
127766 while( zPattern[iPattern]!=0 ){
127768 /* Read (and consume) the next character from the input pattern. */
127769 UChar32 uPattern;
127770 U8_NEXT_UNSAFE(zPattern, iPattern, uPattern);
127771 assert(uPattern!=0);
127773 /* There are now 4 possibilities:
127775 ** 1. uPattern is an unescaped match-all character "%",
127776 ** 2. uPattern is an unescaped match-one character "_",
127777 ** 3. uPattern is an unescaped escape character, or
127778 ** 4. uPattern is to be handled as an ordinary character
127780 if( !prevEscape && uPattern==MATCH_ALL ){
127781 /* Case 1. */
127782 uint8_t c;
127784 /* Skip any MATCH_ALL or MATCH_ONE characters that follow a
127785 ** MATCH_ALL. For each MATCH_ONE, skip one character in the
127786 ** test string.
127788 while( (c=zPattern[iPattern]) == MATCH_ALL || c == MATCH_ONE ){
127789 if( c==MATCH_ONE ){
127790 if( zString[iString]==0 ) return 0;
127791 U8_FWD_1_UNSAFE(zString, iString);
127793 iPattern++;
127796 if( zPattern[iPattern]==0 ) return 1;
127798 while( zString[iString] ){
127799 if( icuLikeCompare(&zPattern[iPattern], &zString[iString], uEsc) ){
127800 return 1;
127802 U8_FWD_1_UNSAFE(zString, iString);
127804 return 0;
127806 }else if( !prevEscape && uPattern==MATCH_ONE ){
127807 /* Case 2. */
127808 if( zString[iString]==0 ) return 0;
127809 U8_FWD_1_UNSAFE(zString, iString);
127811 }else if( !prevEscape && uPattern==uEsc){
127812 /* Case 3. */
127813 prevEscape = 1;
127815 }else{
127816 /* Case 4. */
127817 UChar32 uString;
127818 U8_NEXT_UNSAFE(zString, iString, uString);
127819 uString = u_foldCase(uString, U_FOLD_CASE_DEFAULT);
127820 uPattern = u_foldCase(uPattern, U_FOLD_CASE_DEFAULT);
127821 if( uString!=uPattern ){
127822 return 0;
127824 prevEscape = 0;
127828 return zString[iString]==0;
127832 ** Implementation of the like() SQL function. This function implements
127833 ** the build-in LIKE operator. The first argument to the function is the
127834 ** pattern and the second argument is the string. So, the SQL statements:
127836 ** A LIKE B
127838 ** is implemented as like(B, A). If there is an escape character E,
127840 ** A LIKE B ESCAPE E
127842 ** is mapped to like(B, A, E).
127844 static void icuLikeFunc(
127845 sqlite3_context *context,
127846 int argc,
127847 sqlite3_value **argv
127849 const unsigned char *zA = sqlite3_value_text(argv[0]);
127850 const unsigned char *zB = sqlite3_value_text(argv[1]);
127851 UChar32 uEsc = 0;
127853 /* Limit the length of the LIKE or GLOB pattern to avoid problems
127854 ** of deep recursion and N*N behavior in patternCompare().
127856 if( sqlite3_value_bytes(argv[0])>SQLITE_MAX_LIKE_PATTERN_LENGTH ){
127857 sqlite3_result_error(context, "LIKE or GLOB pattern too complex", -1);
127858 return;
127862 if( argc==3 ){
127863 /* The escape character string must consist of a single UTF-8 character.
127864 ** Otherwise, return an error.
127866 int nE= sqlite3_value_bytes(argv[2]);
127867 const unsigned char *zE = sqlite3_value_text(argv[2]);
127868 int i = 0;
127869 if( zE==0 ) return;
127870 U8_NEXT(zE, i, nE, uEsc);
127871 if( i!=nE){
127872 sqlite3_result_error(context,
127873 "ESCAPE expression must be a single character", -1);
127874 return;
127878 if( zA && zB ){
127879 sqlite3_result_int(context, icuLikeCompare(zA, zB, uEsc));
127884 ** This function is called when an ICU function called from within
127885 ** the implementation of an SQL scalar function returns an error.
127887 ** The scalar function context passed as the first argument is
127888 ** loaded with an error message based on the following two args.
127890 static void icuFunctionError(
127891 sqlite3_context *pCtx, /* SQLite scalar function context */
127892 const char *zName, /* Name of ICU function that failed */
127893 UErrorCode e /* Error code returned by ICU function */
127895 char zBuf[128];
127896 sqlite3_snprintf(128, zBuf, "ICU error: %s(): %s", zName, u_errorName(e));
127897 zBuf[127] = '\0';
127898 sqlite3_result_error(pCtx, zBuf, -1);
127902 ** Function to delete compiled regexp objects. Registered as
127903 ** a destructor function with sqlite3_set_auxdata().
127905 static void icuRegexpDelete(void *p){
127906 URegularExpression *pExpr = (URegularExpression *)p;
127907 uregex_close(pExpr);
127911 ** Implementation of SQLite REGEXP operator. This scalar function takes
127912 ** two arguments. The first is a regular expression pattern to compile
127913 ** the second is a string to match against that pattern. If either
127914 ** argument is an SQL NULL, then NULL Is returned. Otherwise, the result
127915 ** is 1 if the string matches the pattern, or 0 otherwise.
127917 ** SQLite maps the regexp() function to the regexp() operator such
127918 ** that the following two are equivalent:
127920 ** zString REGEXP zPattern
127921 ** regexp(zPattern, zString)
127923 ** Uses the following ICU regexp APIs:
127925 ** uregex_open()
127926 ** uregex_matches()
127927 ** uregex_close()
127929 static void icuRegexpFunc(sqlite3_context *p, int nArg, sqlite3_value **apArg){
127930 UErrorCode status = U_ZERO_ERROR;
127931 URegularExpression *pExpr;
127932 UBool res;
127933 const UChar *zString = sqlite3_value_text16(apArg[1]);
127935 (void)nArg; /* Unused parameter */
127937 /* If the left hand side of the regexp operator is NULL,
127938 ** then the result is also NULL.
127940 if( !zString ){
127941 return;
127944 pExpr = sqlite3_get_auxdata(p, 0);
127945 if( !pExpr ){
127946 const UChar *zPattern = sqlite3_value_text16(apArg[0]);
127947 if( !zPattern ){
127948 return;
127950 pExpr = uregex_open(zPattern, -1, 0, 0, &status);
127952 if( U_SUCCESS(status) ){
127953 sqlite3_set_auxdata(p, 0, pExpr, icuRegexpDelete);
127954 }else{
127955 assert(!pExpr);
127956 icuFunctionError(p, "uregex_open", status);
127957 return;
127961 /* Configure the text that the regular expression operates on. */
127962 uregex_setText(pExpr, zString, -1, &status);
127963 if( !U_SUCCESS(status) ){
127964 icuFunctionError(p, "uregex_setText", status);
127965 return;
127968 /* Attempt the match */
127969 res = uregex_matches(pExpr, 0, &status);
127970 if( !U_SUCCESS(status) ){
127971 icuFunctionError(p, "uregex_matches", status);
127972 return;
127975 /* Set the text that the regular expression operates on to a NULL
127976 ** pointer. This is not really necessary, but it is tidier than
127977 ** leaving the regular expression object configured with an invalid
127978 ** pointer after this function returns.
127980 uregex_setText(pExpr, 0, 0, &status);
127982 /* Return 1 or 0. */
127983 sqlite3_result_int(p, res ? 1 : 0);
127987 ** Implementations of scalar functions for case mapping - upper() and
127988 ** lower(). Function upper() converts its input to upper-case (ABC).
127989 ** Function lower() converts to lower-case (abc).
127991 ** ICU provides two types of case mapping, "general" case mapping and
127992 ** "language specific". Refer to ICU documentation for the differences
127993 ** between the two.
127995 ** To utilise "general" case mapping, the upper() or lower() scalar
127996 ** functions are invoked with one argument:
127998 ** upper('ABC') -> 'abc'
127999 ** lower('abc') -> 'ABC'
128001 ** To access ICU "language specific" case mapping, upper() or lower()
128002 ** should be invoked with two arguments. The second argument is the name
128003 ** of the locale to use. Passing an empty string ("") or SQL NULL value
128004 ** as the second argument is the same as invoking the 1 argument version
128005 ** of upper() or lower().
128007 ** lower('I', 'en_us') -> 'i'
128008 ** lower('I', 'tr_tr') -> 'ı' (small dotless i)
128010 ** http://www.icu-project.org/userguide/posix.html#case_mappings
128012 static void icuCaseFunc16(sqlite3_context *p, int nArg, sqlite3_value **apArg){
128013 const UChar *zInput;
128014 UChar *zOutput;
128015 int nInput;
128016 int nOutput;
128018 UErrorCode status = U_ZERO_ERROR;
128019 const char *zLocale = 0;
128021 assert(nArg==1 || nArg==2);
128022 if( nArg==2 ){
128023 zLocale = (const char *)sqlite3_value_text(apArg[1]);
128026 zInput = sqlite3_value_text16(apArg[0]);
128027 if( !zInput ){
128028 return;
128030 nInput = sqlite3_value_bytes16(apArg[0]);
128032 nOutput = nInput * 2 + 2;
128033 zOutput = sqlite3_malloc(nOutput);
128034 if( !zOutput ){
128035 return;
128038 if( sqlite3_user_data(p) ){
128039 u_strToUpper(zOutput, nOutput/2, zInput, nInput/2, zLocale, &status);
128040 }else{
128041 u_strToLower(zOutput, nOutput/2, zInput, nInput/2, zLocale, &status);
128044 if( !U_SUCCESS(status) ){
128045 icuFunctionError(p, "u_strToLower()/u_strToUpper", status);
128046 return;
128049 sqlite3_result_text16(p, zOutput, -1, xFree);
128053 ** Collation sequence destructor function. The pCtx argument points to
128054 ** a UCollator structure previously allocated using ucol_open().
128056 static void icuCollationDel(void *pCtx){
128057 UCollator *p = (UCollator *)pCtx;
128058 ucol_close(p);
128062 ** Collation sequence comparison function. The pCtx argument points to
128063 ** a UCollator structure previously allocated using ucol_open().
128065 static int icuCollationColl(
128066 void *pCtx,
128067 int nLeft,
128068 const void *zLeft,
128069 int nRight,
128070 const void *zRight
128072 UCollationResult res;
128073 UCollator *p = (UCollator *)pCtx;
128074 res = ucol_strcoll(p, (UChar *)zLeft, nLeft/2, (UChar *)zRight, nRight/2);
128075 switch( res ){
128076 case UCOL_LESS: return -1;
128077 case UCOL_GREATER: return +1;
128078 case UCOL_EQUAL: return 0;
128080 assert(!"Unexpected return value from ucol_strcoll()");
128081 return 0;
128085 ** Implementation of the scalar function icu_load_collation().
128087 ** This scalar function is used to add ICU collation based collation
128088 ** types to an SQLite database connection. It is intended to be called
128089 ** as follows:
128091 ** SELECT icu_load_collation(<locale>, <collation-name>);
128093 ** Where <locale> is a string containing an ICU locale identifier (i.e.
128094 ** "en_AU", "tr_TR" etc.) and <collation-name> is the name of the
128095 ** collation sequence to create.
128097 static void icuLoadCollation(
128098 sqlite3_context *p,
128099 int nArg,
128100 sqlite3_value **apArg
128102 sqlite3 *db = (sqlite3 *)sqlite3_user_data(p);
128103 UErrorCode status = U_ZERO_ERROR;
128104 const char *zLocale; /* Locale identifier - (eg. "jp_JP") */
128105 const char *zName; /* SQL Collation sequence name (eg. "japanese") */
128106 UCollator *pUCollator; /* ICU library collation object */
128107 int rc; /* Return code from sqlite3_create_collation_x() */
128109 assert(nArg==2);
128110 zLocale = (const char *)sqlite3_value_text(apArg[0]);
128111 zName = (const char *)sqlite3_value_text(apArg[1]);
128113 if( !zLocale || !zName ){
128114 return;
128117 pUCollator = ucol_open(zLocale, &status);
128118 if( !U_SUCCESS(status) ){
128119 icuFunctionError(p, "ucol_open", status);
128120 return;
128122 assert(p);
128124 rc = sqlite3_create_collation_v2(db, zName, SQLITE_UTF16, (void *)pUCollator,
128125 icuCollationColl, icuCollationDel
128127 if( rc!=SQLITE_OK ){
128128 ucol_close(pUCollator);
128129 sqlite3_result_error(p, "Error registering collation function", -1);
128134 ** Register the ICU extension functions with database db.
128136 SQLITE_PRIVATE int sqlite3IcuInit(sqlite3 *db){
128137 struct IcuScalar {
128138 const char *zName; /* Function name */
128139 int nArg; /* Number of arguments */
128140 int enc; /* Optimal text encoding */
128141 void *pContext; /* sqlite3_user_data() context */
128142 void (*xFunc)(sqlite3_context*,int,sqlite3_value**);
128143 } scalars[] = {
128144 {"regexp", 2, SQLITE_ANY, 0, icuRegexpFunc},
128146 {"lower", 1, SQLITE_UTF16, 0, icuCaseFunc16},
128147 {"lower", 2, SQLITE_UTF16, 0, icuCaseFunc16},
128148 {"upper", 1, SQLITE_UTF16, (void*)1, icuCaseFunc16},
128149 {"upper", 2, SQLITE_UTF16, (void*)1, icuCaseFunc16},
128151 {"lower", 1, SQLITE_UTF8, 0, icuCaseFunc16},
128152 {"lower", 2, SQLITE_UTF8, 0, icuCaseFunc16},
128153 {"upper", 1, SQLITE_UTF8, (void*)1, icuCaseFunc16},
128154 {"upper", 2, SQLITE_UTF8, (void*)1, icuCaseFunc16},
128156 {"like", 2, SQLITE_UTF8, 0, icuLikeFunc},
128157 {"like", 3, SQLITE_UTF8, 0, icuLikeFunc},
128159 {"icu_load_collation", 2, SQLITE_UTF8, (void*)db, icuLoadCollation},
128162 int rc = SQLITE_OK;
128163 int i;
128165 for(i=0; rc==SQLITE_OK && i<(int)(sizeof(scalars)/sizeof(scalars[0])); i++){
128166 struct IcuScalar *p = &scalars[i];
128167 rc = sqlite3_create_function(
128168 db, p->zName, p->nArg, p->enc, p->pContext, p->xFunc, 0, 0
128172 return rc;
128175 #if !SQLITE_CORE
128176 SQLITE_API int sqlite3_extension_init(
128177 sqlite3 *db,
128178 char **pzErrMsg,
128179 const sqlite3_api_routines *pApi
128181 SQLITE_EXTENSION_INIT2(pApi)
128182 return sqlite3IcuInit(db);
128184 #endif
128186 #endif
128188 /************** End of icu.c *************************************************/
128189 /************** Begin file fts3_icu.c ****************************************/
128191 ** 2007 June 22
128193 ** The author disclaims copyright to this source code. In place of
128194 ** a legal notice, here is a blessing:
128196 ** May you do good and not evil.
128197 ** May you find forgiveness for yourself and forgive others.
128198 ** May you share freely, never taking more than you give.
128200 *************************************************************************
128201 ** This file implements a tokenizer for fts3 based on the ICU library.
128203 ** $Id: fts3_icu.c,v 1.3 2008/09/01 18:34:20 danielk1977 Exp $
128206 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
128207 #ifdef SQLITE_ENABLE_ICU
128210 #include <unicode/ubrk.h>
128211 #include <unicode/utf16.h>
128213 typedef struct IcuTokenizer IcuTokenizer;
128214 typedef struct IcuCursor IcuCursor;
128216 struct IcuTokenizer {
128217 sqlite3_tokenizer base;
128218 char *zLocale;
128221 struct IcuCursor {
128222 sqlite3_tokenizer_cursor base;
128224 UBreakIterator *pIter; /* ICU break-iterator object */
128225 int nChar; /* Number of UChar elements in pInput */
128226 UChar *aChar; /* Copy of input using utf-16 encoding */
128227 int *aOffset; /* Offsets of each character in utf-8 input */
128229 int nBuffer;
128230 char *zBuffer;
128232 int iToken;
128236 ** Create a new tokenizer instance.
128238 static int icuCreate(
128239 int argc, /* Number of entries in argv[] */
128240 const char * const *argv, /* Tokenizer creation arguments */
128241 sqlite3_tokenizer **ppTokenizer /* OUT: Created tokenizer */
128243 IcuTokenizer *p;
128244 int n = 0;
128246 if( argc>0 ){
128247 n = strlen(argv[0])+1;
128249 p = (IcuTokenizer *)sqlite3_malloc(sizeof(IcuTokenizer)+n);
128250 if( !p ){
128251 return SQLITE_NOMEM;
128253 memset(p, 0, sizeof(IcuTokenizer));
128255 if( n ){
128256 p->zLocale = (char *)&p[1];
128257 memcpy(p->zLocale, argv[0], n);
128260 *ppTokenizer = (sqlite3_tokenizer *)p;
128262 return SQLITE_OK;
128266 ** Destroy a tokenizer
128268 static int icuDestroy(sqlite3_tokenizer *pTokenizer){
128269 IcuTokenizer *p = (IcuTokenizer *)pTokenizer;
128270 sqlite3_free(p);
128271 return SQLITE_OK;
128275 ** Prepare to begin tokenizing a particular string. The input
128276 ** string to be tokenized is pInput[0..nBytes-1]. A cursor
128277 ** used to incrementally tokenize this string is returned in
128278 ** *ppCursor.
128280 static int icuOpen(
128281 sqlite3_tokenizer *pTokenizer, /* The tokenizer */
128282 const char *zInput, /* Input string */
128283 int nInput, /* Length of zInput in bytes */
128284 sqlite3_tokenizer_cursor **ppCursor /* OUT: Tokenization cursor */
128286 IcuTokenizer *p = (IcuTokenizer *)pTokenizer;
128287 IcuCursor *pCsr;
128289 const int32_t opt = U_FOLD_CASE_DEFAULT;
128290 UErrorCode status = U_ZERO_ERROR;
128291 int nChar;
128293 UChar32 c;
128294 int iInput = 0;
128295 int iOut = 0;
128297 *ppCursor = 0;
128299 if( nInput<0 ){
128300 nInput = strlen(zInput);
128302 nChar = nInput+1;
128303 pCsr = (IcuCursor *)sqlite3_malloc(
128304 sizeof(IcuCursor) + /* IcuCursor */
128305 (nChar+1) * sizeof(int) + /* IcuCursor.aOffset[] */
128306 nChar * sizeof(UChar) /* IcuCursor.aChar[] */
128308 if( !pCsr ){
128309 return SQLITE_NOMEM;
128311 memset(pCsr, 0, sizeof(IcuCursor));
128312 pCsr->aOffset = (int *)&pCsr[1];
128313 pCsr->aChar = (UChar *)&pCsr->aOffset[nChar+1];
128315 pCsr->aOffset[iOut] = iInput;
128316 U8_NEXT(zInput, iInput, nInput, c);
128317 while( c>0 ){
128318 int isError = 0;
128319 c = u_foldCase(c, opt);
128320 U16_APPEND(pCsr->aChar, iOut, nChar, c, isError);
128321 if( isError ){
128322 sqlite3_free(pCsr);
128323 return SQLITE_ERROR;
128325 pCsr->aOffset[iOut] = iInput;
128327 if( iInput<nInput ){
128328 U8_NEXT(zInput, iInput, nInput, c);
128329 }else{
128330 c = 0;
128334 pCsr->pIter = ubrk_open(UBRK_WORD, p->zLocale, pCsr->aChar, iOut, &status);
128335 if( !U_SUCCESS(status) ){
128336 sqlite3_free(pCsr);
128337 return SQLITE_ERROR;
128339 pCsr->nChar = iOut;
128341 ubrk_first(pCsr->pIter);
128342 *ppCursor = (sqlite3_tokenizer_cursor *)pCsr;
128343 return SQLITE_OK;
128347 ** Close a tokenization cursor previously opened by a call to icuOpen().
128349 static int icuClose(sqlite3_tokenizer_cursor *pCursor){
128350 IcuCursor *pCsr = (IcuCursor *)pCursor;
128351 ubrk_close(pCsr->pIter);
128352 sqlite3_free(pCsr->zBuffer);
128353 sqlite3_free(pCsr);
128354 return SQLITE_OK;
128358 ** Extract the next token from a tokenization cursor.
128360 static int icuNext(
128361 sqlite3_tokenizer_cursor *pCursor, /* Cursor returned by simpleOpen */
128362 const char **ppToken, /* OUT: *ppToken is the token text */
128363 int *pnBytes, /* OUT: Number of bytes in token */
128364 int *piStartOffset, /* OUT: Starting offset of token */
128365 int *piEndOffset, /* OUT: Ending offset of token */
128366 int *piPosition /* OUT: Position integer of token */
128368 IcuCursor *pCsr = (IcuCursor *)pCursor;
128370 int iStart = 0;
128371 int iEnd = 0;
128372 int nByte = 0;
128374 while( iStart==iEnd ){
128375 UChar32 c;
128377 iStart = ubrk_current(pCsr->pIter);
128378 iEnd = ubrk_next(pCsr->pIter);
128379 if( iEnd==UBRK_DONE ){
128380 return SQLITE_DONE;
128383 while( iStart<iEnd ){
128384 int iWhite = iStart;
128385 U16_NEXT(pCsr->aChar, iWhite, pCsr->nChar, c);
128386 if( u_isspace(c) ){
128387 iStart = iWhite;
128388 }else{
128389 break;
128392 assert(iStart<=iEnd);
128396 UErrorCode status = U_ZERO_ERROR;
128397 if( nByte ){
128398 char *zNew = sqlite3_realloc(pCsr->zBuffer, nByte);
128399 if( !zNew ){
128400 return SQLITE_NOMEM;
128402 pCsr->zBuffer = zNew;
128403 pCsr->nBuffer = nByte;
128406 u_strToUTF8(
128407 pCsr->zBuffer, pCsr->nBuffer, &nByte, /* Output vars */
128408 &pCsr->aChar[iStart], iEnd-iStart, /* Input vars */
128409 &status /* Output success/failure */
128411 } while( nByte>pCsr->nBuffer );
128413 *ppToken = pCsr->zBuffer;
128414 *pnBytes = nByte;
128415 *piStartOffset = pCsr->aOffset[iStart];
128416 *piEndOffset = pCsr->aOffset[iEnd];
128417 *piPosition = pCsr->iToken++;
128419 return SQLITE_OK;
128423 ** The set of routines that implement the simple tokenizer
128425 static const sqlite3_tokenizer_module icuTokenizerModule = {
128426 0, /* iVersion */
128427 icuCreate, /* xCreate */
128428 icuDestroy, /* xCreate */
128429 icuOpen, /* xOpen */
128430 icuClose, /* xClose */
128431 icuNext, /* xNext */
128435 ** Set *ppModule to point at the implementation of the ICU tokenizer.
128437 SQLITE_PRIVATE void sqlite3Fts3IcuTokenizerModule(
128438 sqlite3_tokenizer_module const**ppModule
128440 *ppModule = &icuTokenizerModule;
128443 #endif /* defined(SQLITE_ENABLE_ICU) */
128444 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
128446 /************** End of fts3_icu.c ********************************************/